基于HttpClient 4.3的通用POST方法

基于HttpClient 4.3的通用POST方法:

/**
  * 基于HttpClient 4.3的通用POST方法
  * @param url       提交的URL
  * @param paramsMap 提交<参数,值>Map
  * @return 提交响应
  */
public static String post(String url, Map < String, String > paramsMap) {
    CloseableHttpClient client = HttpClients.createDefault();
    String responseText = "";
    CloseableHttpResponse response = null;
    try {
       HttpPost method = new HttpPost(url);
       if (paramsMap != null) {
           List < NameValuePair > paramList = new ArrayList < NameValuePair > ();
           for (Map.Entry < String, String > param: paramsMap.entrySet()) {
              NameValuePair pair=new BasicNameValuePair(param.getKey(),param.getValue());
              paramList.add(pair);
           }
           method.setEntity(new UrlEncodedFormEntity(paramList,"UTF-8"));
       }
       response = client.execute(method);
       HttpEntity entity = response.getEntity();
       if (entity != null) {
           responseText = EntityUtils.toString(entity, "UTF-8");
       }
   } catch (Exception e) {
           e.printStackTrace();
   } finally {
       try {
           response.close();
       } catch (Exception e) {
           e.printStackTrace();
       }
   }
   return responseText;
}

调用:

Map < String, String > params = new HashMap < String, String > ();
params.put("apikey", apikey);
params.put("text", text);
params.put("mobile", mobile);
//转json对象
JSONObject jsonObject = JSONObject.parseObject(post("调用的url地址", params));
 

你可能感兴趣的:(后端开发)