后端发送httpPost请求的2种方式

时间:2021-11-16 19:10:04

  今天写了个发送请求验证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;
}