1.需要引入的几个jar:
httpclient-4.5.2.jar
httpcore-4.4.4.jar
json-lib-2.4-jdk15.jar
2.具体代码:
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(Uri);//uri为请求路径
//头信息
httpPost.addHeader("X-Auth-Token", "testtesttesttest");
httpPost.addHeader("Accept", "application/json;chartset=utf-8");
// 接收参数json列表
JSONObject jsonParam = new JSONObject();
jsonParam.put("参数1", "参数1");
jsonParam.put("参数2","参数2");
StringEntity entity = new StringEntity(jsonParam.toString(),"utf-8");//解决中文乱码问题
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
httpPost.setEntity(entity);
CloseableHttpResponse response = httpclient.execute(httpPost);
try {
int codeStatus = response.getStatusLine().getStatusCode(); //请求结果状态值
if(codeStatus != 200){
return;
}
Header[] headers = loginResponse.getAllHeaders(); //响应头信息
for(Header header : headers){
String name = header.getName();
String value = header.getValue();
}
//获取返回值:
HttpEntity entity = response.getEntity();
String content = EntityUtils.toString(entity,"UTF-8").trim();
} catch (UnsupportedOperationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
response.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
httpclient.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
3.参考文章:
(1)http://hc.apache.org/httpclient-3.x/
(2)http://blog.csdn.net/p793049488/article/details/38731883
(3)http://www.cnblogs.com/loveyakamoz/archive/2011/07/21/2112804.html
(4)http://blog.csdn.net/wangpeng047/article/details/19624529