使用HttpClient封装的Get和Post请求
使用HttpClient封装的Get和Post请求,并可以将结果转为JSON对象返回
导入HttpClient的依赖
org.apache.httpcomponents
httpclient
4.5.2
封装get和post请求
public class HttpUtils {
public static CloseableHttpClient httpClient = HttpClients.createDefault();
//get
public static JSONObject doGet(String url, Map<String, String> params) throws URISyntaxException, IOException {
URIBuilder uriBuilder = new URIBuilder(url);
if (params != null) {
Set<String> keys = params.keySet();
for (String key : keys) {
String value = params.get(key);
uriBuilder.setParameter(key,value);
}
}
HttpGet httpGet = new HttpGet(uriBuilder.build());
CloseableHttpResponse response = httpClient.execute(httpGet);
System.out.println(response);
return toJSONobject(response);
}
//post
public static JSONObject doPost(String url, Map<String, String> params) throws IOException {
HttpPost httpPost = new HttpPost(url);
//封装post请求参数
List<NameValuePair> valuePairs = new ArrayList<NameValuePair>();
if (params != null){
Set<String> keys = params.keySet();
for (String key : keys) {
String value = params.get(key);
valuePairs.add(new BasicNameValuePair(key,value));
}
}
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(valuePairs,"utf8");
httpPost.setEntity(formEntity);
CloseableHttpResponse response = httpClient.execute(httpPost);
return toJSONobject(response);
}
public static JSONObject toJSONobject(CloseableHttpResponse response) throws IOException {
if (response.getStatusLine().getStatusCode() == 200){
String json = EntityUtils.toString(response.getEntity());
JSONObject jsonObject = JSON.parseObject(json);
return jsonObject;
}
return null;
}
}
还没有评论,来说两句吧...