import com.baidu.api.client.core.JacksonUtil
import net.sf.json.JSONObject
import java.util.LinkedHashMap
import java.util.Map
public static void main(String args[]){
try{
Map<String, String> header = new LinkedHashMap<String, String>()
header.put("username","username")
header.put("password","password")
header.put("token","token")
header.put("account_type","1")
Map<String, String> body = new LinkedHashMap<String, String>()
body.put("siteId","siteId")
body.put("method","overview/getTimeTrendRpt")
body.put("start_date","20170627")
body.put("end_date","20170703")
body.put("metrics","pv_count,visitor_count,ip_count,bounce_ratio,avg_visit_time")
Map<String, Object> params = new LinkedHashMap<String, Object>()
params.put("header", header)
params.put("body", body)
//站点列表:https://api.baidu.com/json/tongji/v1/ReportService/getSiteList
//站点数据:https://api.baidu.com/json/tongji/v1/ReportService/getData
//获取的数据
String results = HttpUtil.doPostSSL("https://api.baidu.com/json/tongji/v1/ReportService/getData", json)
}catch (Exception e){
e.printStackTrace()
}
}
public static String doPostSSL(String apiUrl, Object json) {
CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(HttpUtil.createSSLConnSocketFactory()).setConnectionManager(HttpUtil.connMgr).setDefaultRequestConfig(HttpUtil.requestConfig).build()
HttpPost httpPost = new HttpPost(apiUrl)
CloseableHttpResponse response = null
String httpStr = null
try {
httpPost.setConfig(HttpUtil.requestConfig)
StringEntity stringEntity = new StringEntity(json.toString(),"UTF-8")
stringEntity.setContentEncoding("UTF-8")
stringEntity.setContentType("application/json")
httpPost.setEntity(stringEntity)
response = httpClient.execute(httpPost)
int statusCode = response.getStatusLine().getStatusCode()
if (statusCode != org.apache.http.HttpStatus.SC_OK) {
return null
}
HttpEntity entity = response.getEntity()
if (entity == null) {
return null
}
httpStr = EntityUtils.toString(entity, "utf-8")
} catch (Exception e) {
e.printStackTrace()
} finally {
if (response != null) {
try {
EntityUtils.consume(response.getEntity())
} catch (IOException e) {
e.printStackTrace()
}
}
}
return httpStr
}
结果
{
"header":
{
"desc":"success",
"failures":[],
"oprs":1,
"succ":1,
"oprtime":0,
"quota":1,
"rquota":49990,
"status":0
},
"body":
{
"data":
[
{"result":
{"items":
[
[
["2017/06/27"],
["2017/06/28"],
["2017/06/29"],
["2017/06/30"],
["2017/07/01"],
["2017/07/02"],
["2017/07/03"]
],
[
[10,20,30,40.1,50],
[10,20,30,40.2,50],
[10,20,30,40.3,50],
[10,20,30,40.4,50],
[10,20,30,40.5,50],
[10,20,30,40.6,50],
[10,20,30,40.7,50]
],
[],
[]
],
"timeSpan":["2017/06/27 - 2017/07/03"],
"fields":["simple_date_title","pv_count","visitor_count","ip_count","bounce_ratio","avg_visit_time"]
}
}
]
}
}