您的位置:首页 > 理论基础 > 计算机网络

Java的HttpClient、HttpGet和HttpPost请求

2017-07-04 15:12 351 查看
public static String getHttp(String url) {
String result = "";
try {
// 根据地址获取请求
HttpGet request = new HttpGet(url);
// 获取当前客户端对象
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("===>" + 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("===>" + result);
} else {
logger.info("===> post fail");
}
} catch (Exception e) {
e.printStackTrace();
}

return result;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: