java HttpsPost CloseableHttpClient

//请求json
public static String HttpsPost(String url, Map<String, Object> param) throws Exception{
    String respContent ="";
    String restServiceURL = url;
    System.out.println(restServiceURL);

    CloseableHttpClient client = HttpClients.createDefault();
    //设置传入参数
    StringEntity entity = new StringEntity(JSONObject.toJSONString(param), "utf-8");
    HttpPost httpGet = new HttpPost(restServiceURL);
    httpGet.addHeader("Content-Type","application/json;charset=UTF-8");
    httpGet.setEntity(entity);
    HttpResponse resp = client.execute(httpGet);
    int statusCode = resp.getStatusLine().getStatusCode();
    if ( 200==statusCode ) {
        HttpEntity he = resp.getEntity();
        respContent = EntityUtils.toString(he, "utf-8");
    }else {
        log.error("请求第三方异常,状态码{},地址{}",statusCode,url);
    }

    return respContent;

}

 

/**
 * http请求 application/x-www-form-urlencoded
 */
public static String HttpsPostXw(String url, Map<String, String> param) throws Exception{
    String respContent ="";
    String restServiceURL = url;

    CloseableHttpClient client = HttpClients.createDefault();
    //设置传入参数
    HttpPost httpGet = new HttpPost(restServiceURL);
    httpGet.setHeader("Content-type", "application/x-www-form-urlencoded");
    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    if(param!=null){
        for (Map.Entry<String, String> entry : param.entrySet()) {
            nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
    }
    //设置参数到请求对象中
    httpGet.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));

    //装填参数
    if(param!=null){
        for (Map.Entry<String, String> entry : param.entrySet()) {
            httpGet.setHeader(entry.getKey(),entry.getValue());
        }
    }
    HttpResponse resp = client.execute(httpGet);
    int statusCode = resp.getStatusLine().getStatusCode();
    if ( 200==statusCode ) {
        HttpEntity he = resp.getEntity();
        respContent = EntityUtils.toString(he, "utf-8");
    }else {
        log.error("请求第三方异常,状态码{},地址{}",statusCode,url);
    }

    return respContent;

}

转载于:https://my.oschina.net/u/4121470/blog/3070274

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值