HttpClient
利用apache的虛擬客戶端包獲取某個地址的內容 import javaioUnsupportedEncodingException;
import javautilHashSet;
import javautilIterator;
import javautilSet;
import javautilregexMatcher;
import javautilregexPattern;
import mons;
import mons;
import mons;
public class catchMain {
/** *//**
* @param args
*/
public static void main(String[] args) {
String url = ;
String keyword=食;
String response=createhttpClient(urlkeyword);
}
public static String createhttpClient(String urlString param){
HttpClient client = new HttpClient();
String response=null;
String keyword=null;
PostMethod postMethod = new PostMethod(url);
try {
if(param!=null)
keyword = new String(paramgetBytes(gb)ISO);
} catch (UnsupportedEncodingException e) {
// TODO Autogenerated catch block
eprintStackTrace();
}
NameValuePair[] data = { new NameValuePair(keyword keyword) };
// 將表單的值放入postMethod中
postMethodsetRequestBody(data);
try {
int statusCode = clientexecuteMethod(postMethod);
response = new String(postMethodgetResponseBodyAsString()
getBytes(ISO) GBK);
} catch (Exception e) {
eprintStackTrace();
}
return response;
}
java自帶的HttpURLConnection
public static String getPageContent(String strUrl String strPostRequest
int maxLength) {
//讀取結果網頁
StringBuffer buffer = new StringBuffer();
SystemsetProperty(clientdefaultConnectTimeout );
SystemsetProperty(clientdefaultReadTimeout );
try {
URL newUrl = new URL(strUrl);
HttpURLConnection hConnect = (HttpURLConnection) newUrl
openConnection();
//POST方式的額外數據
if (strPostRequestlength() > ) {
hConnectsetDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(hConnect
getOutputStream());
outwrite(strPostRequest);
outflush();
outclose();
}
//讀取內容
BufferedReader rd = new BufferedReader(new InputStreamReader(
hConnectgetInputStream()));
int ch;
for (int length = ; (ch = rdread()) >
&& (maxLength <= || length < maxLength); length++)
bufferappend((char) ch);
rdclose();
hConnectdisconnect();
return buffertoString()trim();
} catch (Exception e) {
// return 錯誤:讀取網頁失敗!;
return null;
}
}
From:http://tw.wingwit.com/Article/program/Java/hx/201311/26339.html