public static String requestHttp(String url) {
String result = "";
try {
// 根据地址获取请求
HttpGet request = new HttpGet(url);//这里发送get请求
// 获取当前客户端对象
HttpClient httpClient = HttpClients.createDefault();
// 通过请求对象获取响应对象
HttpResponse response = httpClient.execute(request);
// 判断网络连接状态码是否正常(0--200都数正常)
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
result= EntityUtils.toString(response.getEntity(),"utf-8");
logger.info("response=============" + result);
} else {
logger.info("============================== post fail");
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public static String postHttp(String url, String jsonStr) {
String result = "";
try {
// 根据地址获取请求
HttpPost post = new HttpPost(url);//这里发送post请求
// 中文乱码的可以尝试下面
//post.addHeader("Content-type","application/json; charset=utf-8");
//post.setHeader("Accept", "application/json");
//post.setEntity(new StringEntity(jsonParam.toString(), Charset.forName("UTF-8")));
StringEntity se = new StringEntity(jsonStr, Charset.forName("UTF-8"));
se.setContentType("text/json");
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
// 获取当前客户端对象
HttpClient httpClient = HttpClients.createDefault();
// 通过请求对象获取响应对象
HttpResponse response = httpClient.execute(post);
// 判断网络连接状态码是否正常(0--200都数正常)
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
result= EntityUtils.toString(response.getEntity(),"utf-8");
logger.info("response=============" + result);
} else {
logger.info("============================== post fail");
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
HttpPost、HttpGet 发送请求
最新推荐文章于 2024-08-21 16:59:06 发布