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

在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請求的例程
html

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();
}

httpclient4.3.4模擬post請求的例程
java

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();
}

運行post方法時,能夠
web

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();
    }
}

最後給出httpcomponents官網的例程
http://hc.apache.org/httpcomponents-core-4.3.x/examples.html
apache

相關文章
相關標籤/搜索