package com.dbutils.http;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
public class HttpClientUtils {
public static String doPost(URL url, Map params, String charset){
//新建HttpClient
HttpClient client = HttpClients.createDefault();
//创建HttpPost
if(null == url || "".equals(url.toString())){
return "url is not allow empty!";
}
HttpPost post = new HttpPost(url.toString());
//添加参数
List paraList = new ArrayList();
Set> mapSet = params.entrySet();
Iterator> iterator = mapSet.iterator();
while(iterator.hasNext()){
Map.Entry elem = iterator.next();
paraList.add(new BasicNameValuePair(elem.getKey(),elem.getValue()));
}
//发起请求
try{
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paraList,charset);
post.setEntity(entity);
//连接并获得返回
HttpResponse respOnse= client.execute(post);
//处理返回数据
if(null != response){
Header[] headers = response.getAllHeaders();
for(Header header : headers){
System.out.println(header.getName() + ":" + header.getValue());
}
HttpEntity respOnseEntity= response.getEntity();
if(null != responseEntity){
//获得Http返回数据,并返回函数
return EntityUtils.toString(responseEntity,charset);
}
}
}catch(Exception e){
return "error" + e.getMessage();
}
return "";
}
public static void main(String[] args){
try{
URL url = new URL("http://localhost:8080");
Map paraMap = new HashMap();
paraMap.put("para1","TK20180529001");
String value = HttpClientUtils.doPost(url,paraMap,"UTF-8");
System.out.print(value);
}catch(Exception e){}
}
}