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