java发送httpPost请求的2种方式

http://www.cnblogs.com/hanyj123/p/9641626.html

今天写了个发送请求验证token,本来使用application/json发送post请求,如下:

/**
* 通过请求第三方接口验证token
* @param token
*/
public Map verifyToken(String token) {
    CloseableHttpClient httpClient = null;
    CloseableHttpResponse response = null;
    Map result = null;
    try {
        httpClient = HttpClients.createDefault();
        //参数
        Map params = new HashMap();
        params.put("userToken", token);
        params.put("type", "floodForecast");
        //通过post方式访问
        HttpPost post = new HttpPost(verifyUrl);
        StringEntity paramEntity = new StringEntity(JSONParser.obj2Json(params), "UTF-8");
        paramEntity.setContentType("application/json");
        post.setEntity(paramEntity);
        response = httpClient.execute(post);
        HttpEntity valueEntity = response.getEntity();
        String content = EntityUtils.toString(valueEntity);
        result = JSONParser.json2Map(content);

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return result;
}

后来第三方接口不支持json接收,需要改成text,如下

/**
* 通过请求第三方接口验证token
* @param token
*/
public Map verifyToken(String token) {
  HttpClient httpClient = null;
  HttpResponse response = null;
  Map result = null;
  try {
    httpClient = HttpClients.createDefault();
    // 准备参数
    List<NameValuePair> params = Lists.newArrayList();
    params.add(new BasicNameValuePair("userToken",token));
    params.add(new BasicNameValuePair("type","flood_forecast"));
    UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params,"UTF-8");
    //通过post方式访问
    HttpPost post = new HttpPost(verifyUrl);
    formEntity.setContentType("application/x-www-form-urlencoded");
    post.setEntity(formEntity);
    response = httpClient.execute(post);
    HttpEntity valueEntity = response.getEntity();
    String content = EntityUtils.toString(valueEntity);
    result = JSONParser.json2Map(content);
  } catch (UnsupportedEncodingException e) {
    e.printStackTrace();
  } catch (ClientProtocolException e) {
    e.printStackTrace();
  } catch (IOException e) {
    e.printStackTrace();
  }
  return result;
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值