httpClient发送普通Get请求

  • Post author:
  • Post category:其他

httpClient发送普通Get请求

/**
     * @param url 请求地址
     * @param map 请求参数
*/
 public static String defalutGetRequest(String url,Map<String,String> map){

        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            URIBuilder uri = new URIBuilder(url);
            //get请求带参数
            List<NameValuePair> list = new LinkedList<>();
            if (map != null) {
                List<BasicNameValuePair> paramList = new ArrayList<>();
                for (String key : map.keySet()) {
                    BasicNameValuePair param1 = new BasicNameValuePair(key, map.get(key));
                    list.add(param1);
                }
            }
            uri.setParameters(list);
            // 创建Http Post请求
            HttpGet httpGet = new HttpGet(uri.build());
            //设置请求状态参数
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectionRequestTimeout(connectionRequestTimeout)
                    .setSocketTimeout(socketTimeout)
                    .setConnectTimeout(3000).build();
            httpGet.setConfig(requestConfig);
            httpGet.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
            // 执行http请求
            response = httpClient.execute(httpGet);
            int status = response.getStatusLine().getStatusCode();//获取返回状态值
            if (status == HttpStatus.SC_OK) {//请求成功
                HttpEntity httpEntity = response.getEntity();
                if(httpEntity != null) {
                    resultString = EntityUtils.toString(httpEntity, "utf-8");
                    EntityUtils.consume(httpEntity);//关闭资源
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (response!=null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return resultString;
    }

版权声明:本文为weixin_45023621原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。