模擬http或https請求,實現ssl下的bugzilla登入、新增BUG,保持會話以及處理token

weixin_30639719發表於2020-04-05


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

轉載於:https://www.cnblogs.com/sea520/p/4561815.html

相關文章