`

httpclient4.x配置带用户名和密码的代理

    博客分类:
  • java
阅读更多

package test;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.NTCredentials;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;


public class ClientProxy {
   
    private static String PROXY_HOST="";
    private static int PROXY_PORT=8080;
    private static String PROXY_USERNAME="";
    private static String PROXY_PASSWORD="";
    private static String PROXY_WORKSTATION="";
    private static String PROXY_DOMAIN="";
    private static String TARGET_HOST="";
    private static String TARGET_GETURL="/index.html";
   
    public static void main(String[] args) throws Exception {

        DefaultHttpClient httpclient = new DefaultHttpClient();
        try {
            AuthScope authscope=new AuthScope(PROXY_HOST, PROXY_PORT);
            Credentials credentials=new NTCredentials(PROXY_USERNAME,PROXY_PASSWORD,PROXY_WORKSTATION,PROXY_DOMAIN);
            httpclient.getCredentialsProvider().setCredentials(authscope,credentials);
            HttpHost targetHost = new HttpHost(TARGET_HOST);
            HttpHost proxy = new HttpHost(PROXY_HOST, PROXY_PORT);
            httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
            HttpGet httpget = new HttpGet(TARGET_GETURL);
           
            System.out.println("executing request: " + httpget.getRequestLine());
            System.out.println("via proxy: " + proxy);
            System.out.println("to target: " + targetHost);
            HttpResponse response = httpclient.execute(targetHost, httpget);
            HttpEntity entity = response.getEntity();
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            if (entity != null) {
                System.out.println("Response content length: " + entity.getContentLength());
            }
            EntityUtils.consume(entity);
        } finally {
            httpclient.getConnectionManager().shutdown();
        }
    }
}

分享到:
评论
2 楼 bewithme 2013-08-12  
HTTP/1.1 407 Proxy Authentication Required ( The ISA Server requires authorization to fulfill the request. Access to the Web Proxy service is denied.  )
Response content length: 3997
1 楼 bewithme 2013-08-12  
我使用这个方法时会报严重: Proxy authentication error: Invalid name provided (Mechanism level: Could not load configuration file D:\WINDOWS\krb5.ini (系统找不到指定的文件。))
这个错,,
但我用包来实现却没有问题,请指教呀大侠,QQ359709421
org.apache.commons.httpclient.HttpClient

相关推荐

Global site tag (gtag.js) - Google Analytics