HttpClient

  • HttpClient 4.1 之後再也不在Apache Commons下,而是位於Apache HttpComponentshtml

    org.apache.commons.httpclient.HttpClient與org.apache.http.client.HttpClient的區別:
    Commons的HttpClient項目如今是生命的盡頭,再也不被開發,已被Apache HttpComponents項目HttpClient和的HttpCore
    模組取代,提供更好的性能和更大的靈活性。apache

  • 目前版本爲HttpClient 4.5.5 (GA)
  • HttpClient的官網示例頁面
  • 通常用法post

public final static void main(String[] args) throws Exception {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpGet httpget = new HttpGet("http://httpbin.org/get");

            System.out.println("Executing request " + httpget.getRequestLine());
            CloseableHttpResponse response = httpclient.execute(httpget);
            try {
                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());

                // Get hold of the response entity
                HttpEntity entity = response.getEntity();

                // If the response does not enclose an entity, there is no need
                // to bother about connection release
                if (entity != null) {
                    InputStream instream = entity.getContent();
                    try {
                        instream.read();
                        // do something useful with the response

                        byte[] bytes = new byte[0];
                        bytes = new byte[instream.available()];
                        instream.read(bytes);
                        String str = new String(bytes);
                        System.out.println("str: " + str);

                        String string = EntityUtils.toString(entity, "UTF-8");
                        System.out.println("string: " + string);
                    } catch (IOException ex) {
                        // In case of an IOException the connection will be released
                        // back to the connection manager automatically
                        throw ex;
                    } finally {
                        // Closing the input stream will trigger connection release
                        instream.close();
                    }
                }
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
    }
  • 最簡單post請求
public static void main(String[] args) throws Exception {
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        formparams.add(new BasicNameValuePair("account", ""));
        formparams.add(new BasicNameValuePair("password", ""));
        HttpEntity reqEntity = new UrlEncodedFormEntity(formparams, "UTF-8");

        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000)// 1、鏈接超時:connectionTimeout-->指的是鏈接一個url的鏈接等待時間
                .setSocketTimeout(5000)// 2、讀取數據超時:SocketTimeout-->指的是鏈接上一個url,獲取response的返回等待時間
                .setConnectionRequestTimeout(5000).build();

        HttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost("http://cnivi.com.cn/login");
        post.setEntity(reqEntity);
        post.setConfig(requestConfig);
        HttpResponse response = client.execute(post);

        if (response.getStatusLine().getStatusCode() == 200) {
            HttpEntity resEntity = response.getEntity();
            String message = EntityUtils.toString(resEntity, "UTF-8");
            System.out.println(message);
        } else {
            System.out.println("請求失敗");
        }
    }
  • 解決參數亂碼問題
HttpEntity entity = new StringEntity(xml, ContentType.create("text/xml", Consts.UTF_8));

參考資料

相關文章
相關標籤/搜索
本站公眾號
   歡迎關注本站公眾號,獲取更多信息