模拟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 ...
随机推荐
- DI 之 3.3 更多DI的知识(陆)
3.3.1 延迟初始化Bean 延迟初始化也叫做惰性初始化,指不提前初始化Bean,而是只有在真正使用时才创建及初始化Bean. 配置方式很简单只需在<bean>标签上指定 " ...
- [backbone]backbone.js
学习文档: 开始学习 Backbone http://www.ibm.com/developerworks/cn/web/wa-backbonejs/
- 简单的百度贴吧爬虫实现(urllib)
环境:ubuntu 16.04 LTS (X86-64),pycharm python版本 :3.5.1+ #生成的文件默认会保存到代码所在根目录 1 import urllib.request, ...
- 关于byte[]字节传输的大端和小端小议
当前的存储器,多以byte为访问的最小单元,当一个逻辑上的地址必须分割为物理上的若干单元时就存在了先放谁后放谁的问题,于是端(endian)的问题应运而生了,对于不同的存储方法,就有大端(big-en ...
- ABAP版连连看
网上看到的,感觉不错,借来装13... *&---------------------------------------------------------------------* *&a ...
- CentOS命令登录MySQL时,报错ERROR 1045 (28000):
CentOS命令登录MySQL时,报错ERROR 1045 (28000): Access denied for user root@localhost (using password: NO)错误解 ...
- centos chkconfig 服务设置
chkconfig命令主要用来更新(启动或停止)和查询系统服务的运行级信息.谨记chkconfig不是立即自动禁止或激活一个服务,它只是简单的改变了符号连接. 使用语法:chkconfig [--ad ...
- 如何对ConnectionString进行加密解码?
这个就不说了就是一个类 public static class EncryptionConfig { /* 加密配置节点 * Response.Write(EncryptionConfig.Encry ...
- 关于Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)的问题
找不到mysql socket的问题,我最近碰到了好多次重装系统以前,我的mysql,apache,php都是自己编译安装的,当时并没有碰到这些问题,重装系统以后,我的mysql是通过yum安装的,a ...
- 3D开发的基本知识
为了实现3D图形,程序员需要定义两个方面的数据: 1.3D图形的每个顶点(Vertex)的位置,每个顶点的位置都需要X.Y.Z三个左标值. 2.3D图形每个面由哪些顶点组成. Android的3D坐标 ...