package com.igs.webShop.web.util;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* Created by dbz on 2016/4/5.
*/
public class HttpClientUtil {
/**
*
* @param url 请求的地址
* @param params 请求参数为Map<String,String>,最终会把map里的参数以&拼接起来
* @return
*/
public static String post(String url,Map<String,String> params){
//创建HttpClient对象
HttpClient client=new DefaultHttpClient();
//创建httpPost对象并封装请求参数对象
HttpPost post=postForm(url,params);
String result=null;
//调用发送请求方法
result=invoke(client,post);
//当HttpClient的实例不再需要时,可以使用连接管理器关闭
client.getConnectionManager().shutdown();
return result;
}
public static String get(String url,Map<String,String> params){
DefaultHttpClient client=new DefaultHttpClient();
String result=null;
HttpGet get=new HttpGet(url);
result=invoke(client,get);
client.getConnectionManager().shutdown();
return result;
}
public static HttpPost postForm(String url,Map<String,String> params){
HttpPost httpPost=new HttpPost(url);
List<NameValuePair> nvps=new ArrayList<NameValuePair>();
for(String key:params.keySet()){
nvps.add(new BasicNameValuePair(key,params.get(key)));
}
try {
httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
}catch (UnsupportedEncodingException e){
e.printStackTrace();
}
return httpPost;
}
public static String invoke(HttpClient client,HttpUriRequest request){
HttpResponse response=sendRequest(client,request);
String result=parseResponse(response);
return result;
}
public static HttpResponse sendRequest(HttpClient client,HttpUriRequest request){
HttpResponse response=null;
try{
response=client.execute(request);
}catch (ClientProtocolException cpe){
cpe.printStackTrace();
}catch (IOException ioe){
ioe.printStackTrace();
}
return response;
}
public static String parseResponse(HttpResponse response){
HttpEntity entity=response.getEntity();
String charset= EntityUtils.getContentCharSet(entity);
String result=null;
try{
result=EntityUtils.toString(entity);
}catch (ParseException pe){
pe.printStackTrace();
}catch (IOException ioe){
ioe.printStackTrace();
}
return result;
}
}