GET请求:
/**
* get 请求
* @param url
* @return
*/
public static String doGetStr(String url){
HttpClient httpClient = HttpClientBuilder.create().build();
logger.debug("发起请求的地址: {}", url);
HttpGet get = new HttpGet(url);
try {
/*
* 添加请求头信息
*/
// 浏览器表示
get.addHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.6)");
// 传输的类型
get.addHeader("Content-Type", "application/x-www-form-urlencoded");
// 执行请求
HttpResponse execute = httpClient.execute(get);
// 获得响应的实体对象
HttpEntity entity = execute.getEntity();
if(entity != null){
// 使用Apache提供的工具类进行转换成字符串
String result = EntityUtils.toString(entity,"UTF-8");
// JSONObject jsonObject = JSONObject.fromObject(result);
return result;
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
POST请求:
/**
* post 请求
* @param url
* @param outstr
* @return
*/
public static String doPostStr(String url,String outstr){
HttpClient httpClient = HttpClientBuilder.create().build();
logger.debug("发起请求的地址: {}", url);
HttpPost httpPost = new HttpPost(url);
// 设置请求的header
httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json;charset=utf-8");
try {
// 设置请求的参数
StringEntity entity = new StringEntity(outstr,"UTF-8");
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
httpPost.setEntity(entity);
// 执行请求
HttpResponse execute = httpClient.execute(httpPost);
int code = execute.getStatusLine().getStatusCode();
// System.out.println("http状态码 :"+ code);
String result = EntityUtils.toString(execute.getEntity(), "UTF-8");
// JSONObject jsonObject = JSONObject.fromObject(result);
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}