1. 环境,平台
1.1 JDK1.7+eclipse
首先在eclipse安装testNG插件,安装过程http://www.blogjava.net/qileilove/archive/2014/09/02/417593.html
在网上下载httpclient4.3jar包,下载地址 http://download.csdn.net/detail/u010627840/8192601
下载JSON相关jar包,下载地址 https://mvnrepository.com/artifact/com.alibaba/fastjson/1.2.62
1.2 maven+idea+testNg
依赖的jar
<dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <version>6.8</version> </dependency><!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient --> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.3</version> </dependency> <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.62</version> </dependency>
2 目的
模拟浏览器发出get请求,获取返回的JSON,并解析。
package com.example.shard.test;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
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.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class HttpGetTest {
@BeforeClass
public void beforeClass() {
System.out.println("==========this is before class===============");
}
@Test
public void testGet() throws Exception {
requestGet("http://119.147.19.43/v3/user/get_info");
// requestGet("http://www.renren.com/PLogin.do");
}
private void requestGet(String urlWithParams) throws Exception {
CloseableHttpClient httpclient = HttpClientBuilder.create().build();
HttpGet httpget = new HttpGet(urlWithParams);
//配置请求的超时设置
RequestConfig requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(50)
.setConnectTimeout(50)
.setSocketTimeout(50).build();
httpget.setConfig(requestConfig);
CloseableHttpResponse response = httpclient.execute(httpget);
System.out.println("响应码StatusCode -> " + response.getStatusLine().getStatusCode());
HttpEntity entity = response.getEntity();
String jsonStr = EntityUtils.toString(entity);//, "utf-8");
char c = jsonStr.trim().charAt(0);
if ('[' == c) {
JSONArray jsonArray = JSONArray.parseArray(jsonStr);
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject jsonObj = jsonArray.getJSONObject(i);
System.out.println("jsonObj=:" + jsonObj);
}
} else if ('{' == c) {
JSONObject jsonObj1 = JSONObject.parseObject(jsonStr);
System.out.println("解析后的数据:jsonObj1=" + jsonObj1);
}
httpget.releaseConnection();
}
@AfterClass
public void afterClass() {
System.out.println("===========this is after class=================");
}
}