主要知識(shí)點(diǎn):
- 不能緩存服務(wù)器響應(yīng),一般用于抓包
- 相較于HttpUrlConnection來(lái)說(shuō)处硬,不需要關(guān)心各種輸入輸出流的轉(zhuǎn)換
- 步驟:獲取HttpUrlConnection敬特,獲取HttpGet他挎、HttpPost烫葬、execute獲取響應(yīng)(判斷狀態(tài)碼)界弧、對(duì)響應(yīng)結(jié)果(Entity)進(jìn)行轉(zhuǎn)換
- HttpPost/HttpGet.setHeader設(shè)置請(qǐng)求頭,從response獲取cookie等響應(yīng)頭信息
源碼:
public class HttpClientRequest {
public String getData(String path) throws Exception{
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(path);
HttpResponse response = client.execute(httpGet);
if(response.getStatusLine().getStatusCode()==200){
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity,"utf-8");
return data;
}
return null;
}
public String postData(String path,List<NameValuePair> parameters) throws Exception{
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(path);
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters);
httpPost.setEntity(entity);
HttpResponse response = client.execute(httpPost);
if(response.getStatusLine().getStatusCode()==200){
HttpEntity responseEntity = response.getEntity();
String data = EntityUtils.toString(responseEntity,"utf-8");
return data;
}
return null;
}
}
調(diào)用:
new Thread(){
public void run() {
try {
HttpClientRequest hcr = new HttpClientRequest();
/******************GET方式請(qǐng)求*********************/
//String str =hcr.getData("http://192.168.1.183/test.php?name=123");
/******************POST方式請(qǐng)求*********************/
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("name", "xiaoming"));
String str = hcr.postData("http://192.168.1.183/test.php",parameters);
System.out.println(str);
} catch (Exception e) {
e.printStackTrace();
}
};
}.start();
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者