`

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资料很多,但很多都是有代码无jar,也是找了一下午,特供资料,与君互勉。

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

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

    萤石平台接口用例demo(带完整的jar包)

    import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.RequestEntity; import org.apache.commons....

    java8源码-small-frame-demo:小框架-demo

    apache-poi-demo poi-demo json-path-demo xml-jaxb-test xml-xstream-test xml-fasterxml-test byte-code-op asm-demo byte-buddy-demo object-op-frame objenesis-test jol-demo 计算 java 对象大小 java-op-db ...

    HtmlEmail发送邮件+HttpClient下载功能

    1.支持发送邮件和远端文件下载两个功能Demo,环境MyEclipse 6.0.1+jdk1.6 2.import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import org.apache....

    elasticsearch学习demo

    &lt;httpclient-version&gt;4.5.1&lt;/httpclient-version&gt; &lt;zkclient-version&gt;0.1 &lt;sl4j.version&gt;1.7.25 &lt;groupId&gt;com.alibaba&lt;/groupId&gt; &lt;artifactId&gt;fastjson ${fastjson-version} &lt;groupId&gt;org.elastic...

    Volley-demo-master

    Android 提供了两个 HTTP 客户端AndroidHttpClient (扩展自 apache HTTPClient)和HttpUrlConnection来发出 HTTP 请求。 两者都有自己的优点和缺点。 在开发应用程序时,我们编写处理所有 HTTP 请求的 HTTP 连接类...

    基于Tomcat搭建SSL双向认证示例【100012422】

    Tomcat搭建SSL双向认证Demo、Java原生类库SSLSocket编程、Apache的Httpclient库模拟请求

    SeimiCrawler(Java 爬虫框架) v1.3.0.zip

    默认下载器改为Apache Httpclient,备用为下载器OkHttp3实现 优化部分代码 demo日志默认全部输出至控制台 SeimiCrawler(Java 爬虫框架)简介 SeimiCrawler是一个敏捷的,独立部署的,支持分布式的Java爬虫框架,...

    Android loopj 文件上传

    代码是基于loopj (Asynchronous Http Client for Android) 的文件上传Demo,loopj 是基于 Apache's HttpClient 的异步http客户端。

    wx_withdraw_demo:微信企业付款到银行卡

    我们需要在http中加载wx颁发的证书在项目中我使用的是httpclient加载证书package com.chen.utils.wxHttpclient;import org.apache.http.conn.ConnectionKeepAliveStrategy;import org.apache....

    JAVA版 微信支付 获取预支付id 14年11月18日最新版本

    截止到 当前时间 2014年11月18日 ,我在网上找到很多个关于获取微信获取预支付的问题,都不能解决我的问题,首先是微信支付,版本分歧很多,并且给的DEMO没有java版本的,文档写得很烂,经过了3天的努力,发现了很多...

    Java发送httpPost请求–传消息头,消息体的方法

    HttpClient工具类拓展sendPost方法 最近开发中需要调外部厂商提供的API接口,接口文档中定义需要传递一个消息头+消息体。参考httpClient工具类中没有相关方法,所以自己写出来,并和大家分享。 代码来一波 import ...

    Android程序报错程序包org.apache.http不存在问题的解决方法

    Android 6.0(api 23)已经不支持HttpClient了,在build.gradle中 加入 useLibrary ‘org.apache.http.legacy’就可以了,如图: 您可能感兴趣的文章:Eclipse运行android项目报错Unable to build: the file dx....

    271个java需要用的jar包

    struts2-osgi-demo-bundle-2.3.15.3.jar struts2-osgi-plugin-2.3.15.3.jar struts2-oval-plugin-2.3.15.3.jar struts2-pell-multipart-plugin-2.3.15.3.jar struts2-plexus-plugin-2.3.15.3.jar struts2-portlet-...

    Android静默安装常用工具类

    更详细的设置可以直接使用HttpURLConnection或apache的HttpClient。 源码可见HttpUtils.java,更多方法及更详细参数介绍可见HttpUtils Api Guide。 2、DownloadManagerPro Android系统下载管理DownloadManager增强...

Global site tag (gtag.js) - Google Analytics