httpclient4.3.x模擬post及get請求

jopen 10年前發布 | 129K 次閱讀 網絡工具包 httpclient4

在web開發中,我們經常需要模擬post及get請求,現在網上比較多的是使用httpclient3.x,然而httpclient4.x已經發布好幾年了,而且4.x之后改名為HttpComponents,顯然是今后的趨勢.
Apache HttpComponents4.x中的HttpClient是一個很好的工具,它符合HTTP1.1規范,是基于HttpCore類包的實現。但是 HttpComponents4.x較之前httpclient3.x的API變化比較大,已經分為 HttpClient,HttpCore,HttpAsyncClient等多個組件,在模擬post及get請求時的編碼也出現了較大的變化.

下面是httpclient4.3.4模擬get請求的例程

public void requestGet(String urlWithParams) throws Exception {
        CloseableHttpClient httpclient = HttpClientBuilder.create().build();

    //HttpGet httpget = new HttpGet("http://www.baidu.com/");
    HttpGet httpget = new HttpGet(urlWithParams);   
    //配置請求的超時設置
    RequestConfig requestConfig = RequestConfig.custom()  
            .setConnectionRequestTimeout(50)
            .setConnectTimeout(50)  
            .setSocketTimeout(50).build();  
    httpget.setConfig(requestConfig); 

    CloseableHttpResponse response = httpclient.execute(httpget);        
    System.out.println("StatusCode -> " + response.getStatusLine().getStatusCode());

    HttpEntity entity = response.getEntity();        
    String jsonStr = EntityUtils.toString(entity);//, "utf-8");
    System.out.println(jsonStr);

    httpget.releaseConnection();

}</pre>httpclient4.3.4模擬post請求的例程

public void requestPost(String url,List<NameValuePair> params) throws ClientProtocolException, IOException {
    CloseableHttpClient httpclient = HttpClientBuilder.create().build();

HttpPost httppost = new HttpPost(url);
    httppost.setEntity(new UrlEncodedFormEntity(params));

    CloseableHttpResponse response = httpclient.execute(httppost);
    System.out.println(response.toString());

    HttpEntity entity = response.getEntity();
    String jsonStr = EntityUtils.toString(entity, "utf-8");
    System.out.println(jsonStr);

    httppost.releaseConnection();

}</pre>運行post方法時,可以

public static void main(String[] args){
    try {
        String loginUrl = "http://localhost:8080/yours";
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("name", "zhang"));
        params.add(new BasicNameValuePair("passwd", "123"));

    requestPost(loginUrl,params);
} catch (ClientProtocolException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

}</pre>最后給出httpcomponents官網的例程
http://hc.apache.org/httpcomponents-core-4.3.x/examples.html

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!