zoukankan      html  css  js  c++  java
  • java发送http设置代理

    使用"apache.commons.httpclient"

    添加依赖

     <dependency>
                <groupId>commons-httpclient</groupId>
                <artifactId>commons-httpclient</artifactId>
                <version>3.0</version>
     </dependency>

      

    public static String doJsonPost(String url,String json, Map<String, String> headerParams) {
            MultiThreadedHttpConnectionManager httpConnectionManager = new MultiThreadedHttpConnectionManager();
            httpConnectionManager.closeIdleConnections(MAX_IDLE_TIME_OUT);
            HttpClient httpClient = new HttpClient();
            PostMethod postMethod = new PostMethod(url);
          
            //设置代理服务器IP和端口号
            httpClient.getHostConfiguration().setProxy("11.11.11.11", 8080);
            //使用抢先认证
            httpClient.getParams().setAuthenticationPreemptive(true);
            //如果代理需要密码验证,这里设置用户名密码
            Credentials defaultcreds = new UsernamePasswordCredentials("username", "password");
            httpClient.getState().setProxyCredentials(AuthScope.ANY, defaultcreds);
    
            try {
                postMethod.addRequestHeader("Content-Type","application/x-www-form-urlencoded");
                postMethod.addRequestHeader("Pragma","no-cache");
                postMethod.addRequestHeader("Cache-Control:","no-cache");
                postMethod.setRequestBody(json);
                httpClient.executeMethod(postMethod);
                if(postMethod.getStatusCode() == HttpStatus.SC_OK || postMethod.getStatusCode() == HttpStatus.SC_BAD_REQUEST){
                    return postMethod.getResponseBodyAsString();
                }else {
                    postMethod.abort();
                }
            } catch (Exception e) {
            } finally {
                postMethod.releaseConnection();
            }
            return null;
        }

      

  • 相关阅读:
    几种常用的曲线
    0188. Best Time to Buy and Sell Stock IV (H)
    0074. Search a 2D Matrix (M)
    0189. Rotate Array (E)
    0148. Sort List (M)
    0859. Buddy Strings (E)
    0316. Remove Duplicate Letters (M)
    0452. Minimum Number of Arrows to Burst Balloons (M)
    0449. Serialize and Deserialize BST (M)
    0704. Binary Search (E)
  • 原文地址:https://www.cnblogs.com/yizw/p/13673165.html
Copyright © 2011-2022 走看看