在一次工作中,需要用Java去请求一个接口,并提取返回来的json数据中自己想要的值。
在maven项目中,项目的依赖:
1.http依赖
org.apache.httpcomponents
httpclient
4.5
org.apache.httpcomponents
httpcore
4.4.4
org.apache.httpcomponents
httpmime
4.5
2.json处理依赖
net.sf.json-lib
json-lib
2.4
jdk15
commons-beanutils
commons-beanutils
1.7.0
commons-collections
commons-collections
3.1
commons-lang
commons-lang
2.5
net.sf.ezmorph
ezmorph
1.0.3
以上有的依赖不是必须的,为了方便起见加了所有的依赖。
http中的GET请求实现
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
public class HttpClientUtil {
// utf-8字符编码
public static final String CHARSET_UTF_8 = "utf-8";
// HTTP内容类型。
public static final String CONTENT_TYPE_TEXT_HTML = "text/xml";
// HTTP内容类型。相当于form表单的形式,提交数据
public static final String CONTENT_TYPE_FORM_URL = "application/x-www-form-urlencoded";
// HTTP内容类型。相当于form表单的形式,提交数据
public static final String CONTENT_TYPE_JSON_URL = "application/json;charset=utf-8";
// 连接管理器
private static PoolingHttpClientConnectionManager pool;
// 请求配置
private static RequestConfig requestConfig;
static {
try {
//System.out.println("初始化HttpClientTest~~~开始");
SSLContextBuilder builder = new SSLContextBuilder();
builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
builder.build());
// 配置同时支持 HTTP 和 HTPPS
Registry socketFactoryRegistry = RegistryBuilder. create().register(
"http", PlainConnectionSocketFactory.getSocketFactory()).register(
"https", sslsf).build();
// 初始化连接管理器
pool = new PoolingHttpClientConnectionManager(
socketFactoryRegistry);
// 将最大连接数增加到200,实际项目最好从配置文件中读取这个值
pool.setMaxTotal(200);
// 设置最大路由
pool.setDefaultMaxPerRoute(2);
// 根据默认超时限制初始化requestConfig
int socketTimeout = 10000;
int connectTimeout = 10000;
int connectionRequestTimeout = 10000;
requestConfig = RequestConfig.custom().setConnectionRequestTimeout(
connectionRequestTimeout).setSocketTimeout(socketTimeout).setConnectTimeout(
connectTimeout).build();
//System.out.println("初始化HttpClientTest~~~结束");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
// 设置请求超时时间
requestConfig = RequestConfig.custom().setSocketTimeout(50000).setConnectTimeout(50000)
.setConnectionRequestTimeout(50000).build();
}
public static CloseableHttpClient getHttpClient() {
CloseableHttpClient httpClient = HttpClients.custom()
// 设置连接池管理
.setConnectionManager(pool)
// 设置请求配置
.setDefaultRequestConfig(requestConfig)
// 设置重试次数
.setRetryHandler(new DefaultHttpRequestRetryHandler(0, false))
.build();
return httpClient;
}
private static String sendHttpGet(HttpGet httpGet){
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
// 响应内容
String responseContent = null;
try {
// 创建默认的httpClient实例.
httpClient = getHttpClient();
// 配置请求信息
httpGet.setConfig(requestConfig);
// 执行请求
response = httpClient.execute(httpGet);
// 得到响应实例
HttpEntity entity = response.getEntity();
// 可以获得响应头
// Header[] headers = response.getHeaders(HttpHeaders.CONTENT_TYPE);
// for (Header header : headers) {
// System.out.println(header.getName());
// }
// 得到响应类型
// System.out.println(ContentType.getOrDefault(response.getEntity()).getMimeType());
// 判断响应状态
if (response.getStatusLine().getStatusCode() >= 300) {
throw new Exception(
"HTTP Request is not success, Response code is " + response.getStatusLine().getStatusCode());
}
if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
responseContent = EntityUtils.toString(entity, CHARSET_UTF_8);
EntityUtils.consume(entity);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// 释放资源
if (response != null) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return responseContent;
}
public static String HttpGet(String httpUrl){
//创建Get请求
HttpGet httpGet=new HttpGet(httpUrl);
return sendHttpGet(httpGet);
}
/*public String getMid(){
}*/
public static void main(String[] args) throws Exception{
String tempdata=HttpGet("http://xx.xx.xxx.xx:8081/api/data/all?category=集团客户");
System.out.print(tempdata);
}
}
数据源格式是json格式的,如下图
获取mid的值:
JSONObject object1=JSONObject.fromObject(tempdata);
//System.ou.println(object1.get("Status")) 获取Status的值
JSONArray object2=object1.getJSONArray("Result"); //result的值是一个数组,所以需要JSONArray
for(int i=0;i