首页 > 编程语言 > 详细

java http get/post请求

时间:2019-10-29 23:13:37      阅读:85      评论:0      收藏:0      [点我收藏+]

一、http get/post请求

    /**
     * @Description httpPost请求
     */
    public static String httpPost(String url, String jsonParam, String userName, String password) {
        String responseResult = "";
        try{
            CloseableHttpClient httpClient = HttpClients.createDefault();
            RequestConfig requestConfig = RequestConfig.custom()
                    .setSocketTimeout(300 * 1000)
                    .setConnectTimeout(300 * 1000)
                    .build();

            HttpPost post = new HttpPost(url);

            if(StringUtils.isNotBlank(userName) && StringUtils.isNotBlank(password)){
                post.addHeader("Authorization", "Basic " + encode(userName+":"+password));
            }

            post.setConfig(requestConfig);
            post.setHeader("Content-Type","application/json;charset=utf-8");
            StringEntity postingString = new StringEntity(jsonParam,"utf-8");

            post.setEntity(postingString);
            HttpResponse response = httpClient.execute(post);
            responseResult = EntityUtils.toString(response.getEntity());

        }catch (Exception e){
            logger.error(e.getMessage(),e);
        }

        return responseResult;
    }


    /**
     * @Description httpGet请求
     */
    public static final String get(String url) {
        String result = "";
        HttpClient client = new HttpClient();
        GetMethod method = new GetMethod(url);
        method.addRequestHeader("User-Agent", DEFAULT_USER_AGENT);
        try {
            client.executeMethod(method);
            result = method.getResponseBodyAsString();
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        } finally {
            method.releaseConnection();
        }
        return result;
    }

 

java http get/post请求

原文:https://www.cnblogs.com/chenweichu/p/11762016.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!