`
bosschen
  • 浏览: 193243 次
  • 性别: Icon_minigender_1
  • 来自: 北京
文章分类
社区版块
存档分类
最新评论

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;
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics