java發起get請求

java發起get請求

學習記錄:
話不多說直接上代碼:

package com.jl.chromeTest;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;

/**
 * get請求測試
 * @author liujilong
 * @since 2019-7-18 10:26:49
 */
public class Test {

    @org.junit.Test
    public void test() throws Exception{
        String result = get("http://www.baidu.com");
        System.out.println("result====="+result);
    }

    /**
     * get請求
     * @param url
     * @return
     * @throws Exception
     */
    public  String get(String url) throws Exception {
        String content = null;
        URLConnection urlConnection = new URL(url).openConnection();
        HttpURLConnection connection = (HttpURLConnection) urlConnection;
        connection.setRequestMethod("GET");
        //連接
        connection.connect();
        //得到響應碼
        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader
                    (connection.getInputStream(), StandardCharsets.UTF_8));
            StringBuilder bs = new StringBuilder();
            String l;
            while ((l = bufferedReader.readLine()) != null) {
                bs.append(l).append("\n");
            }
            content = bs.toString();
        }
        return content;
    }
}

結果如圖:

在這裏插入圖片描述
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章