`
coffee_yan
  • 浏览: 36605 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

HttpClient4.3.5使用代理创建实例并发送请求

阅读更多
	public String xmlHttpPost(String requestInfo, String urlAddress, boolean isProxy, 
			String proxyHost, int proxyPort, ContentType contentType) {
		String responseInfo = null;
		InputStream inputResStream = null;
		try {
			CloseableHttpClient httpClient = null;
			if (isProxy) {
				HttpHost proxy = new HttpHost(proxyHost, proxyPort);
				DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
				httpClient = HttpClients.custom().setRoutePlanner(routePlanner).build();
			}else{
				httpClient = HttpClients.createDefault();
			}
			StringEntity stringEntity = new StringEntity(requestInfo, contentType);
			HttpPost post = new HttpPost(urlAddress);
			post.setEntity(stringEntity);

			log.info("urlAddress: " + urlAddress.trim() + " proxyHost: " + proxyHost.trim() + " proxyPort: " + proxyPort);
			CloseableHttpResponse response = httpClient.execute(post);
			try {
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					inputResStream = entity.getContent();
					try {
						BufferedReader br = new BufferedReader(new InputStreamReader(inputResStream));
						StringBuffer resBuffer = new StringBuffer();
						String resTemp = "";
						while ((resTemp = br.readLine()) != null) {
							resBuffer.append(resTemp);
						}
						responseInfo = resBuffer.toString();
					} finally {
						inputResStream.close();
					}
				}
			} finally {
				response.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return responseInfo;
	}
0
1
分享到:
评论

相关推荐

    httpclient4.3.5

    1. **创建HttpClient实例**:首先需要创建一个HttpClient对象,可以选择预设的HttpClientBuilder或直接使用DefaultHttpClient。 2. **设置请求参数**:包括URL、HTTP方法(GET、POST等)、请求头、实体内容等。 3....

    httpclient-4.3.5

    通过构建一个HttpClient实例,我们可以配置各种连接参数,如连接超时、重试策略等,并发起HTTP请求。 2. `HttpRequestBase`:这是一个抽象类,代表HTTP请求的基本实现,如HttpGet、HttpPost等。开发者可以根据需求...

    httpcomponents-client-4.3.5.zip

    - **线程安全**:HttpClient实例不是线程安全的,如果在多线程环境中使用,需要为每个线程创建单独的实例或者使用线程局部变量。 Apache HttpClient 4.3.5作为一款强大的HTTP客户端工具,不仅提供了丰富的功能,...

    httpclient需要的jar包

    在使用过程中,了解如何创建HttpClient实例,设置请求头,处理响应,以及如何正确关闭资源是非常重要的。 例如,一个简单的GET请求可能如下所示: ```java CloseableHttpClient httpClient = HttpClients.create...

    httppost上传文件需要的两个jar

    6. 执行请求:通过`httpClient.execute(httpPost)`发送请求并获取响应。 7. 处理响应:检查响应状态码,获取响应实体并进行后续处理。 8. 关闭资源:使用`httpClient.close()`关闭连接。 文件上传是Web开发中的...

    图灵机器人使用的jar包

    在实际使用中,开发者首先需要将这三个JAR文件添加到项目的类路径中,然后可以通过HttpClient的相关API来构建HTTP请求,例如创建`CloseableHttpClient`实例,定义`HttpGet`或`HttpPost`对象,并设置必要的请求头和...

    jt07日常笔记

    - 它允许开发者轻松地发送HTTP请求,并处理来自服务器的响应。 - **使用HttpClient发起HTTP请求**: - 通过引入HttpClient依赖,可以在Java代码中模拟HTTP请求,获取响应数据。 - 常见应用场景包括数据抓取...

Global site tag (gtag.js) - Google Analytics