httpClient POST 请求

public static String doPostJson(String url,Map<String,String> map) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();  
            if(map!=null){  
                for (Entry<String, String> entry : map.entrySet()) {  
                    nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));  
                }  
            }  
            //设置参数到请求对象中  
            httpPost.setEntity(new UrlEncodedFormEntity(nvps,"utf-8"));  
            
            
            // 创建请求内容
       //     StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
       //     httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);
            
            HttpEntity httpEntity = response.getEntity(); 


            
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return resultString;
    }

  

猜你喜欢

转载自www.cnblogs.com/lxnv587/p/10495866.html