Interface Test (ii)-httpclient

Source: Internet
Author: User

Using HttpClient for interface testing, the relevant code to use

HttpClient for interface Testing
Required jar Packages: Httpclient.jar, Httpcore.jar, Commons-logging.jar
GET Request:
Create a HttpClient object
Closeablehttpclient httpClient = Httpclients.createdefault ();
If you are sending a GET request, create a HttpGet object
HttpGet httpget = new HttpGet ("http://www.baidu.com/");
Perform a GET request
Closeablehttpresponse response = Httpclient.execute (HttpGet);

POST request:
Closeablehttpclient httpClient = Httpclients.createdefault ();
If the send is a POST request, create the HttpPost object
HttpPost HttpPost = new HttpPost ("Http://localhost:8080/login");
Post request parameter Configuration
list<namevaluepair> formparams = new arraylist<namevaluepair> ();
Formparams.add (New Basicnamevaluepair ("name", "xxx"));
Formparams.add (New Basicnamevaluepair ("pwd", "123456"));
Set the encoding format to Utf-8
Urlencodedformentity uefentity = new Urlencodedformentity (formparams, "UTF-8");
Httppost.setentity (uefentity);//set POST request parameters
Send an interface request using the Execute method of HttpClient
Closeablehttpresponse response = new Httpclient.execute (httppost);

After you create the HttpClient object, the Response object operation is complete, you need to release
Release connection
Response.close ();
Httpclient.close ();

Common methods:
1. Set the request and connection timeout time
Requestconfig requestconfig = Requestconfig.custom (). SetSocketTimeout (20000). Setconnecttimeout (20000). build ();
Get request set request and transmit timeout time
Httpget.setconfig (Requestconfig);
Post request set request and transmit timeout time
Httppost.setconfig (Requestconfig);

2. Get the response header information
Header headers[] = Response.getallheaders ();
for (Header header:headers) {
Response header Information Name
System.out.println (Header.getname ());
The value corresponding to the header information
System.out.println (Header.getvalue ());
}

3. Get the response header information for the server-specified header name
Header serverheaders[] = response.getheaders ("Server");

4, get the server return status code, if equal to 200 indicates that the request and response are successful
Response.getstatusline (). Getstatuscode ();
Common error Codes:
200 the request is successful and the requested information is included in the response
400 server failed to recognize request
404 the requested resource is not on the server
500 an error occurred in the request

5. Obtain the actual IP address of all the servers it may have, depending on the hostname (may contain multiple servers)
inetaddress[] address = Inetaddress.getallbyname ("www.baidu.com");
for (int i = 0; i < address.length; i++) {
System.out.println (address[]);
}

6, call HttpResponse's GetEntity () method to get the Httpentity object, the response content of the server
String returnstr = entityutils.tostring (Response.getentity ());
(Common server-returned responses typically include: XML, JSON format, etc.)

Server Response Content Resolution
1. Using the Jsonobject plugin to process XML, JSON response data
2, need 6 jar package: Json-lib.jar, Commons-beanutils.jar, Commons-collections.jar, Ezmorph.jar, Commons-logging.jar, Commons-logging.jar
Xom.jar transform XML data into JSON data
String xml = "<?xml version=\" 1.0\ "encoding=\" utf-8\ "?><users><password>123456</password> <username>xxx</username></users> ";
XMLSerializer XMLSerializer = new XMLSerializer ();
Use the Xmlserializer.read () method to convert data in XML format to JSON-formatted data
JSON JSON = Xmlserializer.read (XML);
Converted JSON data
{"Password": "123456", "username": "XXX"}

JSON common parsing methods
Convert a JSON string to a Jsonobject object
Jsonobject jsonobj = Jsonobjec.fromobject (JSON string);
Get the value corresponding to name
Jsonobj.getstring ("name");//Take the value corresponding to the node xxx jsonobj.getint (XXX);
Determines whether the JSON string contains the name node if there is a return true
Jsonobj.has ("name");

To parse complex results
{
"ReturnCode": 0,
"Message": "",
"Count": 2,
"Result": {
"Users": [{"pwd": "123456", "name": "XXX"},
{"pwd": "123456", "Name": "AAA"}]
}
}

Convert a JSON string to a Jsonobject object
Jsonobject jsonobj = Jsonobject.fromobject (JSON string);
Result is a JSON object that uses Getjsonobject () to get
Jsonobject resultobj =jsonobj.getjsonobject ("return");
Users are array objects, you can use Getjsonarray () to get a JSON array
Jsonarray userlist = Resultobj.getjsonarray ("users");
You can iterate over the object elements in the array
for (Object object:userlist) {
Jsonobject user = (Jsonobject) object;
User.getstring ("pwd");
User.getstring ("name");
}

Interface Test (ii)-httpclient

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.