搜尋此網誌

2013年6月12日 星期三

【Java】【轉載】 Apache HttpClient 4.x 使用 GET, POST 範例

在看範例之前先把一些重要連結整理給大家: 
想知道這次到底更動了哪些東西可以看:Apache HttpClient 首頁
官方的 Tutorial 在:Apache HttpClient Tutorial 
而 API DOC、說明文件則在:Apache HttpClient apidocs

相關的程式碼、jar 檔在:HttpComponents HttpClient 4.0 (GA)
注意,在寫程式前必需先將四個 jar 檔正確匯入,最後兩個(*)是選用,

commons-logging-x.x.x.jar
commons-codec-x.x.x.jar
httpcore-x.x.x.jar
httpclient-x.x.x.jar
apache-mime4j-x.x.x.jar (*)
httpmime-x.x.x.jar (*)
說了這麼多,以下是程式的範例,
第一個是傳回在 google 查詢 httpclient 的結果。
第二則是傳回台大圖書館查詢 Head First Java 的結果。

  • 實際安裝jar版本:
    • apache-mime4j.jar
    • commons-codec-1.4.jar
    • commons-logging-1.1.1.jar
    • httpclient-4.0.1.jar
    • httpclient-4.1.jar
    • httpcore-4.1.jar
    • httpmime-4.1.jar


package Crawler;

import java.io.IOException;
import java.util.ArrayList;

import org.apache.http.HttpStatus;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

/**
 * Apache HttpClient 4.x 使用 GET, POST 查詢網頁的範例
 * 
 * 
 */
public class Crawler extends DefaultHttpClient {

 public static void main(String[] args) throws IOException {

  DefaultHttpClient demo = new DefaultHttpClient();
  demo.getParams().setParameter("http.protocol.content-charset", "UTF-8");

  // Get Request Example,取得 google 查詢 httpclient 的結果
  HttpGet httpGet = new HttpGet(http://www.google.com.tw/search?q=httpclinet");
  HttpResponse response = demo.execute(httpGet);
  String responseString = EntityUtils.toString(response.getEntity());
  if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
   // 如果回傳是200 OK 的話才輸出
   System.out.println(responseString);
  } else {
   System.out.println(response.getStatusLine());
  }
 
   // Post Request Example,查詢台大圖書館書籍
   ArrayList<NameValuePair> pairList = new ArrayList<NameValuePair>();
   pairList.add(new BasicNameValuePair("searchtype", "t"));
   pairList.add(new BasicNameValuePair("searchscope", "keyword"));
   pairList.add(new BasicNameValuePair("searcharg", "Head First Java"));
   pairList.add(new BasicNameValuePair("SORT", "D"));
  
   HttpPost httpPost = new
   HttpPost("http://tulips.ntu.edu.tw:1081/search*cht/a?");
   StringEntity entity = new
   StringEntity(URLEncodedUtils.format(pairList, "UTF-8"));
   httpPost.setEntity(entity);
   response = demo.execute(httpPost);
   responseString = EntityUtils.toString(response.getEntity());
   if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
   // 如果回傳是200 OK 的話才輸出
   System.out.println(responseString);
   } else {
   System.out.println(response.getStatusLine());
   }
 }
}

沒有留言: