HttpClient

1:概述

HttpClient是HttpComponents(簡稱爲hc)項目其中的一部份,訪問地址:http://hc.apache.org/



HttpClient是一個代碼級的Http客戶端工具,能夠使用它模擬瀏覽器向Http服務器發送請求。使用HttpClient還須要HttpCore.後者包括Http請求與Http響應的代碼封裝。

html

    public final static void main(String[] args) throws Exception {
        HttpClient httpclient = new DefaultHttpClient();
        try {
            HttpGet httpget = new HttpGet("http://www.apache.org/");
            System.out.println("executing request " + httpget.getURI());
            HttpResponse response = httpclient.execute(httpget);
            HttpEntity entity = response.getEntity();

            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            if (entity != null) {
                System.out.println("Response content length: " + entity.getContentLength());
            }
            System.out.println("----------------------------------------");

            InputStream inSm = entity.getContent();
            Scanner inScn = new Scanner(inSm);
            while (inScn.hasNextLine()) {
                System.out.println(inScn.nextLine());
            }
            // Do not feel like reading the response body
            // Call abort on the request object
            httpget.abort();
        } finally {
            // When HttpClient instance is no longer needed,
            // shut down the connection manager to ensure
            // immediate deallocation of all system resources
            httpclient.getConnectionManager().shutdown();
        }
    }

  
httpcore:EntityUtils.toString(httpEntity)
讀取response響應內容部分,也能夠藉助於 httpcore-4.1.2.jar 裏面的java

Java代碼 複製代碼 收藏代碼
  1. String content = EntityUtils.toString(httpEntity); 
String content = EntityUtils.toString(httpEntity);
/**
 * User: liuwentao
 * Time: 12-1-25 下午1:23
 */
public class Demo1 {

    /**
     * 用 get 方法訪問 www.apache.org 並返回內容
     *
     * @param args
     */
    public static void main(String[] args) {
        //建立默認的 HttpClient 實例
        HttpClient httpClient = new DefaultHttpClient();
        try {
            //建立 httpUriRequest 實例
            HttpGet httpGet = new HttpGet("http://www.apache.org/");
            System.out.println("uri=" + httpGet.getURI());

            //執行 get 請求
            HttpResponse httpResponse = httpClient.execute(httpGet);

            //獲取響應實體
            HttpEntity httpEntity = httpResponse.getEntity();
            //打印響應狀態
            System.out.println(httpResponse.getStatusLine());
            if (httpEntity != null) {
                //響應內容的長度
                long length = httpEntity.getContentLength();
                //響應內容
                String content = EntityUtils.toString(httpEntity);

                System.out.println("Response content length:" + length);
                System.out.println("Response content:" + content);
            }

            //有些教程裏沒有下面這行
            httpGet.abort();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //關閉鏈接,釋放資源
            httpClient.getConnectionManager().shutdown();
        }
    }
}

  執行結果:



httpget.setHeader

1:分析請求包中這六個頭信息



2:代碼apache

    /**
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) {
        HttpClient httpClient = new DefaultHttpClient();
        try {
            HttpGet httpget = new HttpGet("http://www.iteye.com");

            httpget.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
            httpget.setHeader("Accept-Language", "zh-cn,zh;q=0.5");
            httpget.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 5.1; rv:7.0.1) Gecko/20100101 Firefox/7.0.1)");
            httpget.setHeader("Accept-Encoding", "gzip, deflate");
            httpget.setHeader("Accept-Charset", "GB2312,utf-8;q=0.7,*;q=0.7");
            httpget.setHeader("Host", "www.iteye.com");
            httpget.setHeader("Connection", "Keep-Alive");

            HttpResponse response = httpClient.execute(httpget);
            HttpEntity entity = response.getEntity();

            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            if (entity != null) {
                System.out.println("Response content length: " + entity.getContentLength());
            }
            System.out.println("----------------------------------------");

            InputStream inSm = entity.getContent();
            Scanner inScn = new Scanner(inSm);
            while (inScn.hasNextLine()) {
                System.out.println(inScn.nextLine());
            }
            // Do not feel like reading the response body
            // Call abort on the request object
            httpget.abort();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // When HttpClient instance is no longer needed,
            // shut down the connection manager to ensure
            // immediate deallocation of all system resources
            httpClient.getConnectionManager().shutdown();
        }
    }

  3:效果

以上亂碼是因爲瀏覽器

Java代碼 複製代碼 收藏代碼
    1. httpget.setHeader("Accept-Encoding", "gzip, deflate");   
註釋掉這行
/**
 * User: liuwentao
 * Time: 12-1-25 下午1:23
 */
