// 伪装浏览器请求
private static String userAgent = "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36";
private static String contentType = "application/json;charset=utf-8";private static String accept = "application/json";
public static String getHttpClient(String url, String query) {
// 创建client和post对象
HttpClient client = HttpClients.createDefault();
//post请求用于(key-value)类型
post.setHeader("User-Agent", userAgent); // 伪装浏览器请求
// json形式
post.addHeader("content-type", contentType);
post.addHeader("accept", accept);
post.setEntity(new StringEntity(query, Charset.forName("utf-8"))); // json字符串以实体的实行放到post中
HttpResponse response = null;
try {
response = client.execute(post); // 获得response对象
} catch (Exception e) {
e.printStackTrace();
}
String result = "";
if (HttpStatus.SC_OK != response.getStatusLine().getStatusCode()) {
result = "请求返回不正确";
return result;
}
try {
result = EntityUtils.toString(response.getEntity()); // 获得字符串形式的结果
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
//创建传入NameValuePair集合类型的参数
//NameValuePair键值对类型的实体 个人比较推荐使用 第一种String类型 比较灵活 自由选择
public static JSONObject getHttpClient(String url,List<? extends NameValuePair> formparams) {
JSONObject dataJson = new JSONObject();
// 创建默认的httpClient实例.
CloseableHttpClient httpclient = HttpClients.createDefault();
// 创建httppost
HttpPost httppost = new HttpPost(url);
UrlEncodedFormEntity uefEntity;
CloseableHttpResponse response = null;
try {
uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
httppost.setEntity(uefEntity);
System.out.println("executing request " + httppost.getURI());
response = httpclient.execute(httppost);
}catch (Exception e) {
e.printStackTrace();
}
if (HttpStatus.SC_OK != response.getStatusLine().getStatusCode()) {
dataJson.put("errMsg", "错误码"+response.getStatusLine().getStatusCode());
}
try {
HttpEntity entity = response.getEntity();
if (entity != null) {
String str = EntityUtils.toString(entity, "UTF-8");
System.out.println("Response content: "+ str);
System.out.println(str);
JSONObject queryJson = JSON.parseObject(str);
dataJson.put("errMsg", queryJson.getString("errMsg"));
dataJson.put("success", queryJson.getString("success"));
}
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return dataJson;
}
//创建get类
public static String doGet(String url) {try {
HttpClient client = new DefaultHttpClient();
//发送get请求
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);
/**请求发送成功,并得到响应**/
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
/**读取服务器返回过来的json字符串数据**/
String strResult = EntityUtils.toString(response.getEntity());
return strResult;
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}