java http请求get post

java http请求get post

pom.xml

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.12</version>
        </dependency>

HttpClientHelper

/**
 * Created by JiangJunpeng on 2019/9/27.<br>
 */
public class HttpClientHelper {

    private static Logger logger = LoggerFactory.getLogger(HttpClientHelper.class);

    /**
     * @param :
     * @return :
     * @throws :
     * @MethodName : doGet
     * @Description : http get请求
     * @author : JiangJunpeng
     * @date : 2019/9/27 16:56
     */
    public static String doGet(String url) {
        CloseableHttpResponse response = null;
        try(CloseableHttpClient client = HttpClientBuilder.create().build()) {
            //发送get请求
            HttpGet request = new HttpGet(url);
            RequestConfig build = RequestConfig.custom()
                    .setConnectionRequestTimeout(14000)
                    .setConnectTimeout(14000)
                    .setSocketTimeout(14000).build();
            request.setConfig(build);
            response = client.execute(request);
            /**请求发送成功,并得到响应**/
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                /**读取服务器返回过来的json字符串数据**/
                return EntityUtils.toString(response.getEntity());
            }
        } catch (IOException e) {
            logger.error("doGet 请求出错,请求url为[{}],错误信息为:[{}]",url,e.getMessage());
//            e.printStackTrace();
        }
        return null;
    }

    /**
     *@description:http,get请求设置超时时间
     *@param:
     *@return:
     *@author:JiangJunpeng
     *@date:2020/2/19
     */
    public static String doGet(String url, int timeout) {
        CloseableHttpClient client = HttpClientBuilder.create().build();
//        HttpClient client = new DefaultHttpClient();
        CloseableHttpResponse response = null;
        try {
            //发送get请求
            HttpGet request = new HttpGet(url);
            RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout) //连接超时时间
                    .setConnectionRequestTimeout(1000) //从连接池中取的连接的最长时间
                    .setSocketTimeout(5 * 1000) //数据传输的超时时间
                    .build();
            request.setConfig(config);
            response = client.execute(request);
            /**请求发送成功,并得到响应**/
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                /**读取服务器返回过来的json字符串数据**/
                String strResult = EntityUtils.toString(response.getEntity());
                return strResult;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (client != null) {
                    client.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        return null;
    }

    /**
     * @param :
     * @return :
     * @throws :
     * @MethodName : doPost
     * @Description : http post请求
     * @author : JiangJunpeng
     * @date : 2019/9/27 16:28
     */
    public static String doPost(String url, Map map){
        BufferedReader in = null;
        CloseableHttpClient client = HttpClientBuilder.create().build();
        CloseableHttpResponse response = null;
        try {
            // 定义HttpClient
            // 实例化HTTP方法
            HttpPost request = new HttpPost();
            request.setURI(new URI(url));
            //设置参数
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            for (Iterator iter = map.keySet().iterator(); iter.hasNext(); ) {
                String name = (String) iter.next();
                String value = String.valueOf(map.get(name));
                nvps.add(new BasicNameValuePair(name, value));
            }
            request.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
            response = client.execute(request);
            int code = response.getStatusLine().getStatusCode();
            //请求成功
            if (code == 200) {
                in = new BufferedReader(new InputStreamReader(response.getEntity()
                        .getContent(), "utf-8"));
                StringBuffer sb = new StringBuffer("");
                String line = "";
                String NL = System.getProperty("line.separator");
                while ((line = in.readLine()) != null) {
                    sb.append(line + NL);
                }
                in.close();
                return sb.toString();
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }finally {
            try {
                if (client != null) {
                    client.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    /**
     * @param :
     * @return :
     * @throws :
     * @MethodName : doPost
     * @Description : http post请求
     * @author : JiangJunpeng
     * @date : 2019/9/27 16:28
     */
    public static String doPost(String url, String json) throws IOException {
        DefaultHttpRequestRetryHandler defaultHttpRequestRetryHandler = new DefaultHttpRequestRetryHandler(0,false);
        CloseableHttpClient httpclient = null;
        if (url.startsWith("https")) {
            httpclient = wrapClient();
        } else {
            httpclient = HttpClientBuilder.create().setDefaultRequestConfig(RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build()).setRetryHandler(defaultHttpRequestRetryHandler).build();
        }
        // 创建httpPost
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-Type", "application/json");
        String charSet = "UTF-8";
        StringEntity entity = new StringEntity(json, charSet);
        httpPost.setEntity(entity);
        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(httpPost);
            StatusLine status = response.getStatusLine();
            int state = status.getStatusCode();
            if (state == HttpStatus.SC_OK) {
                HttpEntity responseEntity = response.getEntity();
                String jsonString = EntityUtils.toString(responseEntity);
                return jsonString;
            } else {
                return "请求返回:" + state + "(" + url + ")";
            }
        } finally {
            try {
                if (httpclient != null) {
                    httpclient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }


    public static String post(String url, List<NameValuePair> params, Map<String, String> head) {
        DefaultHttpRequestRetryHandler defaultHttpRequestRetryHandler = new DefaultHttpRequestRetryHandler(0,false);
        CloseableHttpClient client = null;
        if (url.startsWith("https")) {
            client = wrapClient();
        } else {
            client = HttpClientBuilder.create().setDefaultRequestConfig(RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build()).setRetryHandler(defaultHttpRequestRetryHandler).build();
        }
        HttpPost post = new HttpPost(url);
        post.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));
        if (head != null) {
            for (Map.Entry<String, String> entry : head.entrySet()) {
                post.setHeader(entry.getKey(), entry.getValue());
            }
        }
        CloseableHttpResponse response = null;
        try {
            response = client.execute(post);
            if (response.getStatusLine().getStatusCode() != 200) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("code", response.getStatusLine().getStatusCode());
                jsonObject.put("message", EntityUtils.toString(response.getEntity(),StandardCharsets.UTF_8));
                return jsonObject.toString();
            }
            return EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
        } catch (IOException e) {
            logger.error("post 请求出错url为[{}],报错信息为[{}]",url,e.getMessage());
            return null;
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                if (client != null) {
                    client.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static String formDataPost(String url, Map<String,String> params, Map<String, String> head) {
        DefaultHttpRequestRetryHandler defaultHttpRequestRetryHandler = new DefaultHttpRequestRetryHandler(0,false);
        CloseableHttpClient client = null;
        if (url.startsWith("https")) {
            client = wrapClient();
        } else {
            client = HttpClientBuilder.create().setDefaultRequestConfig(RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build()).setRetryHandler(defaultHttpRequestRetryHandler).build();
        }
        HttpPost post = new HttpPost(url);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            builder.addTextBody(entry.getKey(), entry.getValue(), ContentType.MULTIPART_FORM_DATA);
        }
        post.setEntity(builder.build());
        if (head != null) {
            for (Map.Entry<String, String> entry : head.entrySet()) {
                post.setHeader(entry.getKey(), entry.getValue());
            }
        }
        CloseableHttpResponse response = null;
        try {
            response = client.execute(post);
            if (response.getStatusLine().getStatusCode() != 200) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("code", response.getStatusLine().getStatusCode());
                jsonObject.put("message", EntityUtils.toString(response.getEntity(),StandardCharsets.UTF_8));
                return jsonObject.toString();
            }
            return EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
        } catch (IOException e) {
            logger.error("post 请求出错url为[{}],报错信息为[{}]",url,e.getMessage());
            return null;
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                if (client != null) {
                    client.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }




    public static String get(String urlStr, List<NameValuePair> params) {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        CloseableHttpResponse response = null;
        try {
            URL url = new URL(urlStr);
            URI uri = new URIBuilder()
                    .setScheme(url.getProtocol())
                    .setHost(url.getHost())
                    .setPath(url.getPath())
                    .setParameters(params).build();
            HttpGet httpGet = new HttpGet(uri);
            response = httpClient.execute(httpGet);
            if (response.getStatusLine().getStatusCode()!=200) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("code", response.getStatusLine().getStatusCode());
                jsonObject.put("message", EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8));
                return jsonObject.toString();
            }
            return EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", 500);
            return jsonObject.toString();
        }finally {
            try {
                if (response!=null) {
                    response.close();
                }
                if (httpClient!=null) {
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值