主要知识点:
- 不能缓存服务器响应,一般用于抓包
- 相较于HttpUrlConnection来说,不需要关心各种输入输出流的转换
- 步骤:获取HttpUrlConnection,获取HttpGet、HttpPost、execute获取响应(判断状态码)、对响应结果(Entity)进行转换
- HttpPost/HttpGet.setHeader设置请求头,从response获取cookie等响应头信息
源码:
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;
}
}
调用:
new Thread(){
public void run() {
try {
HttpClientRequest hcr = new HttpClientRequest();
/******************GET方式请求*********************/
//String str =hcr.getData("http://192.168.1.183/test.php?name=123");
/******************POST方式请求*********************/
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();