当前位置:首页 > 开发 > 互联网 > 正文

Apache HttpClient Demo

发表于: 2013-02-26   作者:antlove   来源:转载   浏览次数:
摘要: 一 建立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/n
一 建立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("--------------------");
	}
}

Apache HttpClient Demo

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

编辑推荐
======现在介绍一个新的方式来访问Web站点,那就是HttpClient======   HttpClient是Apache开源组
HttpClient简介 HTTP 协议可能是现在 Internet 上使用得最多、最重要的协议了,越来越多的 Java 应
什么是Mina,用Mina可以干什么? 官网:http://mina.apache.org/ 看不懂英文?那就随便百度,大概了
工程目录如下图所示: build.xml <?xml version="1.0" encoding="UTF-8"?> <project defau
由于毕业设计要涉及到互联网的的通讯,所以很快就接触到于远程服务器交互。起初想是和服务器的数据
HttpClient4.0.3 GA 版发布,此版本主要是为了修复 HttpClient 4.0.2 中多个本地主机名称导致的 SSL
下面的部分内容来源于《Unlocking Android》一书: 要了解HTTPClient,我们先看一下如何使用核心类
0.Maven Dependency <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://ww
作者:chszs,转载需注明。博客主页:http://blog.csdn.net/chszs 很多网站都使用了URL重定向技术,
HttpClient使用步骤 1、生成代表客户端的HttpClient对象 2、生成代表请求的对象 3、发送请求,获得
版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号