`
Jatula
  • 浏览: 276696 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

HttpClient Examples:Request via a proxy

阅读更多

官方主頁:http://hc.apache.org/

 

Components

Request via a proxy

This example demonstrates how to send an HTTP request via a proxy.

 

请求通过一个代理

 

这个例子示范怎样去发送一个HTTP请求通过一个代理

 

package cn.lake.util;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.scheme.SocketFactory;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicHttpRequest;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.util.EntityUtils;

/**
 * How to send a request via proxy using {@link HttpClient HttpClient}.
 *
 * @author <a href="mailto:rolandw at apache.org">Roland Weber</a>
 *
 *
 * <!-- empty lines above to avoid 'svn diff' context problems -->
 * @version $Revision$
 *
 * @since 4.0
 */
public class ClientExecuteProxy {

	/**
	 * The default parameters.
	 * Instantiated in {@link #setup setup}.
	 */
	private static HttpParams defaultParameters = null;

	/**
	 * The scheme registry.
	 * Instantiated in {@link #setup setup}.
	 */
	private static SchemeRegistry supportedSchemes;

	/**
	 * Main entry point to this example.
	 *
	 * @param args      ignored
	 */
	public final static void main(String[] args) throws Exception {

		// make sure to use a proxy that supports CONNECT
		final HttpHost target = new HttpHost("issues.apache.org", 443, "https");
		final HttpHost proxy = new HttpHost("127.0.0.1", 8666, "http");

		setup(); // some general setup

		HttpClient client = createHttpClient();

		client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

		HttpRequest req = createRequest();

		System.out.println("executing request to " + target + " via " + proxy);
		HttpEntity entity = null;
		try {
			HttpResponse rsp = client.execute(target, req);
			entity = rsp.getEntity();

			System.out.println("----------------------------------------");
			System.out.println(rsp.getStatusLine());
			Header[] headers = rsp.getAllHeaders();
			for (int i = 0; i < headers.length; i++) {
				System.out.println(headers[i]);
			}
			System.out.println("----------------------------------------");

			if (rsp.getEntity() != null) {
				System.out.println(EntityUtils.toString(rsp.getEntity()));
			}

		} finally {
			// If we could be sure that the stream of the entity has been
			// closed, we wouldn't need this code to release the connection.
			// However, EntityUtils.toString(...) can throw an exception.

			// if there is no entity, the connection is already released
			if (entity != null)
				entity.consumeContent(); // release connection gracefully
		}
	} // main

	private final static HttpClient createHttpClient() {

		ClientConnectionManager ccm = new ThreadSafeClientConnManager(getParams(), supportedSchemes);
		//  new SingleClientConnManager(getParams(), supportedSchemes);

		DefaultHttpClient dhc = new DefaultHttpClient(ccm, getParams());

		return dhc;
	}

	/**
	 * Performs general setup.
	 * This should be called only once.
	 */
	private final static void setup() {

		supportedSchemes = new SchemeRegistry();

		// Register the "http" and "https" protocol schemes, they are
		// required by the default operator to look up socket factories.
		SocketFactory sf = PlainSocketFactory.getSocketFactory();
		supportedSchemes.register(new Scheme("http", sf, 80));
		sf = SSLSocketFactory.getSocketFactory();
		supportedSchemes.register(new Scheme("https", sf, 80));

		// prepare parameters
		HttpParams params = new BasicHttpParams();
		HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
		HttpProtocolParams.setContentCharset(params, "UTF-8");
		HttpProtocolParams.setUseExpectContinue(params, true);
		defaultParameters = params;

	} // setup

	private final static HttpParams getParams() {
		return defaultParameters;
	}

	/**
	 * Creates a request to execute in this example.
	 *
	 * @return  a request without an entity
	 */
	private final static HttpRequest createRequest() {

		HttpRequest req = new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1);
		//("OPTIONS", "*", HttpVersion.HTTP_1_1);

		return req;
	}

}

 

 

翻譯不好,請見諒!

分享到:
评论

相关推荐

    HttpClient问题:The server failed to respond with a valid HTTP resp

    在使用Apache HttpClient进行HTTP通信时,可能会遇到"HttpClient问题:The server failed to respond with a valid HTTP resp"这样的异常。这个错误通常表示服务器未能返回一个有效的HTTP响应,这可能是由多种原因...

    commons-httpclient-3.1jar包

    《Apache Commons HttpClient 3.1详解》 Apache Commons HttpClient 是一个功能强大的Java库,专为实现客户端HTTP通信而设计。这个3.1版本是HttpClient的一个重要里程碑,它提供了丰富的功能和改进,使得开发者能够...

    httpclient-4.5.12-API文档-中文版.zip

    Maven坐标:org.apache.httpcomponents:httpclient:4.5.12; 标签:apache、httpcomponents、httpclient、中文文档、jar包、java; 使用方法:解压翻译后的API文档,用浏览器打开“index.html”文件,即可纵览文档...

    httpclient-4.5.13-API文档-中文版.zip

    Maven坐标:org.apache.httpcomponents:httpclient:4.5.13; 标签:apache、httpcomponents、httpclient、jar包、java、中文文档; 使用方法:解压翻译后的API文档,用浏览器打开“index.html”文件,即可纵览文档...

    httpclient-4.5.13-API文档-中英对照版.zip

    Maven坐标:org.apache.httpcomponents:httpclient:4.5.13; 标签:apache、httpcomponents、httpclient、jar包、java、中英对照文档; 使用方法:解压翻译后的API文档,用浏览器打开“index.html”文件,即可纵览...

    可用org.apache.commons.httpclient-3.1.0.jar.zip

    import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.methods....

    Android Httpclient Proxy Test

    本文将深入探讨如何在Android中使用HttpClient进行代理设置,并结合具体的例子来阐述相关知识点。 首先,了解`HttpClient`是Apache的一个开源库,它提供了一个强大的、功能丰富的HTTP客户端API,使得开发者可以方便...

    commons-httpclient3.1.jar,commons-codec1.3.jar,commons-logging1.1.1.jar

    标题中的"commons-httpclient3.1.jar,commons-codec1.3.jar,commons-logging1.1.1.jar"指的是三个关键的Java库文件,它们是Apache HttpClient项目的一部分,用于在Java应用程序中实现HTTP通信。这些JAR(Java ...

    httpclient-4.5jar

    httpclient-4.5所需jar包,里面包含httpclient-4.5.jar等等10个必须的开发包。 1.commons-codec-1.9.jar 2.commons-logging-1.2.jar 3.fluent-hc-4.5.jar 4.httpclient-4.5.jar 5.httpclient-cache-4.5.jar 6....

    httpClient实例httpClient调用 http/https实例 忽略SSL验证

    HttpResponse response = httpClient.execute(request); ``` 现在,我们转向主题——忽略SSL验证。在生产环境中,SSL验证是必须的,以确保数据传输的安全性。但在开发或测试环境中,我们可能需要绕过这一环节。...

    httpclient-4.5.5-API文档-中文版.zip

    赠送jar包:httpclient-4.5.5.jar; 赠送原API文档:httpclient-4.5.5-javadoc.jar; 赠送源代码:httpclient-4.5.5-sources.jar; 包含翻译后的API文档:httpclient-4.5.5-javadoc-API文档-中文(简体)版.zip ...

    httpclient-4.5jar包

    《HttpClient 4.5详解与应用实践》 HttpClient是一个开源的Java库,由Apache软件基金会维护,主要用于在HTTP协议上实现客户端的通信。版本4.5是HttpClient的一个稳定版本,提供了许多增强的功能和优化,使其成为...

    ribbon-httpclient-2.2.5.jar

    ribbon-httpclient-2.2.5.jar

    HttpClientUtil:一个Http请求使用HttpClient访问服务器,我们也可以上传文件到服务器,比如文件或图片。它提供接口来更新你的上传进度

    - 创建 HttpClient 实例:首先,我们需要创建一个 HttpClient 实例,这可以通过 HttpClientBuilder 或直接使用 HttpClients.createDefault() 方法完成。 - 创建请求:然后,我们需要构造一个 HttpRequestBase 对象...

    httpclient、Request请求JAR包

    Request是对httpclient的封装,类似于python的request库,用法Request.Get(pictureUrl).execute().returnContent().toString();需要以来httpclient和httpcore包。2020年1月更新。

    commons-httpclient-3.0.jar JAVA中使用HttpClient可以用到

    《JAVA中使用HttpClient:commons-httpclient-3.0.jar详解》 在JAVA开发中,进行HTTP请求时,Apache的HttpClient库是一个不可或缺的工具。本文将深入解析`commons-httpclient-3.0.jar`,它是HttpClient的一个重要...

    jetty-reactive-httpclient:码头ReactiveStreams HttpClient

    码头ReactiveStream HttpClient 围绕的包装器。...// Create a request using the HttpClient APIs.Request request = httpClient . newRequest( " http://localhost:8080/path " );// Wrap the request using the

    org.apache.commons.httpclient-3.1.jar

    《Apache Commons HttpClient 3.1:HTTP客户端编程的基石》 ...然而,需要注意的是,HttpClient 3.1已不再维护,最新的稳定版本为HttpClient 4.x,对于新项目建议使用更现代的版本以获取更好的性能和兼容性。

    httpclient-4.5.jar

    在这个版本中,我们关注的是`httpclient-4.5.jar`,这是一个包含了HttpClient 4.5核心功能的Java库。这个库的发布日期为2016年7月19日,它提供了许多改进和新特性,旨在帮助开发者更高效、更稳定地构建网络应用程序...

    wechatpay-apache-httpclient:微信支付 APIv3 Apache HttpClient装饰器(decorator)

    wechatpay-apache-httpclient 概览 的扩展,实现了请求签名的生成和应答签名的验证。...implementation 'com.github.wechatpay-apiv3:wechatpay-apache-httpclient:0.2.2' Maven 加入以下依赖 &lt;groupId&gt;com.github.w

Global site tag (gtag.js) - Google Analytics