import org.apache.http.*;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeaderElementIterator;
import org.apache.http.message.BasicHttpResponse;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
/**
* Created by zhanghaibin on 2018/6/11.
*/
public class HttpClientTest {
public static void test1() {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://localhost/");
HttpResponse response = null;
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
int l;
byte[] tmp = new byte[2048];
while ((l = instream.read(tmp)) != -1) {
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
// HTTP 请求(Request)
public static void request() {
URI uri = null;
try {
uri = new URIBuilder()
.setScheme("http")
.setHost("www.google.com")
.setPath("/search")
.setParameter("q", "httpclient")
.setParameter("btnG", "Google Search")
.setParameter("aq", "f")
.setParameter("oq", "")
.build();
} catch (URISyntaxException e) {
e.printStackTrace();
}
HttpGet httpget = new HttpGet(uri);
System.out.println(httpget.getURI());
}
// HTTP 响应(Response)
public static void response() {
HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1
, HttpStatus.SC_OK, "OK");
System.out.println(response.getProtocolVersion());
System.out.println(response.getStatusLine().getStatusCode());
System.out.println(response.getStatusLine().getReasonPhrase());
System.out.println(response.getStatusLine().toString());
}
// 处理报文首部(Headers)
public static void headers() {
HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK");
response.addHeader("Set-Cookie", "c1=a; path=/; domain=localhost");
response.addHeader("Set-Cookie", "c2=b; path=\"/\", c3=c; domain=\"localhost\"");
Header h1 = response.getFirstHeader("Set-Cookie");
System.out.println(h1);
Header h2 = response.getLastHeader("Set-Cookie");
System.out.println(h2);
Header[] hs = response.getHeaders("Set-Cookie");
System.out.println(hs.length);
// ==============获得所有指定类型首部最有效的方式是使用HeaderIterator接口====================================
response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK");
response.addHeader("Set-Cookie", "c1=a; path=/; domain=localhost");
response.addHeader("Set-Cookie", "c2=b; path=\"/\", c3=c; domain=\"localhost\"");
HeaderIterator it = response.headerIterator("Set-Cookie");
while (it.hasNext()) {
System.out.println(it.next());
}
// =============================HttpClient也提供了其他便利的方法吧HTTP报文转化为单个的HTTP元素。=====================================
response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK");
response.addHeader("Set-Cookie", "c1=a; path=/; domain=localhost");
response.addHeader("Set-Cookie", "c2=b; path=\"/\", c3=c; domain=\"localhost\"");
HeaderElementIterator hei = new BasicHeaderElementIterator(
response.headerIterator("Set-Cookie"));
while (hei.hasNext()) {
HeaderElement elem = hei.nextElement();
System.out.println(elem.getName() + " = " + elem.getValue());
NameValuePair[] params = elem.getParameters();
for (int i = 0; i < params.length; i++) {
System.out.println(" " + params[i]);
}
}
}
// HTTP实体(HTTP Entity)
public static void createEntity() {
try {
StringEntity myEntity = new StringEntity("important message",
ContentType.create("text/plain", "UTF-8"));
System.out.println(myEntity.getContentType());
System.out.println(myEntity.getContentLength());
System.out.println(EntityUtils.toString(myEntity));
System.out.println(EntityUtils.toByteArray(myEntity).length);
// 某些情况,整个响应内容的仅仅一小部分需要被取出,会使消费其他剩余内容的性能代价和连接可重用性代价太高,
// 这时可以通过关闭响应来终止内容流
// (例子中可以看出,实体输入流仅仅读取了两个字节,就关闭了响应,也就是按需读取,而不是读取全部响应)
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpget = new HttpGet("http://localhost/");
CloseableHttpResponse response = httpclient.execute(httpget);
try {
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
int byteOne = instream.read();
int byteTwo = instream.read();
// Do not need the rest
}
} finally {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
// HTML表单
public static void createNameValuePair() {
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("param1", "value1"));
formparams.add(new BasicNameValuePair("param2", "value2"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams,
Consts.UTF_8);
HttpPost httppost = new HttpPost("http://localhost/handler.do");
httppost.setEntity(entity);
}
// 使用内容分块
public static void useChunked() {
StringEntity entity = new StringEntity("important message",
ContentType.create("plain/text", Consts.UTF_8));
entity.setChunked(true);
HttpPost httppost = new HttpPost("http://localhost/acrtion.do");
httppost.setEntity(entity);
}
// 响应处理
public static void handlerResponse() {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("https://blog.csdn.net/u011179993/article/details/47251909");
ResponseHandler<byte[]> handler = new ResponseHandler<byte[]>() {
public byte[] handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
HttpEntity entity = response.getEntity();
if (entity != null) {
ByteArrayOutputStream result = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = entity.getContent().read(buffer)) != -1) {
result.write(buffer, 0, length);
}
System.out.println(result.toString());
return EntityUtils.toByteArray(entity);
} else {
return null;
}
}
};
byte[] response = httpclient.execute(httpget, handler);
} catch (IOException e) {
e.printStackTrace();
}
}
//HTTP执行环境
public static void zhixinghuanjing() {
try {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpget = new HttpGet("https://blog.csdn.net/u011179993/article/details/47251909");
HttpResponse response = httpclient.execute(httpget, localContext);
HttpHost target = (HttpHost) localContext.getAttribute(
ExecutionContext.HTTP_TARGET_HOST);
System.out.println("Final target: " + target);
HttpEntity entity = response.getEntity();
if (entity != null) {
entity.consumeContent();
}
} catch (IOException e) {
e.printStackTrace();
}
}
// 上下文
public static void context() {
HttpContext context = new BasicHttpContext();
context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, new HttpHost("127.0.0.1:8bhb"));
HttpClientContext clientContext = HttpClientContext.adapt(context);
HttpHost target = clientContext.getTargetHost();
HttpRequest request = clientContext.getRequest();
HttpResponse response = clientContext.getResponse();
RequestConfig config = clientContext.getRequestConfig();
System.out.println(target);
System.out.println(target.getHostName());
System.out.println(request);
System.out.println(response);
System.out.println(config);
}
public static void main(String[] args) {
//test1();
/*request();
response();
headers();
createEntity();
createNameValuePair();*/
//handlerResponse();
//zhixinghuanjing();
context();
}
}
分享到:
相关推荐
1. **创建HttpClient实例**:使用`HttpClientBuilder`或`HttpClients`静态工厂方法创建一个HttpClient实例。 ```java HttpClient httpClient = HttpClients.createDefault(); ``` 2. **构建HttpRequest**:...
本文档主要介绍了如何在JSP中使用HttpClient发起POST请求,包括POST方法的基本概念、使用步骤以及具体实例。这对于理解如何通过HttpClient在JSP中发送POST请求非常有帮助。 #### 二、POST方法的概念 POST方法是一种...
// 从依赖注入容器中获取HttpClient实例 var httpClient = serviceProvider.GetService<HttpClient>(); ``` ### 2. 发送GET请求 `HttpClient`提供了`GetAsync`方法用于发送GET请求。下面是如何使用它的示例: ```...
首先,了解HttpClient的基本使用。HttpClient是一个灵活且强大的HTTP客户端API,它允许开发者执行各种HTTP方法(如GET、POST等),处理响应,以及管理连接池。要创建一个简单的HttpClient实例,你需要以下步骤: 1....
在"HttpClient实例+必备3个jar包"的项目中,包含了以下关键知识点: 1. **HttpClient类库**:HttpClient库提供了丰富的API,可以创建复杂的HTTP请求,包括设置请求头、携带请求体、处理重定向、管理Cookie等。通过...
然而,在使用 HttpClient 时,我们需要注意一些重要的配置和使用方法,以避免一些常见的错误。 一、基本用法 在 .NET CORE 中,我们可以使用 IHttpClientFactory 来创建 HttpClient,以解决之前的种种问题。...
本实例将深入探讨如何在Java中使用HttpClient进行网络通信。 首先,你需要在项目中引入HttpClient的相关依赖。如果是Maven项目,可以在pom.xml文件中添加以下依赖: ```xml <groupId>org.apache.httpcomponents ...
1. **创建HttpClient对象**:首先,我们需要创建一个HttpClient实例,这通常是通过HttpClientBuilder或HttpAsyncClientBuilder构建的。例如: ```java CloseableHttpClient httpClient = HttpClients.create...
总的来说,`HttpClient`是Android开发中处理网络请求的重要工具,虽然现在有其他的替代方案,如OkHttp和Retrofit,但理解它的原理和使用方法对于开发者来说仍然是有益的。通过这个实例,你可以了解到网络通信的基本...
首先,我们需要理解HttpClient的基本使用。HttpClient的核心类包括HttpClient本身,HttpGet、HttpPost等请求方法,以及EntityEnclosingRequest接口,用于处理带有实体(如表单数据)的请求。在模拟登录时,我们通常...
这个实例“httpclient实例”专注于在Servlet之间通过HttpClient传递数据流。我们先来理解HttpClient的基本概念,然后深入探讨如何在Servlet环境中应用它。 HttpClient是由Apache基金会开发的一个Java库,它提供了...
首先,创建一个新的HttpClient实例非常简单,你可以通过`HttpClient.newBuilder()`方法来实现。这个构建器提供了丰富的选项,允许你根据需求定制HttpClient的行为。例如: ```java HttpClient client = HttpClient....
### httpclient使用教程 #### HttpClient概述与重要性 ... ...#### HttpClient关键特性...此教程不仅介绍了HttpClient的基本使用方法,还强调了资源管理和异常处理的重要性,是Java开发者处理HTTP通信不可或缺的技能之一。
3. **执行请求**:使用HttpClient实例的execute方法发送请求,并获取HttpResponse。 4. **处理响应**:检查响应状态码,读取响应头和实体内容,进行必要的处理。 5. **关闭资源**:执行完请求后,关闭HttpClient和...
在本文中,我们将深入探讨HttpClient的核心概念、使用方法以及如何通过`httpclient.jar`进行实战应用。 首先,HttpClient的主要组件包括: 1. **HttpClient实例**:这是整个HTTP通信的核心,负责管理连接、请求和...
在"使用说明.txt"中,通常会详细阐述如何配置和使用这些jar包,包括添加到项目构建路径、初始化HttpClient实例、构造请求、解析响应等内容,对于初学者来说是非常有价值的参考资料。务必仔细阅读并按照指导进行操作...
- 避免长时间持有HttpClient实例,推荐使用`CloseableHttpClient`并在使用完毕后关闭。 - 根据实际需求配置连接超时和读取超时。 总之,使用HttpClient访问Servlet能够简化Java应用之间的通信,特别是在分布式...
一、HttpClient基本使用 HttpClient主要由以下几个核心组件构成: 1. HttpClient:客户端实例,负责管理连接、配置请求等。 2. HttpRequestBase:表示HTTP请求,如GET、POST等。 3. HttpResponse:表示HTTP响应,...
在“httpclient.zip”中的工具类,可能包含了一些预配置的HTTPClient实例,优化了连接池设置,处理了SSL/TLS认证,或者提供了一些便捷的方法来构造HTTP请求和解析响应。这样的工具类通常会简化代码,提高代码的...
1. **创建HttpClient对象**:使用`HttpClientBuilder`或`HttpAsyncClientBuilder`构建HttpClient实例。 2. **构建HttpGet/HttpPost请求**:根据需求创建`HttpGet`或`HttpPost`对象,并设置URL、请求头等信息。 3. **...