为 httpclient 设置代理, 设置http头.

本文介绍如何使用Apache HttpClient 3.1版本通过校园网代理获取网络资源。主要讲解了如何设置代理服务器及其端口,并演示了如何通过设置HTTP头部来模拟浏览器行为。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在学校园网,要代理才可上网。写程序获取网上资源时,怎么办呢?同样可以为程序设置代理。我用HttpClient的3.1版本。有些网站要浏览器才可以访问,但程序可以仿浏览器,主要是设置http头。

在HostConfiguration.setProxy里设置。如下面代码:

  1. package com.chenlb;  
  2.   
  3. import java.io.IOException;  
  4. import java.util.ArrayList;  
  5. import java.util.List;  
  6.   
  7. import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;  
  8. import org.apache.commons.httpclient.Header;  
  9. import org.apache.commons.httpclient.HttpClient;  
  10. import org.apache.commons.httpclient.HttpException;  
  11. import org.apache.commons.httpclient.HttpStatus;  
  12. import org.apache.commons.httpclient.UsernamePasswordCredentials;  
  13. import org.apache.commons.httpclient.auth.AuthScope;  
  14. import org.apache.commons.httpclient.methods.GetMethod;  
  15. import org.apache.commons.httpclient.params.HttpMethodParams;  
  16.   
  17. public class HttpClientUse {  
  18.   
  19.     public static void main(String[] args) throws HttpException, IOException {  
  20.         HttpClient httpClient = new HttpClient();  
  21.   
  22.         httpClient.getHostConfiguration().setProxy("localhost"808);  
  23.   
  24.         /*//需要验证 
  25.         UsernamePasswordCredentials creds = new UsernamePasswordCredentials("chenlb", "123456"); 
  26.  
  27.         httpClient.getState().setProxyCredentials(AuthScope.ANY, creds); 
  28.         */  
  29.   
  30.         //设置http头  
  31.         List<Header> headers = new ArrayList<Header>();  
  32.         headers.add(new Header("User-Agent""Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)"));  
  33.         httpClient.getHostConfiguration().getParams().setParameter("http.default-headers", headers);  
  34.   
  35.         GetMethod method = new GetMethod("http://www.baidu.com");  
  36.         method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,  
  37.                 new DefaultHttpMethodRetryHandler(3false));  
  38.         try {  
  39.             int statusCode = httpClient.executeMethod(method);  
  40.   
  41.             if (statusCode != HttpStatus.SC_OK) {  
  42.                 System.out.println("Method failed code="+statusCode+": " + method.getStatusLine());  
  43.   
  44.             } else {  
  45.                 System.out.println(new String(method.getResponseBody(), "gb2312"));  
  46.             }  
  47.         } finally {  
  48.             method.releaseConnection();  
  49.         }  
  50.     }  
  51. }  

如果要用户名与密码验证的,请把/* */注释去掉。使验证有效。

验证,关键是:

  1. UsernamePasswordCredentials creds = new UsernamePasswordCredentials("chenlb""123456");  
  2.   
  3. httpClient.getState().setProxyCredentials(AuthScope.ANY, creds);  

设置http请求头.

  1. List<Header> headers = new ArrayList<Header>();  
  2. headers.add(new Header("User-Agent""Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)"));  
  3. httpClient.getHostConfiguration().getParams().setParameter("http.default-headers", headers);  
在 Java 中使用 Apache HttpClient 设置代理并访问 Microsoft API 需要以下几个步骤: 1. **添加依赖**: 首先确保你的项目已经包含了 Apache HttpClient 的依赖。如果没有,可以通过 Maven 或 Gradle 添加: - Maven: `<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.x.y</version> </dependency>` - Gradle: `implementation 'org.apache.httpcomponents:httpclient:x.y.z'` 2. **创建 ProxyConfiguration**: 创建一个表示代理设置的实例,包括代理主机名、端口、以及可能需要的身份验证凭据(如果需要的话): ```java HttpHost proxyHost = new HttpHost("your-proxy-host", your-proxy-port, "http"); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password); AuthScope authScope = new AuthScope(proxyHost.getHostHeader(), proxyHost.getPort()); CloseableHttpClient httpClient = HttpClients.custom() .setProxy(proxyHost) .setDefaultCredentialsProvider( new BasicCredentialsProvider().setCredentials(authScope, credentials)) .build(); ``` 3. **封装请求**: 使用 HttpClient 发送 GET 请求到 Microsoft API 地址: ```java String apiUrl = "https://your-microsoft-api-url"; HttpGet httpGet = new HttpGet(apiUrl); CloseableHttpResponse response = httpClient.execute(httpGet); // 处理响应... try (CloseableHttpResponse httpResponse = response) { // 获取内容 EntityUtils.consume(response.getEntity()); } finally { response.close(); } ``` 4. **处理异常**: 不忘记处理可能出现的异常,例如 `IOException`。 5. **关闭资源**: 当完成所有操作后,别忘了关闭 HttpClientHttpResponse: ```java httpClient.close(); ``` 注意:上述示例是一个基本的示例,实际应用中可能还需要处理超时、重试等场景。同时,微软 API 可能需要特定的认证机制,如 OAuth,这取决于具体的 API 文档说明。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值