package com.zhonghong.tsp.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
public class HttpClientUtil {
private static final Log log = LogFactory.getLog(HttpClientUtil.class);
/**
* HttpClient 模拟spring单点登录后,发送请求URL
*
* @param postUrl
* 请求url
* @param casLoginUrl
* 单点登录url
* @param username
* 登录用户名
* @param password
* 登录密码
* @return
* @throws ServletException
*/
public static String springSecurityRequest(String postUrl,
String casLoginUrl, String username, String password)
throws Exception {
String result = "";
DefaultHttpClient httpclient = HttpConnectionManager.getHttpClient();
String loginIt = doCasLoginRequest(httpclient, casLoginUrl);
// 登录 CAS 身份认证系统
HttpPost httpost = new HttpPost(casLoginUrl);
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("username", username));
nvps.add(new BasicNameValuePair("password", password));
nvps.add(new BasicNameValuePair("lt", loginIt));
nvps.add(new BasicNameValuePair("_eventId", "submit"));
nvps.add(new BasicNameValuePair("submit", "登录"));
httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
HttpResponse response = httpclient.execute(httpost);
HttpEntity entity = response.getEntity();
if (entity != null) {
entity.consumeContent();
writeCookie(httpclient, username);
result = doGetRequest(httpclient, postUrl);
}
httpclient.getConnectionManager().shutdown();
return result;
}
private static String doCasLoginRequest(HttpClient httpclient, String url)
throws IOException {
String result = "";
HttpGet httpget = new HttpGet(url);
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
BufferedReader rd = new BufferedReader(new InputStreamReader(
entity.getContent(), HTTP.UTF_8));
String tempLine = rd.readLine();
String s = "<input type=\"hidden\" name=\"lt\" value=\"";
while (tempLine != null) {
int index = tempLine.indexOf(s);
if (index != -1) {
String s1 = tempLine.substring(index + s.length());
int index1 = s1.indexOf("\"");
if (index1 != -1)
result = s1.substring(0, index1);
}
tempLine = rd.readLine();
}
if (entity != null) {
entity.consumeContent();
}
return result;
}
private static void writeCookie(DefaultHttpClient httpclient,
String username) throws Exception {
List<Cookie> myCookie = httpclient.getCookieStore().getCookies();
if (myCookie == null || myCookie.size() == 0) {
BasicClientCookie cookie = new BasicClientCookie("ssusername",
username);
// 设置当前容器中的所有页面都可以访问到该Cookie
cookie.setPath("/");
// 设置cookie的有效时间为2小时
CookieStore cookies = httpclient.getCookieStore();
cookies.addCookie(cookie);
httpclient.setCookieStore(cookies);
} else {
boolean flag = false;
for (int i = 0; i < myCookie.size(); i++) {
BasicClientCookie cookie = (BasicClientCookie) myCookie.get(i);
String cookiename = cookie.getName();
if ("ssusername".equals(cookiename)) {
cookie.setValue(username);
flag = true;
break;
}
}
if (!flag) {
BasicClientCookie cookie = new BasicClientCookie("ssusername",
username);
CookieStore cookies = httpclient.getCookieStore();
cookies.addCookie(cookie);
httpclient.setCookieStore(cookies);
}
}
}
private static String doGetRequest(HttpClient httpclient, String url)
throws IOException {
HttpGet httpget = new HttpGet(url);
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
String result = null;
if (entity != null) {
result = toString(entity.getContent(), HTTP.UTF_8);
entity.consumeContent();
}
return result;
}
public static String doGetRequest(String url) throws IOException {
HttpClient httpclient = HttpConnectionManager.getHttpClient();
return doGetRequest(httpclient, url);
}
@SuppressWarnings("rawtypes")
public static String doPostRequest(String url, Map param) {
HttpPost httpost = new HttpPost(url);
List<NameValuePair> nvps = setNameValuePair(param);
try {
HttpClient httpclient = HttpConnectionManager.getHttpClient();
httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
httpost.setHeader("Connection", "close");
HttpResponse response = httpclient.execute(httpost);
HttpEntity entity = response.getEntity();
String result = null;
if (entity != null) {
result = toString(entity.getContent(), HTTP.UTF_8);
entity.consumeContent();
}
return result;
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return "";
}
@SuppressWarnings("rawtypes")
private static List<NameValuePair> setNameValuePair(Map param) {
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
if (param == null){
return nvps;
}
Iterator entries = param.entrySet().iterator();
Map.Entry entry;
while (entries.hasNext()) {
entry = (Map.Entry) entries.next();
String name = (String) entry.getKey();
Object valueObj = entry.getValue();
if (null == valueObj) {
nvps.add(new BasicNameValuePair(name, ""));
} else if (valueObj instanceof String[]) {
String[] values = (String[]) valueObj;
for (int i = 0; i < values.length; i++) {
nvps.add(new BasicNameValuePair(name, values[i]));
}
} else {
nvps.add(new BasicNameValuePair(name, valueObj.toString()));
}
}
return nvps;
}
private static String toString(InputStream in, String encode) {
StringBuffer result = new StringBuffer();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(in,
encode));
String tempLine = rd.readLine();
while (tempLine != null) {
result.append(tempLine);
tempLine = rd.readLine();
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return result.toString();
}
public static void sendPost(String url, HttpServletRequest request,
HttpServletResponse response) throws Exception {
String info = doPostRequest(url, request.getParameterMap());
renderHtml(response, info);
}
public static void sendPostJson(String url, HttpServletRequest request,
HttpServletResponse response) throws Exception {
String info = doPostRequest(url, request.getParameterMap());
renderJson(response, info);
}
/**
* 发送文本。使用UTF-8编码。
*
* @param response
* HttpServletResponse
* @param text
* 发送的字符串
*/
public static void renderHtml(HttpServletResponse response, String text) {
render(response, "text/html;charset=UTF-8", text);
}
/**
* 发送文本。使用UTF-8编码。
*
* @param response
* HttpServletResponse
* @param text
* 发送的字符串
*/
public static void renderText(HttpServletResponse response, String text) {
render(response, "text/plain;charset=UTF-8", text);
}
/**
* 发送json。使用UTF-8编码。
*
* @param response
* HttpServletResponse
* @param text
* 发送的字符串
*/
public static void renderJson(HttpServletResponse response, String text) {
render(response, "application/json;charset=UTF-8", text);
}
/**
* 发送xml。使用UTF-8编码。
*
* @param response
* HttpServletResponse
* @param text
* 发送的字符串
*/
public static void renderXml(HttpServletResponse response, String text) {
render(response, "text/xml;charset=UTF-8", text);
}
/**
* 发送内容。使用UTF-8编码。
*
* @param response
* @param contentType
* @param text
*/
public static void render(HttpServletResponse response, String contentType,
String text) {
response.setContentType(contentType);
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
if(text != null){
try {
response.getWriter().write(text);
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
}
}
- 浏览: 37628 次
- 性别:
- 来自: 武汉
文章分类
最新评论
-
linruibo001:
地方
flex4文件上传+视频播放(简单案例) -
rinniclyks:
谢谢分享,这个对我来说很用,下午我试试看
网页上Applet用javacomm20读取客户端串口 -
mlc19860417:
下来看看
spring线程发送邮件 -
jeff712:
东西不错,
Struts2中POI在内存中生成Excel文件并下载 -
Samter:
好东西,谢谢了!
Struts2中POI在内存中生成Excel文件并下载
发表评论
-
RSA
2014-07-29 15:35 509package com.client.rsa;import ... -
消息拆包
2014-05-13 18:37 6827E.....7E public static List& ... -
网页上Applet用javacomm20读取客户端串口
2012-09-20 15:22 907public class SerialHandleBean ... -
消息构造器
2012-09-20 15:03 584public class MessageArrayBuilde ... -
TypeChangeUtil
2012-09-20 14:59 861public class TypeChangeUtil { ... -
log4j.properties 使用
2012-09-20 14:26 573log4j.properties 使用 一. ... -
javaee 限制登录
2011-11-26 11:19 840public class LoginSessionListen ... -
java(加密与解密)
2011-02-22 17:05 824java(加密与解密) PBE——Password-base ... -
给图片加水印
2010-09-20 10:34 728// 将 s 进行 BASE64 编码 public stat ... -
lucene3.0
2010-09-18 14:01 653lucene3.0 -
JAVA葵花宝典
2009-09-15 16:55 1208JAVA葵花宝典
相关推荐
在"java httpclient 模拟登录"这个场景下,我们通常会用到HttpClient来模拟用户登录网站的过程,获取登录后的session信息,以便后续能够访问登录后才能看到的页面内容。以下将详细介绍如何使用Java HttpClient进行...
在Java项目中,使用HttpClient可以实现与Web服务器的高效通信。下面将详细介绍这12个jar包的作用及其在HttpClient中的功能: 1. `commons-beanutils-1.8.0.jar`: Apache Commons BeanUtils库提供了对Java Beans属性...
### Java HttpClient 发送GET请求和带有表单参数的POST请求详解 #### 一、概述 在Java编程中,处理HTTP请求是一项常见的需求,特别是在与Web服务进行交互时。Apache HttpClient库提供了一种强大的方法来执行HTTP...
httpclient常用封装工具 doGet(String url, Map, String> param) doPost(String url, Map, String> param) doPostJson(String url, String json)
Java HttpClient 是 Apache HttpClient 库的一部分,它提供了丰富的功能,包括连接管理、重试策略、超时设置等,使得在Java中进行网络通信变得更加便捷。HttpClient库不仅支持基本的HTTP协议,还支持HTTPS以及一些...
Java HttpClient 是一个强大的库,常用于执行HTTP请求,模拟浏览器行为。在这个小例子中,我们将专注于客户端代码,因为标题提示没有包含服务器端的部分。HttpClient 可以用来进行GET、POST和其他HTTP方法的操作,...
java httpclient 所需要的包,都是最新版的 commons-logging-1.1.3.jar commons-codec-1.6.jar commons-httpclient-3.1.jar
java httpClient 工具类 java httpClient 工具类 java httpClient 工具类 java httpClient 工具类 java httpClient 工具类 java httpClient 工具类 java httpClient 工具类 java httpClient 工具类 java httpClient ...
Java HttpClient 是一个强大的网络通信库,它允许Java开发者在应用程序中实现HTTP和HTTPS协议的请求。这个工具类在电商开发中特别有用,因为通常需要与各种Web服务进行交互,如商品信息抓取、订单同步、用户反馈处理...
本实例将深入探讨如何在Java中使用HttpClient进行网络通信。 首先,你需要在项目中引入HttpClient的相关依赖。如果是Maven项目,可以在pom.xml文件中添加以下依赖: ```xml <groupId>org.apache.httpcomponents ...
1. JAVA HttpClient库的使用 2. HTTPS协议的使用 3. SSL/TLS证书的使用 4. X509TrustManager的使用 5. DefaultHttpClient类的使用 6. HttpClient的自定义 7. POST请求的发送 8. 请求头和请求体的指定 9. HTTPS服务器...
这里提到的压缩包包含了使用Java HttpClient所需的多个关键组件。 1. `apache-mime4j-0.6.jar`: 这个库提供了对MIME消息解析的支持,MIME是一种标准,用于在邮件和网络消息中传输多媒体内容。在HTTP客户端中,它...
标题中的“简单的HTTP功能监控”指的是使用Java编程语言,通过`httpclient-3.1`库来实现对HTTP服务的功能性监控。`httpclient-3.1`是Apache HttpClient的一个旧版本,它提供了丰富的功能来执行HTTP请求并处理响应,...
在Java编程中,HttpClient常被用于网页爬虫的开发,因为它提供了对网络通信的低级别控制,使我们能够灵活地处理各种网络任务。 在使用Java HttpClient进行网页抓取时,首先需要理解以下关键概念和组件: 1. **...
该工具类使用httpclient进行http or https请求,包括requestbody格式和form表单格式,另外含文件服务器中转上传方法,几乎支持所有常用接口调用,内含详细注释和说明文件,含jar包,及maven方式引用,拿过去直接用吧
【Java HttpClient库在12306购票应用中的实践】 1. Java HttpClient介绍 Java HttpClient是Apache HttpClient项目的一部分,是一个强大的HTTP客户端API,允许开发者在Java应用程序中执行HTTP请求。它支持各种HTTP...
在本文中,我们将深入探讨Java HttpClient工具的使用方法、核心概念以及它如何帮助开发人员更高效地进行网络通信。 1. **HttpClient的安装与引入** 要使用HttpClient,首先需要将其添加到项目的依赖库中。对于...
综上所述,通过Java的HttpClient库,可以在Eclipse环境中编写程序,实现从指定URL下载文件到本地的功能。通过理解HttpClient的工作原理和提供的API,开发者可以构建出稳定、高效的文件下载解决方案。
下面我们将详细探讨如何在Java中使用HttpClient来实现这一目标。 首先,我们需要导入必要的Apache HttpClient库,通常包含以下依赖: ```xml <groupId>org.apache.httpcomponents <artifactId>httpclient ...