Simulate HTTP or HTTPS requests, implement Bugzilla logins under SSL, add bugs, maintain sessions, and process tokens

Source: Internet
Author: User
Tags setcookie


1. Add the jar package to the project required by the corresponding httpclient, if it is Maven project, please add the following configuration in Pom.xml:

<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.4.1</version>
</dependency>


2. Create a new test class (fully simulate HTTP requests, implement Bugzilla logins under SSL, add bugs, maintain sessions, and handle tokens), note https://bugzilla.tools.vipshop.com/bugzilla/ This part of the URL to be replaced with your own domain address, as well as Bugzilla's account and password

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
{
Creating an Cookiestore instance
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 the server does not trust the certificate we have created, so the certificate trust must be ignored in the code
Client = Bugzillahttpsutil.createsslclientdefault ();

Bugzillahttpsutil.login (client);

Bugzillahttpsutil.tocreatebug (client);

Bugzillahttpsutil.createbug (client);

Close a stream and release resources
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", "Your Bugzilla account");
Parametermap.put ("Bugzilla_password", "Your Bugzilla password");
Urlencodedformentity postentity = new Urlencodedformentity (GetParam (Parametermap), "UTF-8");
Httppost.setentity (postentity);
SYSTEM.OUT.PRINTLN ("Request line:" + httppost.getrequestline ());

Perform a POST request
HttpResponse HttpResponse = Client.execute (HttpPost);

Printresponse (HttpResponse);

Cookie Store
Setcookiestore (HttpResponse);

Context
SetContext ();

Token cannot be initialized here, because there is no post data
Inittoken (HttpResponse);
}

@SuppressWarnings ({"Rawtypes", "Unchecked"})
private void Tocreatebug (Closeablehttpclient client)
Throws Exception
{
HttpPost HttpPost = new HttpPost (Tocreatebugurl);

Map Parametermap = new HashMap ();
Parametermap.put ("Product", "Mobile: app-Sale (new)");
Parametermap.put ("Component", "payment");
Parametermap.put ("Version", "5.1");

Urlencodedformentity postentity = new Urlencodedformentity (GetParam (Parametermap), "UTF-8");
Httppost.setentity (postentity);
SYSTEM.OUT.PRINTLN ("Request line:" + httppost.getrequestline ());

Perform a POST request
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", "products name");
Parametermap.put ("Component", "payment");
Parametermap.put ("Version", "5.1");
Parametermap.put ("Short_desc", "Test 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", "Performance Test");
Parametermap.put ("Cf_impactenv", "Performance Test");

Each page of the token is different, especially after landing and the token to submit the difference is large
Parametermap.put ("token", token);

Urlencodedformentity postentity = new Urlencodedformentity (GetParam (Parametermap), "UTF-8");
Httppost.setentity (postentity);

Perform a POST request
HttpResponse HttpResponse =
Client.execute (HttpPost);

Setcookiestore (HttpResponse);

SetContext ();

}

/**
* Sea Analysis input stream get token, specimen <input type= "hidden" name= "token" value= "1432806799-DC8423DFBB4C68FB1305D5AA439F95A2" >
*/
Private String Inittoken (HttpResponse httpresponse)
Throws Exception
{
Get Response message Entity Content section
Httpentity htmlentity = httpresponse.getentity ();

String htmlstring = entityutils.tostring (htmlentity, "UTF-8");

String html = htmlstring.replace ("\ r \ n", "");

String prefix = "token\" value=\ "";
String suffix = "\" > ";

Find the starting position of the token string (not included)
int beginindex = html.indexof (prefix);

Find the token string end position (not included)
int endIndex = html.indexof (suffix, beginindex);
token = html.substring (Beginindex +, 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
{
Get Response message Entity
httpentity entity = httpresponse.getentity ();
Response status
System.out.println ("Status:" + Httpresponse.getstatusline ());
System.out.println ("headers:");
Headeriterator iterator = Httpresponse.headeriterator ();
while (Iterator.hasnext ())
{
System.out.println ("\ T" + iterator.next ());
}
Determine if the response entity is empty
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);
Create a new 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 ()
{
Trust all
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 ();
}
}

In the spirit of the principle of sharing resources, welcome all friends on this basis to improve and further share, let us achieve more elegant. If you have any questions and need further communication can add my QQ 1922003019 or directly send QQ mail to me to communicate

Sea 2015 China: Guangzhou: VIP

Simulate HTTP or HTTPS requests, implement Bugzilla logins under SSL, add bugs, maintain sessions, and process tokens

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.