需求背景
我们会有调用一个webservice项目的接口,此时需要用java来模拟post或者get请求来获取结果。
废话不多少,直接上代码。我们会在HttpClient的基础上再封装一个HttpClientUtil类,对外分别开放doGet
和doPost
方法,来实现get和post请求。
HttpClientUtil类代码
import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HttpClientUtil {
private static final Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);
/**
* 使用Appache的HttpClient进行post请求
* @param url http提交的url
* @param map class:'Map<String, Object>', 并且value是可以通过String.valueOf(value) 转化为字符串的类型
* 支持String,boolean,Integer等
* @param charset 例如"utf-8"
* @return 请求的结果,请求成功会返回json string
*/
public static String doPost(String url, Map<String, Object> map, String charset) {
HttpClient httpClient = null;
HttpPost httpPost = null;
String result = null;
try {
httpClient = HttpClients.createDefault();
httpPost = new HttpPost(url);
// 设置参数
List<NameValuePair> list = new ArrayList<NameValuePair>();
Iterator<Entry<String, Object>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Entry<String, Object> elem = (Entry<String, Object>) iterator.next();
list.add(new BasicNameValuePair(elem.getKey(), String.valueOf(elem.getValue())));
}
if (list.size() > 0) {
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, charset);
httpPost.setEntity(entity);
}
HttpResponse response = httpClient.execute(httpPost);
if (response != null) {
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
result = EntityUtils.toString(resEntity, charset);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return result;
}
/**
* 使用Appache的HttpClient进行get请求
* @param url http提交的url
* @param map must be null
* @param charset 例如"utf-8"
* @return 请求的结果,请求成功会返回json string
*/
public static String doGet(String url, Map<String, Object> map,
String charset) {
map = null;
HttpClient httpClient = null;
HttpGet httpGet = null;
String result = null;
try {
httpClient = HttpClients.createDefault();
httpGet = new HttpGet(url);
HttpResponse response = httpClient.execute(httpGet);
if (response != null) {
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
result = EntityUtils.toString(resEntity, charset);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return result;
}
public static String postByStringBody(String url, String paramText, boolean needResponse){
String responseStr = "";
//post请求返回结果
HttpClient httpClient = HttpClients.createDefault();
// JSONObject jsonResult = null;
HttpPost method = new HttpPost(url);
try {
if (null != paramText && paramText.length() > 0) {
//解决中文乱码问题
StringEntity entity = new StringEntity(paramText.toString(), "utf-8");
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
method.setEntity(entity);
}
HttpResponse result = httpClient.execute(method);
url = URLDecoder.decode(url, "UTF-8");
/**请求发送成功,并得到响应**/
if (result.getStatusLine().getStatusCode() == 200) {
String str = "";
try {
/**读取服务器返回过来的json字符串数据**/
responseStr = EntityUtils.toString(result.getEntity());
if (!needResponse) {
return null;
}
} catch (Exception e) {
logger.error("post请求提交失败:" + url);
}
}
} catch (IOException e) {
logger.error("post请求提交失败:" + url);
}
return responseStr;
}
}
调用该方法代码段
String accountUrl = "http://*********url";
HashMap<String, Object> params = new HashMap<String,Object>();
params.put("userId", userId);
params.put("token", token);
params.put("os", "weixin");
params.put("version", ConfigUtils.getVersion());
params.put("mac", "weixin");
params.put("model", "weixin");
params.put("from", "d");
String reuslt = HttpClientUtil.doPost(accountUrl, params, "UTF-8");
reuslt = reuslt.contains("html")?"{}":reuslt;
logger.info("[getAccount]userId:{},result:{}",new Object[]{userId,reuslt});
JSONObject jsonObject = JSON.parseObject(reuslt);
/***
* <code>{"data":{"username":"526306457@qq.com"},"message":"sucess","status":0}</code>
*/
if (jsonObject.getInteger("status") == 0) {
String username = jsonObject.getJSONObject("data").getString("username");
return username;
}else {
return "";
}
此时返回的reuslt结果便是发送该请求获取到的请求。