Java HttpUtil
添加一下依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.4</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.8</version>
</dependency>
大概步骤_Get
- 创建CloseableHttpClient
- 创建HttpGet对象,传入url
- httpclient执行请求,用HttpResponse接受返回数据
- 使用HttpEntity在response中获取entity
- 将entity转化成string,再规范成JsonObject
大概步骤_Post
- 创建CloseableHttpClient
- 创建HttpPost对象,传入url
- 为httppost对象设置传递参数
- httpclient执行请求,用HttpResponse接受返回数据
- 使用HttpEntity在response中获取entity
- 将entity转化成string,再规范成JsonObject
具体代码如下:
package com.exercise.demo;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
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.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import net.sf.json.JSONObject;
public class HttpUtil {
public static JSONObject doGet(String url) {
CloseableHttpClient httpclient = HttpClientBuilder.create().build();
HttpGet httpget = new HttpGet(url);
JSONObject jsonObj = null;
try {
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if(entity!=null) {
String result = EntityUtils.toString(entity,"UTF-8");
jsonObj = JSONObject.fromObject(result);
}
} catch (IOException e) {
e.printStackTrace();
}
return jsonObj;
}
public static JSONObject doPost(String url,String json) {
CloseableHttpClient httpclient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost(url);
JSONObject jsonObj = null;
try {
httpPost.setEntity(new StringEntity(json,"UTF-8"));
HttpResponse response = httpclient.execute(httpPost);
HttpEntity entity = response.getEntity();
if(entity!=null) {
String result = EntityUtils.toString(entity, "UTF-8");
jsonObj = JSONObject.fromObject(result);
}
} catch (IOException e) {
e.printStackTrace();
}
return jsonObj;
}
}
*Ending~~~~~~感谢阅读*