public class Demo3 {

    /**
     * 用 get 方法訪問 www.baidu.com 並返回內容
     *
     * @param args
     */
    public static void main(String[] args) {
        //建立默認的 HttpClient 實例
        HttpClient httpClient = new DefaultHttpClient();

        try {
            //建立 httpUriRequest 實例
            HttpGet httpGet = new HttpGet("http://www.iteye.com");

            httpGet.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
            httpGet.setHeader("Accept-Language", "zh-cn,zh;q=0.5");
            httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 5.1; rv:7.0.1) Gecko/20100101 Firefox/7.0.1)");
//            httpGet.setHeader("Accept-Encoding", "gzip, deflate");
            httpGet.setHeader("Accept-Charset", "GB2312,utf-8;q=0.7,*;q=0.7");
            httpGet.setHeader("Host", "www.iteye.com");
            httpGet.setHeader("Connection", "Keep-Alive");
            System.out.println("uri=" + httpGet.getURI());

            //執行 get 請求
            HttpResponse httpResponse = httpClient.execute(httpGet);

            //獲取響應實體
            HttpEntity httpEntity = httpResponse.getEntity();
            //打印響應狀態
            System.out.println(httpResponse.getStatusLine());
            if (httpEntity != null) {
                //響應內容的長度
                long length = httpEntity.getContentLength();
                //響應內容
                String content = EntityUtils.toString(httpEntity);

                System.out.println("Response content length:" + length);
                System.out.println("Response content:" + content);
            }

            //有些教程裏沒有下面這行
            httpGet.abort();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //關閉鏈接,釋放資源
            httpClient.getConnectionManager().shutdown();
        }
    }
}

  效果:


用post方法訪問本地應用根據傳遞參數不一樣,返回不一樣結果服務器

    <servlet>
        <servlet-name>Test1Servlet</servlet-name>
        <servlet-class>demo.servlet.Test1Servlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Test1Servlet</servlet-name>
        <url-pattern>/test1Servlet</url-pattern>
    </servlet-mapping>

  

/**
 * User: liuwentao
 * Time: 11-12-25 下午1:08
 */
public class Test1Servlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //接收地址欄參數
        String param1 = request.getParameter("param1");
        //輸出
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.write("你傳遞來的參數param1=" + param1);
        out.close();
    }
}

  

/**
 * User: liuwentao
 * Time: 12-1-25 下午1:23
 */
public class Demo2 {

    /**
     * 用post方法訪問本地應用根據傳遞參數不一樣,返回不一樣結果
     *
     * @param args
     */
    public static void main(String[] args) {
        //建立默認的 HttpClient 實例
        HttpClient httpClient = new DefaultHttpClient();

        HttpPost httpPost = new HttpPost("http://localhost:86/test1Servlet");

        List<NameValuePair> formParams = new ArrayList<NameValuePair>();
        formParams.add(new BasicNameValuePair("param1", "劉文濤"));
        UrlEncodedFormEntity urlEncodedFormEntity;

        try {
            urlEncodedFormEntity = new UrlEncodedFormEntity(formParams, "UTF-8");
            httpPost.setEntity(urlEncodedFormEntity);
            System.out.println("execurting request:" + httpPost.getURI());
            HttpResponse httpResponse = null;
            httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            if (httpEntity != null) {
                String content = EntityUtils.toString(httpEntity, "UTF-8");
                System.out.println("Response content:" + content);
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //關閉鏈接,釋放資源
            httpClient.getConnectionManager().shutdown();
        }
    }
}

  結果:

app

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