`

Apache HttpClient Demo

阅读更多
一 建立web服务HttpServer。
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" 
xmlns="http://java.sun.com/xml/ns/j2ee" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
	<display-name>HttpServer</display-name>
	<filter>
		<filter-name>UserPermissionFilter</filter-name>
		<filter-class>filter.UserPermissionFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>UserPermissionFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	<servlet>
		<display-name>LoginServlet</display-name>
		<servlet-name>LoginServlet</servlet-name>
		<servlet-class>servlet.LoginServlet</servlet-class>
	</servlet>
	<servlet>
		<display-name>PostXMLServlet</display-name>
		<servlet-name>PostXMLServlet</servlet-name>
		<servlet-class>servlet.PostXMLServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>LoginServlet</servlet-name>
		<url-pattern>/LoginServlet</url-pattern>
	</servlet-mapping>
	<servlet-mapping>
		<servlet-name>PostXMLServlet</servlet-name>
		<url-pattern>/PostXMLServlet</url-pattern>
	</servlet-mapping>
</web-app>

login.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
	<form action="LoginServlet" method="post">
		username:<input type="text" name="username"/><br/>
		password:<input type="password" name="password"/><br/>
		<input type="submit" value="login"/>
	</form>
</body>
</html>

main.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
	<h1>This is the main page.</h1>
</body>
</html>

UserPermissionFilter.java
package filter;
import java.io.IOException;
import java.util.Arrays;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
public class UserPermissionFilter implements Filter {
	private String[] excludedUri={"/HttpServer/LoginServlet",
								  "/HttpServer/PostXMLServlet"};
	public void destroy() {}
	public void doFilter(ServletRequest request, 
						 ServletResponse response, 
						 FilterChain chain)
	throws IOException, ServletException {
		HttpServletRequest httpRequest=(HttpServletRequest) request;
		
		if(!Arrays.asList(excludedUri).contains(httpRequest.getRequestURI())){
			String user=(String) httpRequest.getSession().getAttribute("user");
			if(user==null||"".equals(user)){
				request.getRequestDispatcher("/login.jsp")
					   .forward(request, response);
				return;
			}
		}
		chain.doFilter(request, response);
	}
	public void init(FilterConfig fConfig) throws ServletException {}
}

LoginServlet.java
package servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	protected void doGet(HttpServletRequest request, 
						 HttpServletResponse response) 
						 throws ServletException, IOException {
		doPost(request,response);
	}
	protected void doPost(HttpServletRequest request, 
						  HttpServletResponse response) 
						  throws ServletException, IOException {
		String username=request.getParameter("username");
		String password=request.getParameter("password");
		if("admin".equals(username)&&"admin".equals(password)){
			request.getSession().setAttribute("user", username);
			response.getWriter().write("Login Success!");
		}else{
			response.sendRedirect("/HttpServer/login.jsp");
		}
	}
}

PostXMLServlet.java
package servlet;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class PostXMLServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	protected void doGet(HttpServletRequest request, 
			      		 HttpServletResponse response) 
			      		 throws ServletException, IOException {
		doPost(request,response);
	}
	protected void doPost(HttpServletRequest request, 
						  HttpServletResponse response) 
						  throws ServletException, IOException {
		BufferedReader br = new BufferedReader(
							new InputStreamReader(request.getInputStream()));
		String line=null;
		while((line=br.readLine())!=null){
			System.out.println(line);
		}
		br.close();
	}
}

HttpServer用于接收客户端请求。除了请求路径/HttpServer/LoginServlet和/HttpServer/PostXMLServlet都要做用户校验。如果校验为通过则返回login.jsp页面。


二 客户端测试
要引入外部jar包 httpclient-4.2.3.jar httpcore-4.2.2.jar commons-logging-1.0.4.jar

1.测试用户登录
LoginClient.java
package http.client;
import http.Utils;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
public class LoginClient {
	@SuppressWarnings("deprecation")
	public static void main(String[] args) throws Exception {
		HttpClient httpclient = new DefaultHttpClient();
		/* initialize the request method */
		// prepare the request url
		HttpPost httpPost = new HttpPost("http://localhost:7070/HttpServer/LoginServlet");
		// prepare the request parameters
		List<NameValuePair> params=new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("username","admin"));
		params.add(new BasicNameValuePair("password","admin"));
		// set the request entity
		httpPost.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
		
		/* execute the request */
		System.out.println("executing request " + httpPost.getURI());
		HttpResponse response = httpclient.execute(httpPost);

		/* check whether it has relocated */
		int statusCode = response.getStatusLine().getStatusCode();
		if (statusCode == HttpStatus.SC_MOVED_TEMPORARILY || 
			statusCode == HttpStatus.SC_MOVED_PERMANENTLY ||
			statusCode == HttpStatus.SC_SEE_OTHER || 
			statusCode == HttpStatus.SC_TEMPORARY_REDIRECT){
			
			Header[] headers = response.getHeaders("location");
			
			if (headers != null) {
				httpPost.releaseConnection();
				String newUrl = headers[0].getValue();
				httpPost.setURI(URI.create(newUrl));
				response = httpclient.execute(httpPost);
			}
		}
		/* print the result of the request */
		Utils.printResponse(response);
		// Do not feel like reading the response body
		// Call abort on the request object
		httpPost.abort();
		// When HttpClient instance is no longer needed,
		// shut down the connection manager to ensure
		// immediate deallocation of all system resources
		httpclient.getConnectionManager().shutdown();
	}
}

如果传入的用户名密码正确那直接返回login success成功信息,否则返回login.jsp页面。

2. 通过2次请求直接访问main.jsp页面。第一次请求用户登录,第二次请求则访问main.jsp
RequestMainClient.java

package http.client;
import http.Utils;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
public class RequestMainClient {
	@SuppressWarnings("deprecation")
	public static void main(String[] args)throws Exception {
		HttpClient httpclient = new DefaultHttpClient();
		/* execute login operation */
		// prepare the request url
		HttpPost httpPost = new HttpPost("http://localhost:7070/HttpServer/LoginServlet");
		// prepare the request parameters
		List<NameValuePair> params=new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("username","admin"));
		params.add(new BasicNameValuePair("password","admin"));
		// set the request entity
		httpPost.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
		
		System.out.println("executing request " + httpPost.getURI());
		HttpResponse response =httpclient.execute(httpPost);

		/* request main page */
		httpPost.releaseConnection();
		httpPost=new HttpPost("http://localhost:7070/HttpServer/main.jsp");  
		response = httpclient.execute(httpPost);
		/* print the result of the request */
		Utils.printResponse(response);
		// Do not feel like reading the response body
		// Call abort on the request object
		httpPost.abort();
		// When HttpClient instance is no longer needed,
		// shut down the connection manager to ensure
		// immediate deallocation of all system resources
		httpclient.getConnectionManager().shutdown();
	}
}

如果第一次请求登录成功则第二次请求可以直接访问main.jsp, 否则第二次将会返回login.jsp


3.提交实体数据(这里为xml文件)
PostXMLClient.java

package http.client;
import http.Utils;
import java.io.File;
import java.net.URL;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.FileEntity;
import org.apache.http.impl.client.DefaultHttpClient;
public class PostXMLClient {
	public static void main(String[] args) throws Exception {
		HttpClient httpclient = new DefaultHttpClient();
		/* initialize the request method */
		// prepare the request url
		HttpPost httpPost = new HttpPost("http://localhost:7070/HttpServer/PostXMLServlet");
		
		URL url=PostXMLClient.class.getClassLoader().getResource("http/fruits.xml");
		File file=new File(url.getFile());
		System.out.println(file.exists());
		
		httpPost.setEntity(new FileEntity(file,ContentType.TEXT_XML));
		 
		/* execute operation */
		System.out.println("executing request " + httpPost.getURI());
		HttpResponse response =httpclient.execute(httpPost);

		/* print the result of the request */
		Utils.printResponse(response);
		
		// Do not feel like reading the response body
		// Call abort on the request object
		httpPost.abort();
		// When HttpClient instance is no longer needed,
		// shut down the connection manager to ensure
		// immediate deallocation of all system resources
		httpclient.getConnectionManager().shutdown();
	}
}

fruits.xml
<?xml version="1.0" encoding="UTF-8"?>
<fruits>
	<fruit>
		<name>apple</name>
		<price>10</price>
	</fruit>
	<fruit>
		<name>orange</name>
		<price>4</price>
	</fruit>
</fruits>

Utils.java
package http;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
public class Utils {
	public static void printResponse(HttpResponse response)throws Exception{
		/* print the result of the request */
		HttpEntity entity = response.getEntity();
		System.out.println("--------------------");
		// print the status line 
		System.out.println(response.getStatusLine());
		// print the headers
		System.out.println("========== headers ==========");
		Header[] headers=response.getAllHeaders();
		for(Header header:headers){
			System.out.println(header);
		}
		// print the content length
		if (entity != null) {
			System.out.println("\nResponse content length: "+ 
								entity.getContentLength());
		}
		// print the entity content
		System.out.println("\n========== response content ==========");
		BufferedReader is=new BufferedReader(
						  new InputStreamReader(entity.getContent()));
		String line=null;
		while((line=is.readLine())!=null){
			System.out.println(line);
		}
		System.out.println("--------------------");
	}
}
分享到:
评论
4 楼 longdie237 2014-07-29  
感谢楼主
3 楼 lijiejava 2013-02-27  
antlove 写道
lijiejava 写道

大哥你看了么?


????
2 楼 antlove 2013-02-27  
lijiejava 写道

大哥你看了么?
1 楼 lijiejava 2013-02-26  

相关推荐

    httpClient完整请求Demo

    HttpClient是Apache基金会开发的一个Java库,用于执行HTTP请求。...本示例将深入讲解如何使用HttpClient进行完整的HTTP请求,同时结合JSON数据处理,因为"json...希望这个Demo能帮助你在实际项目中更好地运用HttpClient。

    httpclient Demo 案例 含jar

    Apache HttpClient是一个强大的开源库,它提供了丰富的功能,用于执行HTTP请求和管理响应。在这个“httpclient Demo 案例 含jar”中,我们将深入探讨如何使用HttpClient来处理POST请求时传递参数的字符原样问题,即...

    android httpclient demo

    首先,`Android HttpClient`是Apache HTTP Client的一个实现,适用于Android平台。它提供了丰富的API,用于构造和执行HTTP请求。然而,由于Android API Level 23之后不再支持HttpClient,开发者现在更多地转向使用...

    HttpClient Demo

    HttpClient是Apache基金会开发的一个Java库,用于执行HTTP请求。它为开发者提供了强大的功能,包括连接管理、重试机制、身份验证、以及支持HTTP/1.1和部分HTTP/2协议。HttpClient 4.3版本是该库的一个稳定版本,包含...

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

    wechatpay-apache-httpclient 概览 的扩展,实现了请求签名的生成和应答签名的验证。 如果你是使用Apache HttpClient的商户开发者,可以使用它构造HttpClient。得到的HttpClient在执行请求时将自动携带身份认证信息...

    httpclient Demo

    HttpClient是Apache基金会开发的一个HTTP客户端库,用于在Java应用程序中执行HTTP请求。它提供了丰富的功能,包括支持HTTP、HTTPS协议,处理Cookie、重定向、管理HTTP连接等,是进行网络编程的重要工具。在这个...

    HttpClient_Demo

    HttpClient_Demo是一个示例项目,它展示了如何在Java应用程序中使用Apache HttpClient库来实现HTTP客户端功能。在这个项目中,我们可以学习到以下关键知识点: 1. **HttpClient库介绍**:HttpClient是Apache软件...

    httpclient(springboot)demo

    本篇将详细介绍如何在Spring Boot项目中整合HttpClient,以及这个整合的示例(demo)所涉及的关键知识点。 首先,让我们理解Spring Boot与HttpClient的整合过程: 1. **添加依赖**:在`pom.xml`文件中,你需要引入...

    apachehttp demo

    在这个"apachehttp demo"中,我们将探讨如何利用Apache HTTP Client库进行资源下载操作。Apache HTTP Client是一个Java库,允许开发者构建应用程序来与HTTP服务器进行交互,支持各种HTTP协议特性。 首先,我们需要...

    HttpClient抓取网页Demo

    HttpClient是Apache基金会开发的一个Java库,它为Java程序员提供了一个强大的工具来执行HTTP请求并处理响应。HttpClient允许你模拟浏览器行为,发送GET、POST以及其他HTTP方法的请求,并处理服务器返回的各种内容,...

    java的Apache组件学习Demo

    本篇文章将深入探讨标题为"java的Apache组件学习Demo"中的几个关键组件:IO、Lang、Bean、Configuration、Codec、Collection以及HttpClient。 首先,Apache Commons IO是一个针对Java I/O操作的实用工具库,它提供...

    httpClient4.3 Jar包 demo

    HttpClient是Apache软件基金会的一个开源项目,它提供了Java语言下的HTTP客户端API,使开发者能够方便地进行HTTP通信。HttpClient 4.3是该库的一个版本,它包含了一系列改进和新特性,旨在提供更高效、更灵活的HTTP...

    httpclient发送get请求和post请求demo

    在Java编程中,Apache HttpClient库是一个非常常用的工具,它提供了对HTTP协议的强大支持,包括GET和POST...在提供的压缩包文件中,`test-demo`和`httpclient-demo`可能包含了这些示例的源码,供你进一步学习和参考。

    HttpClientDemo

    HttpClient是Apache基金会开发的一个Java库,用于执行HTTP和HTTPS请求。在Java中,HttpClient是一个强大的工具,它提供了丰富的功能来处理网络通信,特别是在发送HTTP请求和接收响应时。本示例将详细介绍如何使用...

    httpcore-httpclient-demo.zip

    HTTPCore和HttpClient是Apache软件基金会开发的两个重要组件,它们在Java编程中广泛用于构建网络应用,特别是处理HTTP协议的请求和响应。HTTPCore是低级别、轻量级的库,提供基础的HTTP连接管理,而HttpClient则是在...

    Java通过HttpClient调用百度地图Demo

    在这个特定的示例中,我们关注的是如何使用HttpClient来调用百度地图的API,创建一个简单的Demo。下面将详细介绍这个过程以及相关的技术知识点。 首先,你需要在项目中引入Apache HttpClient库。这可以通过Maven或...

    HttpClient post提交文件加传参的demo

    这个"HttpClient post提交文件加传参的demo"是针对初学者的一个实例,帮助理解如何使用HttpClient来实现这样的功能。在此,我们将详细探讨HttpClient的使用以及如何通过它进行文件上传和参数传递。 首先,你需要...

    httpclient发送post请求

    而"httpclient-demo"项目则是一个客户端应用,它的任务是利用Apache HttpClient库来构建和发送POST请求到"post-demo"项目提供的接口。HttpClient库提供了丰富的API,允许开发者灵活地设置请求头、主体内容、超时等...

    HttpClient接口调用工具类(附带demo)

    HttpClient是Apache基金会开发的一个HTTP客户端库,用于在Java应用程序中执行HTTP请求。它提供了一种高效、灵活且可扩展的方式来发起HTTP请求,并处理响应。在这个工具类中,我们看到包括了Post、Get、Put和Delete四...

Global site tag (gtag.js) - Google Analytics