模拟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 ...
随机推荐
- .net 时间戳和日期互转 【转】http://www.cnblogs.com/zhuiyi/p/5307540.html
.net 时间戳和日期互转 1.时间戳转日期public static DateTime IntToDateTime(int timestamp){ return TimeZone.CurrentTi ...
- hdu----(5055)Bob and math problem(贪心)
Bob and math problem Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Oth ...
- Trapping Rain Water [LeetCode]
Problem Description: http://oj.leetcode.com/problems/trapping-rain-water/ Basic idea: Get the index ...
- 221. Maximal Square -- 矩阵中1组成的最大正方形
Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and re ...
- iOS的常见文件及程序的启动原理
一. iOS中常见文件 (一). Xcode6之前 创建项目,默认可以看见一个存放框架的文件夹 info文件以工程文件名开头,如:第一个项目-Info.plist 项目中默认有一个PCH文件 (二). ...
- jdbc URL中的各个参数详解
常用的有两个,一个是gjt(Giant JavaTree)组织提供的mysql驱动,其JDBC Driver名称(Java类名)为:org.gjt.mm.mysql.Driver 详情请参见网站:ht ...
- OUT函数及其熟练使用,split的用法
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...
- C#基础学习文章导航
第一部分:入个门 C#入门篇-1:HelloWorld的类 C#入门篇-2:什么是变量 C#入门篇-3:数据类型及转换 C#入门篇-4:使用运算符 第二部分:流程控制语句 C#入门篇5-1:流程控制语 ...
- ubuntu14.10服务器版安装xampp,配置域名端口访问
1.从xampp下载下了xampp-linux-1.7.3a.tar这个包,然后ftp到我的linux虚拟机中, 2.复制到opt下,(可以直接解压的)到opt下面,tar xvfz xampp-li ...
- [Js]评分星星
效果: 鼠标移到星星上,这颗星星及之前的全亮,提示文字出现,根绝星星数量显示不同文字,移出灭掉,文字消失 思路: 1.定义一个数组,来存放不同的文字 2.存放星星的索引值(要在i定义赋值后,即在for ...