1:概述
HttpClient是HttpComponents(简称为hc)项目其中的一部份,访问地址:http://hc.apache.org/
HttpClient是一个代码级的Http客户端工具,可以使用它模拟浏览器向Http服务器发送请求。使用HttpClient还需要HttpCore.后者包括Http请求与Http响应的代码封装。
2:HttpGet
public final static void main(String[] args) throws Exception {
HttpClient httpclient = new DefaultHttpClient();
try {
HttpGet httpget = new HttpGet("http://www.apache.org/");
System.out.println("executing request " + httpget.getURI());
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
}
System.out.println("----------------------------------------");
InputStream inSm = entity.getContent();
Scanner inScn = new Scanner(inSm);
while (inScn.hasNextLine()) {
System.out.println(inScn.nextLine());
}
// Do not feel like reading the response body
// Call abort on the request object 关闭
httpget.abort();
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources 关闭
httpclient.getConnectionManager().shutdown();
}
}
httpcore:EntityUtils.toString(httpEntity)
读取response响应内容部分,也可以借助于 httpcore-4.1.2.jar 里面的
String content = EntityUtils.toString(httpEntity);
具体:
public class Demo1 {
/**
* 用 get 方法访问 www.apache.org 并返回内容
*
* @param args
*/
public static void main(String[] args) {
//创建默认的 HttpClient 实例
HttpClient httpClient = new DefaultHttpClient();
try {
//创建 httpUriRequest 实例
HttpGet httpGet = new HttpGet("http://www.apache.org/");
System.out.println("uri=" + httpGet.getURI());
//执行 get 请求
HttpResponse httpResponse = httpClient.execute(httpGet);
//获取响应实体
HttpEntity httpEntity = httpResponse.getEntity();
//打印响应状态
System.out.println(httpResponse.getStatusLine());
if (httpEntity != null) {
//响应内容的长度
long length = httpEntity.getContentLength();
//响应内容
String content = EntityUtils.toString(httpEntity);
System.out.println("Response content length:" + length);
System.out.println("Response content:" + content);
}
//有些教程里没有下面这行
httpGet.abort();
} catch (Exception e) {
e.printStackTrace();
} finally {
//关闭连接,释放资源
httpClient.getConnectionManager().shutdown();
}
}
}
执行结果:
httpget.setHeader
1:分析请求包中这六个头信息
2:代码
public static void main(String[] args) {
HttpClient httpClient = new DefaultHttpClient();
try {
HttpGet httpget = new HttpGet("http://www.iteye.com");
httpget.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
httpget.setHeader("Accept-Language", "zh-cn,zh;q=0.5");
httpget.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 5.1; rv:7.0.1) Gecko/20100101 Firefox/7.0.1)");
httpget.setHeader("Accept-Encoding", "gzip, deflate");
httpget.setHeader("Accept-Charset", "GB2312,utf-8;q=0.7,*;q=0.7");
httpget.setHeader("Host", "www.iteye.com");
httpget.setHeader("Connection", "Keep-Alive");
HttpResponse response = httpClient.execute(httpget);
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
}
System.out.println("----------------------------------------");
InputStream inSm = entity.getContent();
Scanner inScn = new Scanner(inSm);
while (inScn.hasNextLine()) {
System.out.println(inScn.nextLine());
}
// Do not feel like reading the response body
// Call abort on the request object
httpget.abort();
} catch (Exception e) {
e.printStackTrace();
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpClient.getConnectionManager().shutdown();
}
}
3:效果
以上乱码是由于
httpget.setHeader("Accept-Encoding", "gzip, deflate");
注释掉这行就行
用post方法访问本地应用根据传递参数不同,返回不同结果
1:web.xml
<servlet>
<servlet-name>Test1Servlet</servlet-name>
<servlet-class>demo.servlet.Test1Servlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Test1Servlet</servlet-name>
<url-pattern>/test1Servlet</url-pattern>
</servlet-mapping>
2:Test1Servlet.java
public class Test1Servlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//接收地址栏参数
String param1 = request.getParameter("param1");
//输出
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.write("你传递来的参数param1=" + param1);
out.close();
}
}
3:Demo2.java
public class Demo2 {
/**
* 用post方法访问本地应用根据传递参数不同,返回不同结果
*
* @param args
*/
public static void main(String[] args) {
//创建默认的 HttpClient 实例
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://localhost:86/test1Servlet");
List<NameValuePair> formParams = new ArrayList<NameValuePair>();
formParams.add(new BasicNameValuePair("param1", "刘文涛"));
UrlEncodedFormEntity urlEncodedFormEntity;
try {
urlEncodedFormEntity = new UrlEncodedFormEntity(formParams, "UTF-8");
httpPost.setEntity(urlEncodedFormEntity);
System.out.println("execurting request:" + httpPost.getURI());
HttpResponse httpResponse = null;
httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity != null) {
String content = EntityUtils.toString(httpEntity, "UTF-8");
System.out.println("Response content:" + content);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭连接,释放资源
httpClient.getConnectionManager().shutdown();
}
}
}
结果:
分享到:
相关推荐
自己做的httpClient实例,写的比较多刚接触的可以看看
1. **创建HttpClient实例**:使用`HttpClientBuilder`或`HttpClients`静态工厂方法创建一个HttpClient实例。 ```java HttpClient httpClient = HttpClients.createDefault(); ``` 2. **构建HttpRequest**:...
要创建一个简单的HttpClient实例,你需要以下步骤: 1. 引入Apache HttpClient库: 在你的项目中,确保已经添加了Apache HttpClient的依赖。例如,如果你使用的是Maven,可以在pom.xml文件中添加以下依赖: ```...
// 从依赖注入容器中获取HttpClient实例 var httpClient = serviceProvider.GetService<HttpClient>(); ``` ### 2. 发送GET请求 `HttpClient`提供了`GetAsync`方法用于发送GET请求。下面是如何使用它的示例: ```...
在"HttpClient实例+必备3个jar包"的项目中,包含了以下关键知识点: 1. **HttpClient类库**:HttpClient库提供了丰富的API,可以创建复杂的HTTP请求,包括设置请求头、携带请求体、处理重定向、管理Cookie等。通过...
本实例将深入探讨如何在Java中使用HttpClient进行网络通信。 首先,你需要在项目中引入HttpClient的相关依赖。如果是Maven项目,可以在pom.xml文件中添加以下依赖: ```xml <groupId>org.apache.httpcomponents ...
实现调用远程servlet方法的实例。有详细注释。和依赖jar包。 //servlet路径 String url = "http://localhost:8080/zfw/servlet/CustomQueryServlet"; //参数一为表名,参数二为字段名 String params[] = {"ZC_...
1. **创建HttpClient对象**:首先,我们需要创建一个HttpClient实例,这通常是通过HttpClientBuilder或HttpAsyncClientBuilder构建的。例如: ```java CloseableHttpClient httpClient = HttpClients.create...
HttpClient用法,实例 HttpClient用法,实例 HttpClient用法,实例 HttpClient用法,实例
本开发实例将带你深入理解如何在Android项目中使用`HttpClient`进行网络请求,实现数据的获取和上传。 首先,`HttpClient`是Apache的一个开源项目,它提供了一个强大的API来处理HTTP协议。`commons-httpclient-3.1....
1. **创建HttpClient实例** 创建HttpClient实例是模拟登录的第一步。这可以通过`HttpClientBuilder`或直接使用`HttpClient`的静态工厂方法完成。例如: ```java CloseableHttpClient httpClient = HttpClients....
1. **HttpClient实例**:HttpClient是线程不安全的,所以通常推荐每个请求创建一个新实例。`HttpClientBuilder`类可以用来构建自定义配置的客户端实例。 2. **请求执行器(RequestExecutor)**:处理HTTP请求和响应...
HttpClient之Https应用实例~ 包含: HttpClient 使用代理访问Https HttpClient 信任所有主机-对于任何证书都不做检查 HttpClient 允许所有证书的校验(包括过期证书)
1. **创建HttpClient实例和PostMethod实例** ```java String url = ".newsmth.net/bbslogin2.php"; HttpClient httpClient = new HttpClient(); PostMethod postMethod = new PostMethod(url); ``` 2. **设置...
读者将学习到如何配置HttpClient实例,设置请求参数,处理响应,并通过源码分析了解其实现细节。同时,还会接触到日志管理和编码转换的相关知识,这些都是Java开发中与网络通信密切相关的技能。
1. 创建HttpClient实例:`CloseableHttpClient httpClient = HttpClients.createDefault();` 2. 构建请求:例如,`HttpGet httpGet = new HttpGet("http://example.com");` 3. 设置请求头:`httpGet.setHeader(...
命名客户端是指我们可以给 HttpClient 实例起一个名称,以便在后续的使用中可以根据名称来获取对应的 HttpClient 实例。我们可以使用以下代码来添加命名客户端: `services.AddHttpClient(Constants.SERVICE_USER...
本示例将深入探讨如何使用Apache HttpClient库在Java环境中调用Web服务,特别是通过Maven构建项目的方式进行。HttpClient是一个强大的HTTP客户端编程工具包,能够支持多种HTTP协议特性,使得Web服务调用变得更加灵活...