HTTP Interface Test Summary

Source: Internet
Author: User
Tags http request

1, send Get/post request
a) Get request using HttpClient
code example:

 public static String Gethttpresponse4get () {closeablehttpclient httpclient = Httpclients.createde
		Fault ();
		String url = "http://www.tmall.com/test.do?id=123";
		GetMethod httpget = new GetMethod (URL); Httpget.addrequestheader ("Content-type", "text/html;
		CHARSET=GBK ");
		Httpget.getparams (). Setparameter ("Http.socket.timeout", 20000); try {//is set to the default recovery policy, automatically retries 3 times when an exception occurs, where you can also set a custom recovery policy httpget.getparams (). Setparameter (Httpmethodparams.retry_
			Handler,new Defaulthttpmethodretryhandler ());  if (Httpclient.executemethod (httpget)! = HTTPSTATUS.SC_OK) {System.out.println ("HttpGet (\" + URL + "\") failed: \ n "+
				Httpget.getstatusline ());
				return null;
			} return httpget.getresponsebodyasstring ();
				} catch (Exception e) {System.out.println ("HttpGet (\" "+ URL +" \ ") failed: \ n" + e.getmessage ());
			return null;
			} finally {httpget.releaseconnection ();
			HttpClient = null; }
		}


Note the point:
1, incoming parameter value (or parameter string) need to be encode, although httpclient is useful urlcodec.encodeurl () encode, but I experiment found, and Urlencoder.encode () The result of the encode or the difference, will affect the final response, so it is recommended to encode the self;
2, need to determine whether the status code returned by the request is 200 after the obtained response is reliable;
3, finally to release the link, do the finishing work.

b) Post request
code example:

public static String Gethttpresponse4post () {try {HttpClient client = new Defaulthttpclient ();
			HttpPost request = new HttpPost ("http://www.tmall.com/test.do");
			Use Namevaluepair to save the post parameter to be passed list<namevaluepair> postparameters = new arraylist<namevaluepair> ();
			Add the parameter Postparameters.add to be passed (new Basicnamevaluepair ("id", "12345"));
			Postparameters.add (New Basicnamevaluepair ("username", "Dave"));
			Instantiate the Urlencodedformentity object urlencodedformentity formentity = new urlencodedformentity (postparameters);
			Use the HttpPost object to set the entity request.setentity (formentity) of the urlencodedformentity;
			HttpResponse response = Client.execute (request); if (Response.getstatusline (). Getstatuscode () = = HTTPSTATUS.SC_OK) {String s = entityutils.tostring (response.getentity
				(), "utf-8");
				System.out.println (s);
				SYSTEM.OUT.PRINTLN ("request normal, End HTTP request");
			return s;
			}} catch (Exception e) {System.out.println ("request exception, exception information thrown"); E.printstacktrace ();
		} finally {Httpclient.getconnectionmanager (). Shutdown ();
	} return ""; }


c) Send GET request on-line environment
To put an HTTP interface test script running under daily on a line, you need to do the following:
1. Establish a real login session: Send POST request to: https://login.taobao.com/member/login.jhtml
2. Then send a GET request to http://i.taobao.com/my_taobao.htm to synchronize cookies from the cache once
3, through This.httpClientLogin.getState (). GetCookies (); Gets the cookie information and resolves the value to _tb_token_
4. Attach this _tb_token_ parameter and value to the URL of the test request, and make the request by the Get method
5, note: In the login post parameter settings, you need to set the character set to: GBK

If you change to Utf-8 or do not set this param it may result in an insufficient cookie value being obtained
(This section thanks to the meticulous advice from the students.) )

2, Urlencode/urldecode
Why URLs need to be encode later to be sent because the URL needs to be converted to an ASCII character set in order to be used by the HTTP protocol. The ASCII character set is a 7-bit character set that contains 128 characters, common in numbers 1-9, with a-za-z and some special characters. When a URL contains characters in a non-ASCII character set, the encode is required to be an ASCII character set for sending requests over the HTTP protocol
The methods for URL encode and decode in Java are:

Urlencoder.encode (Valueofurlparam, "UTF-8");   

Two classes are from the java.net package, you can use the online Encode/decode website to do
It is important to note that:
You can only encode the parameters of the URL (you can encode the entire argument string, or only encode the parameter values, and you cannot encode the domain name and URI, for example:
http://www.tmall.com/test.do?id=123,234, the correct encode after the URL is:
http://www.tmall.com/test.do?id%3d123%2c234 or:
http://www.tmall.com/test.do?id=123%2c234
When using the post to send the request, the parameter content needs to be assembled into httpentity and set into the Post object, which will use the Urlencodedformentity class, this class of constructors will be the post parameters of the encode, So you don't need to do an extra encode, or the application server will read the wrong parameter value in one decode case

3. Mock
A) parameter mock
Problem scenario: In a server-side application, there are usually such fragments:

	public static Long Getloginuserid (Turbinerundata rundata) {
		string userId = (string) rundata.getrequest (). GetSession ()
				. getattribute (sessionkeeper.attribute_user_id_num);
		if (Stringutils.isnumeric (userid)) {
			return Long.parselong (userid);
		}
		return null;
	}


	if (Userid==null | | userId <= 0) {
		result.setsuccess (false);
		Result.seterrorcode (mallbrandresultcode.user_not_login);
		Result.seterrormsg ("parameter user_id Missing");
		}


If the WEBX cannot get the UserID from the session, it will be controlled by the business logic and cannot continue down, there are two workarounds:
L. Go to the session and plug in the UserID
To implement this scenario, you first need to create a real daily under the user login session, because it is under the daily, but also need to address the issue of security authentication, so that can solve the problem. But obviously the cost of doing so is too high and not necessary.
L Mock off this code logic with get parameters
and development Convention a parameter and parameter value, in the program to determine if there is this parameter value directly returns a specified userid.

b) Compress mock
In order to prevent the JSON data sent by the front end of the HTTP GET request is very long, the front-end development through 7zip compression, but httpclient that such a compressed request is badrequest, so can only attempt to change the request to post, while the extracted logic to mock off, In order to facilitate the interface test under daily. For details, please refer to the URL length limitation in HTTP interface test (Maximum URL)
c) CSRF Control mock
In order to prevent CSRF attacks, will be added to the CSRF control module, under the daily can be directly let the development of the logic commented out, but if the script also go back after the system, it needs to be developed together with the logic to mock off, to simplify the test application complexity, reduce the difficulty of test script development.

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.