HttpClient发送post请求

2017-12-09  本文已影响0人  小白豆豆5

HTTPClient发送post请求示例,可发送https请求:

public staticString httpsPost(String url, JSONObject jsonParam,booleannoNeedResponse){

//post请求返回结果

HttpClient httpClient = HttpClientBuilder.create().build();

HttpPost method =newHttpPost(url);

String str =null;

try{

if(null!= jsonParam) {

//解决中文乱码问题

StringEntity entity =newStringEntity(jsonParam.toString(),"utf-8");

entity.setContentEncoding("UTF-8");

entity.setContentType("application/json");

method.setEntity(entity);

}

HttpResponse result = httpClient.execute(method);

url = URLDecoder.decode(url,"UTF-8");

/**请求发送成功,并得到响应**/

if(result.getStatusLine().getStatusCode() ==200) {

try{

/**读取服务器返回过来的json字符串数据**/

str = EntityUtils.toString(result.getEntity());

if(!noNeedResponse) {

return null;

}

/**把json字符串转换成json对象**/

}catch(Exception e) {

log.error("post请求提交失败:"+ url, e);

}

}

}catch(IOException e) {

log.error("post请求提交失败:"+ url, e);

}

returnstr;

}

上一篇下一篇

猜你喜欢

热点阅读