HttpClient使用詳解

HttpClient的主要功能:

  • 實現了全部 HTTP 的方法(GET、POST、PUT、HEAD、DELETE、HEAD、OPTIONS 等)
  • 支持 HTTPS 協議
  • 支持代理服務器(Nginx等)等
  • 支持自動(跳轉)轉向
  • 等等

 

引入依賴

<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.5</version>
</dependency>

 

使用詳解

1. get方法

public class GetUtils {

//無參方式
public void get(String url) {
getWithParams(url, new HashMap<>());
}

//有參方式
public void getWithParams(String url, Map<String, Object> params) {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
CloseableHttpResponse response = null;
try {
// 建立Get請求
url = joinParam(url, params);
HttpGet httpGet = new HttpGet(url);
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(2000) //服務器響應超時時間
.setConnectTimeout(2000) //鏈接服務器超時時間
.build();
httpGet.setConfig(requestConfig);
// 由客戶端執行(發送)Get請求
response = httpClient.execute(httpGet);
// 從響應模型中獲取響應實體
HttpEntity responseEntity = response.getEntity();
System.out.println("響應狀態爲:" + response.getStatusLine());
if (responseEntity != null) {
System.out.println("響應內容長度爲:" + responseEntity.getContentLength());
System.out.println("響應內容爲:" + EntityUtils.toString(responseEntity));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// 釋放資源
if (httpClient != null) {
httpClient.close();
}
if (response != null) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

private static String joinParam(String url, Map<String, Object> params) {
if (params == null || params.size() == 0) {
return url;
}

StringBuilder urlBuilder = new StringBuilder(url);
urlBuilder.append("?");

int counter = 0;
for (Map.Entry<String,Object> entry : params.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
if (key == null) {
continue;
}

if (counter == 0) {
urlBuilder.append(key).append("=").append(value);
} else {
urlBuilder.append("&").append(key).append("=").append(value);
}
counter++;
}

return urlBuilder.toString();
}

}

 

2. post方法

post請求有兩種方式傳參,一種是普通參數,一種是對象參數。普通參數傳參方式和上面的get請求相同,對象參數須要使用setEntity()方法設置,同時須要指定請求的content-typegit

如下兩段代碼均爲對象方式傳參github

2.1 content-type爲:application/x-www-form-urlencoded

public class PostUtils {

    public void post(String url) {
        postWithParams(url, new HashMap<>());
    }

    public void postWithParams(String url, Map<String, String> params) {
        List<NameValuePair> pairs = generatePairs(params);

        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        CloseableHttpResponse response = null;
        try {
            HttpPost httpPost = new HttpPost(url);
            RequestConfig requestConfig = RequestConfig.custom()
                    .setSocketTimeout(2000) //服務器響應超時時間
                    .setConnectTimeout(2000) //鏈接服務器超時時間
                    .build();
            httpPost.setConfig(requestConfig);

            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs, "utf-8");
            httpPost.setEntity(entity);
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
            // 由客戶端執行(發送)請求
            response = httpClient.execute(httpPost);
            System.out.println("響應狀態爲:" + response.getStatusLine());
            // 從響應模型中獲取響應實體
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                System.out.println("響應內容長度爲:" + responseEntity.getContentLength());
                System.out.println("響應內容爲:" + EntityUtils.toString(responseEntity));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // 釋放資源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private List<NameValuePair> generatePairs(Map<String, String> params) {
        if (params == null || params.size() == 0) {
            return Collections.emptyList();
        }

        List<NameValuePair> pairs = new ArrayList<>();
        for (Map.Entry<String,String> entry : params.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            if (key == null) {
                continue;
            }

            pairs.add(new BasicNameValuePair(key, value));
        }

        return pairs;
    }

}

 

2.1 content-type爲:application/json

public void postWithParams(String url, UserEntity userEntity) {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        CloseableHttpResponse response = null;
        try {
            HttpPost httpPost = new HttpPost(url);
            RequestConfig requestConfig = RequestConfig.custom()
                    .setSocketTimeout(2000) //服務器響應超時時間
                    .setConnectTimeout(2000) //鏈接服務器超時時間
                    .build();
            httpPost.setConfig(requestConfig);

            StringEntity entity = new StringEntity(JSON.toJSONString(userEntity), "utf-8");//也能夠直接使用JSONObject
            httpPost.setEntity(entity);
            httpPost.setHeader("Content-Type", "application/json;charset=utf8");
            // 由客戶端執行(發送)請求
            response = httpClient.execute(httpPost);
            System.out.println("響應狀態爲:" + response.getStatusLine());
            // 從響應模型中獲取響應實體
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                System.out.println("響應內容長度爲:" + responseEntity.getContentLength());
                System.out.println("響應內容爲:" + EntityUtils.toString(responseEntity));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // 釋放資源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

 

其餘

提示:網上有不少開源的http工具類,Github上Star很是多的一個HttpClient的工具類是httpclientutil,該工具類的編寫者封裝了不少功能在裏面,若是apache

           不是有什麼特殊的需求的話,徹底能夠直接使用該工具類。使用方式很簡單,可詳見https://github.com/Arronlong/httpclientutiljson

相關文章
相關標籤/搜索