后端發送httpPost請求的2種方式


  今天寫了個發送請求驗證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;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM