模拟http或https请求,实现ssl下的bugzilla登录、新增BUG,保持会话以及处理token
1.增加相应httpclient 需要的jar包到工程,如果是maven工程请在pom.xml增加以下配置即可:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.4.1</version>
</dependency>
2. 新建测试类(完全模拟http请求,实现ssl下的bugzilla登录、新增BUG,保持会话以及处理token),注意https://bugzilla.tools.vipshop.com/bugzilla/这部分的URL要更换成你自己的域名地址,还有bugzilla的账户和密码
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
//import java.rmi.registry.Registry;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.net.ssl.SSLContext;
import org.apache.http.HeaderIterator;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.cookie.CookieSpecProvider;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.impl.cookie.BestMatchSpecFactory;
import org.apache.http.impl.cookie.BrowserCompatSpecFactory;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
/**
*
* @author sea.zeng
*
*/
public class BugzillaHttpsUtil
{
// 创建CookieStore实例
static CookieStore cookieStore = null;
static HttpClientContext context = null;
String loginUrl = "https://bugzilla.tools.vipshop.com/bugzilla/index.cgi";
String toCreateBugUrl = "https://bugzilla.tools.vipshop.com/bugzilla/enter_bug.cgi";
String createBugUrl = "https://bugzilla.tools.vipshop.com/bugzilla/post_bug.cgi";
static String token = "";
static CloseableHttpClient client = null;
public static void main(String[] args)
throws Exception
{
BugzillaHttpsUtil bugzillaHttpsUtil = new BugzillaHttpsUtil();
// sea20150528 先解决服务器不信任我们自己创建的证书,所以在代码中必须要忽略证书信任
client = bugzillaHttpsUtil.createSSLClientDefault();
bugzillaHttpsUtil.login(client);
bugzillaHttpsUtil.toCreateBug(client);
bugzillaHttpsUtil.createBug(client);
// 关闭流并释放资源
client.close();
}
@SuppressWarnings({"rawtypes", "unchecked"})
private void login(CloseableHttpClient client)
throws Exception
{
HttpPost httpPost = new HttpPost(loginUrl);
Map parameterMap = new HashMap();
parameterMap.put("Bugzilla_login", "你的bugzilla账号");
parameterMap.put("Bugzilla_password", "你的bugzilla密码");
UrlEncodedFormEntity postEntity = new UrlEncodedFormEntity(getParam(parameterMap), "UTF-8");
httpPost.setEntity(postEntity);
// System.out.println("request line:" + httpPost.getRequestLine());
// 执行post请求
HttpResponse httpResponse = client.execute(httpPost);
// printResponse(httpResponse);
// cookie store
setCookieStore(httpResponse);
// context
setContext();
// 这里可以不初始化token,因为没有post数据
// initToken(httpResponse);
}
@SuppressWarnings({"rawtypes", "unchecked"})
private void toCreateBug(CloseableHttpClient client)
throws Exception
{
HttpPost httpPost = new HttpPost(toCreateBugUrl);
Map parameterMap = new HashMap();
parameterMap.put("product", "移动:App-特卖会(新)");
parameterMap.put("component", "支付");
parameterMap.put("version", "5.1");
UrlEncodedFormEntity postEntity = new UrlEncodedFormEntity(getParam(parameterMap), "UTF-8");
httpPost.setEntity(postEntity);
// System.out.println("request line:" + httpPost.getRequestLine());
// 执行post请求
HttpResponse httpResponse = client.execute(httpPost);
// cookie store
// setCookieStore(httpResponse);
// context
setContext();
initToken(httpResponse);
}
@SuppressWarnings({"rawtypes", "unchecked"})
private void createBug(CloseableHttpClient client)
throws Exception
{
HttpPost httpPost = new HttpPost(createBugUrl);
Map parameterMap = new HashMap();
parameterMap.put("product", "产品名");
parameterMap.put("component", "支付");
parameterMap.put("version", "5.1");
parameterMap.put("short_desc", "测试bug3");
parameterMap.put("op_sys", "Windows");
parameterMap.put("bug_severity", "low");
parameterMap.put("rep_platform", "Mobile");
parameterMap.put("op_sys", "Android");
parameterMap.put("priority", "Medium");
parameterMap.put("bug_status", "NEW");
parameterMap.put("cf_environment", "性能测试");
parameterMap.put("cf_impactenv", "性能测试");
// 各个页面的token不一样,尤其是登陆后与提交BUG的token差异较大
parameterMap.put("token", token);
UrlEncodedFormEntity postEntity = new UrlEncodedFormEntity(getParam(parameterMap), "UTF-8");
httpPost.setEntity(postEntity);
// 执行post请求
// HttpResponse httpResponse =
client.execute(httpPost);
// setCookieStore(httpResponse);
setContext();
}
/**
* sea 分析输入流获取token,标本<input type="hidden" name="token" value="1432806799-dc8423dfbb4c68fb1305d5aa439f95a2">
*/
private String initToken(HttpResponse httpResponse)
throws Exception
{
// 获取响应消息实体 content 部分
HttpEntity htmlEntity = httpResponse.getEntity();
String htmlString = EntityUtils.toString(htmlEntity, "UTF-8");
String html = htmlString.replace("\r\n", "");
String prefix = "token\" value=\"";
String suffix = "\">";
// 找出token字符串开始位置(不包括)
int beginIndex = html.indexOf(prefix);
// 找出token字符串结束位置(不包括)
int endIndex = html.indexOf(suffix, beginIndex);
token = html.substring(beginIndex + 14, endIndex);
System.out.println("html=================================================================" + html);
System.out.println("beginIndex=================================================================" + beginIndex);
System.out.println("endIndex=================================================================" + endIndex);
System.out.println("token=================================================================" + token);
return token;
}
public static void printResponse(HttpResponse httpResponse)
throws ParseException, IOException
{
// 获取响应消息实体
HttpEntity entity = httpResponse.getEntity();
// 响应状态
System.out.println("status:" + httpResponse.getStatusLine());
System.out.println("headers:");
HeaderIterator iterator = httpResponse.headerIterator();
while (iterator.hasNext())
{
System.out.println("\t" + iterator.next());
}
// 判断响应实体是否为空
if (entity != null)
{
String responseString = EntityUtils.toString(entity);
System.out.println("response length:" + responseString.length());
System.out.println("response content:" + responseString.replace("\r\n", ""));
}
}
public static void setContext()
{
System.out.println("----setContext");
context = HttpClientContext.create();
Registry<CookieSpecProvider> registry =
RegistryBuilder.<CookieSpecProvider> create()
.register(CookieSpecs.BEST_MATCH, new BestMatchSpecFactory())
.register(CookieSpecs.BROWSER_COMPATIBILITY, new BrowserCompatSpecFactory())
.build();
context.setCookieSpecRegistry(registry);
context.setCookieStore(cookieStore);
}
public static void setCookieStore(HttpResponse httpResponse)
{
System.out.println("----setCookieStore");
cookieStore = new BasicCookieStore();
// JSESSIONID
String setCookie = httpResponse.getFirstHeader("Set-Cookie").getValue();
String JSESSIONID = setCookie.substring("JSESSIONID=".length(), setCookie.indexOf(";"));
System.out.println("JSESSIONID:" + JSESSIONID);
// 新建一个Cookie
BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", JSESSIONID);
cookie.setVersion(0);
cookie.setDomain("bugzilla.tools.vipshop.com");
cookie.setPath("/");
cookieStore.addCookie(cookie);
}
@SuppressWarnings("rawtypes")
public static List<NameValuePair> getParam(Map parameterMap)
{
List<NameValuePair> param = new ArrayList<NameValuePair>();
Iterator it = parameterMap.entrySet().iterator();
while (it.hasNext())
{
Entry parmEntry = (Entry)it.next();
param.add(new BasicNameValuePair((String)parmEntry.getKey(), (String)parmEntry.getValue()));
}
return param;
}
public CloseableHttpClient createSSLClientDefault()
{
try
{
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy()
{
// 信任所有
public boolean isTrusted(X509Certificate[] chain, String authType)
throws CertificateException
{
return true;
}
}).build();
SSLConnectionSocketFactory sslsf =
new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
return HttpClients.custom().setSSLSocketFactory(sslsf).setDefaultCookieStore(cookieStore).build();
}
catch (KeyManagementException e)
{
e.printStackTrace();
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
}
catch (KeyStoreException e)
{
e.printStackTrace();
}
return HttpClients.createDefault();
}
}
本着资源共享的原则,欢迎各位朋友在此基础上完善,并进一步分享,让我们的实现更加优雅。如果有任何疑问和需要进一步交流可以加我QQ 1922003019或者直接发送QQ邮件给我沟通
sea 2015 中国:广州:VIP
模拟http或https请求,实现ssl下的bugzilla登录、新增BUG,保持会话以及处理token的更多相关文章
- Requests对HTTPS请求验证SSL证书
SSL证书通过在客户端浏览器和Web服务器之间建立一条SSL安全通道(Secure socket layer(SSL)安全协议是由Netscape Communication公司设计开发.该安全协议主 ...
- requests发送HTTPS请求(处理SSL证书验证)
1.SSL是什么,为什么发送HTTPS请求时需要证书验证? 1.1 SSL:安全套接字层.是为了解决HTTP协议是明文,避免传输的数据被窃取,篡改,劫持等. 1.2 TSL:Transport Lay ...
- python接口自动化(十二)--https请求(SSL)(详解)
简介 本来最新的requests库V2.13.0是支持https请求的,但是一般写脚本时候,我们会用抓包工具fiddler,这时候会 报:requests.exceptions.SSLError: [ ...
- iOS开发 支持https请求以及ssl证书配置(转)
原文地址:http://blog.5ibc.net/p/100221.html 众所周知,苹果有言,从2017年开始,将屏蔽http的资源,强推https 楼主正好近日将http转为https,给还没 ...
- .net 模拟登陆 post https 请求跳转页面
AllowAutoRedirect property is true, the Referer property is set automatically when the request is re ...
- C#模拟Http与Https请求框架实例
using System.Text; using System.Net; using System.IO; using System.Text.RegularExpressions; using Sy ...
- git openssl 模块生成 https 请求的 ssl 测试证书
1,请先确定安装了相关模块 1.1,git --version 1.2,openssl version -a 2,创建一个目录, cd 到该目录下 3,生成私钥 key 文件 openssl g ...
- charles录制https请求
之前一直用windows系统,抓包什么的都是用的fiddler或者wireshark,操作比较简单,扩展性也比较强,现在因为工作原因换了mac,在网上一直没有找到fiddler的mac版本,就只能切换 ...
- 使用HttpClient发送HTTPS请求以及配置Tomcat支持SSL
这里使用的是HttpComponents-Client-4.1.2 package com.jadyer.util; import java.io.File; import java.io.FileI ...
随机推荐
- 从别人那淘的知识 深入剖析Java中的装箱和拆箱
(转载的海子的博文 海子:http://www.cnblogs.com/dolphin0520/) 深入剖析Java中的装箱和拆箱 自动装箱和拆箱问题是Java中一个老生常谈的问题了,今天我们就来 ...
- 滚动条--nicescroll插件(兼容各种浏览器,低至IE5)
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8&quo ...
- hdu 3948 Portal (kusral+离线)
Portal Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Subm ...
- Java 集合系列 14 hashCode
java 集合系列目录: Java 集合系列 01 总体框架 Java 集合系列 02 Collection架构 Java 集合系列 03 ArrayList详细介绍(源码解析)和使用示例 Java ...
- easyui datagrid的列编辑
[第十五篇]easyui datagrid的列编辑,同时插入两张表的数据进去 看图说话. 需求:插入两张表,上面的表单是第一张表的内容,下面的两个表格是第二张详情表的内容,跟第一张表的id关联 第 ...
- python——使用readline库实现tab自动补全
Input History readline tracks the input history automatically. There are two different sets of funct ...
- JSP 服务器响应
Response响应对象主要将JSP容器处理后的结果传回到客户端.可以通过response变量设置HTTP的状态和向客户端发送数据,如Cookie.HTTP文件头信息等. 一个典型的响应看起来就像下面 ...
- 执行MAVEN更新包
我们一般使用 mvn eclipse:eclipse 执行对maven库的引用,这样会修改项目下的classpath文件. 我们修改直接在eclipse 使用maven库作为项目的引用. 步骤如下: ...
- POJ 3206 最小生成树
DESCRIPTION:T_T 在下是读不懂题意的.但是捏.现在知道是求把所有的点(是字母的点)连起来的最小的权值.即最小生成树.因为求最小生成树是不计较源点是哪个的.所以可以把A和S看成一样的.首先 ...
- Entity Framework系列
这个系列主要记录学习EF的过程和碰到的问题以及解决问题的方法. EF中的那些批量操作 EF的Model First