zoukankan      html  css  js  c++  java
  • java http get/post请求

    一、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;
        }
  • 相关阅读:
    杂谈
    分享一首歌——美丽的万物
    Silverlight有感
    风云的银光志Silverlight4.0教程之打印报表和图形(转)
    IIS 7.0的集成模式和经典模式
    WPF中MVVM模式原理分析与实践(转)
    使用HTTP_X_FORWARDED_FOR获取客户端IP的严重后果
    各大网站架构总结笔记(转)
    做了几天silverlight 小结一下
    Fiddler2介绍
  • 原文地址:https://www.cnblogs.com/chenweichu/p/11762016.html
Copyright © 2011-2022 走看看