java httppost_JAVA HTTPPOST

public static String post(String url, Map paramMap) throws ClientProtocolException, IOException,Exception {

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

HttpPost httpPost = new HttpPost(url);

//设置认证信息

JSONObject json=new JSONObject(paramMap);

httpPost.setConfig(RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(3000).setSocketTimeout(5000).build());

List formparams = setHttpParams(paramMap);

UrlEncodedFormEntity param = new UrlEncodedFormEntity(formparams, "UTF-8");

//通过setEntity()设置参数给post

httpPost.setEntity(param);

//利用httpClient的execute()方法发送请求并且获取返回参数

HttpResponse response = httpClient.execute(httpPost);

String httpEntityContent = getHttpEntityContent(response);

httpPost.abort();

return httpEntityContent;

}

/**

* 设置请求参数

* @param

* @return

*/

private static List setHttpParams(Map paramMap) {

List formparams = new ArrayList<>();

Set> set = paramMap.entrySet();

for (Map.Entry entry : set) {

formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));

}

return formparams;

}

/**

* 获得响应HTTP实体内容

* @param response

* @return

* @throws java.io.IOException

* @throws java.io.UnsupportedEncodingException

*/

private static String getHttpEntityContent(HttpResponse response) throws IOException, UnsupportedEncodingException {

//通过HttpResponse 的getEntity()方法获取返回信息

HttpEntity entity = response.getEntity();

if (entity != null) {

InputStream is = entity.getContent();

BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

String line = br.readLine();

StringBuilder sb = new StringBuilder();

while (line != null) {

sb.append(line + "\n");

line = br.readLine();

}

br.close();

is.close();

return sb.toString();

}

return "";

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值