import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
//import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
//import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
public class HttpClientUtil {
/**
* @param url http请求地址
* @param content 请求实体entity内容
* @param contentType Content-Type,默认为text/plain
* @param headerMap 请求头header键值对
* @return 响应内容
* @throws Exception
*/
public String post(String url,String content,String contentType,Map<String,String> headerMap) throws Exception {
if (null == content||null == url ) {
return null;
}
if(null==contentType){
contentType = "text/plain";
}
//创建请求
HttpPost httpPost = new HttpPost(url);//创建post请求
// HttpPut httpPut = new HttpPut(url);//创建put请求
// HttpGet httpGet = new HttpGet(url);//创建get请求
if(null!=headerMap){
Set<Entry<String, String>> set = headerMap.entrySet();
Iterator<Entry<String, String>> it = set.iterator();
while(it.hasNext()){
Entry<String,String> e = (Entry<String,String>)it.next();
//设置请求头
httpPost.setHeader(e.getKey(), e.getValue());
}
}
//设置实体
StringEntity se = new StringEntity(content,ContentType.create(contentType, "UTF-8"));
httpPost.setEntity(se);
//创建http客户端
HttpClient httpclient = HttpClients.createDefault();
//执行发送,并接收响应
HttpResponse res = httpclient.execute(httpPost);
HttpEntity entity = res.getEntity();
InputStream in = entity.getContent();
//取出流中的内容
StringBuffer sb = new StringBuffer();
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
}finally{
if(in!=null){
in.close();
}
}
return sb.toString();
}
public static void main(String[] args) throws Exception {
Map<String,String> headerMap = new HashMap<String,String>();
headerMap.put("Authorization", "BASIC ***");
String content = "{\"mobile\":\"15868800***\",\"content\":\"您正在进行手机校验,验证码是845682,请及时输入。祝您生活愉快!\"}";
System.out.println(content);
String contentType = "application/json";
String url = "http://a***.webpower***.cn/sms/rest/v1/sms";
System.out.println(new HttpClientUtil().post(url, content, contentType, headerMap));
}
}
需要的jar包:
commons-logging.jar
httpclient-4.3.jar
httpcore-4.3.jar