Simple encapsulation of data requests for Java interface Automation testing

Source: Internet
Author: User

We use Java to write interface Automation test framework or to do an interface Automation test platform, it is necessary to make the relevant request, so we need a simple encapsulation under httpclient, I created a new HTTP tool class, the Get method and the Post method in a simple package.

If it is developed, such as app development, whether it is iOS or Android, the data request needs to be very tightly encapsulated, because of the need for a variety of network state, request the status of the corresponding judgment processing, because these judgments need to make the corresponding UI interface to the user prompt, Then we do interface testing is not necessary so strict, because the premise of testing is to ensure the stability of the test environment, we only consider the interface under normal access through the parameters of the various control to determine whether the interface has made the correct data transmission.

The first few have recorded the simple httpclient get and post requests, the following is a simple encapsulation of them, making it easier for us to use

Package Com.httpclientget;import Java.io.ioexception;import Java.io.inputstream;import java.io.OutputStream;import Java.util.arraylist;import Java.util.map;import Org.apache.http.header;import Org.apache.http.HttpEntity;import Org.apache.http.httpresponse;import Org.apache.http.namevaluepair;import org.apache.http.client.HttpClient; Import Org.apache.http.client.config.requestconfig;import Org.apache.http.client.config.RequestConfig.Builder; Import Org.apache.http.client.entity.urlencodedformentity;import Org.apache.http.client.methods.httpget;import Org.apache.http.client.methods.httppost;import Org.apache.http.impl.client.httpclients;import Org.apache.http.impl.conn.poolinghttpclientconnectionmanager;import Org.apache.http.message.BasicNameValuePair; Import Org.apache.http.util.entityutils;public class Httputil {//connection pool private static Poolinghttpclientconnectionmanager connectionmgr;//Timeout time private static final int max_timeout = 7000;private static Requestconfig requestconfig;static{//setting Connection Pool COnnectionmgr = new Poolinghttpclientconnectionmanager ();//Set Connection pool size connectionmgr.setmaxtotal (100); Connectionmgr.setdefaultmaxperroute (Connectionmgr.getmaxtotal ()); Requestconfig.builder Configbuilder = Requestconfig.custom ();//Set Connection Timeout configbuilder.setconnecttimeout (MAX_TIMEOUT) ;//Set Read timeout configbuilder.setsockettimeout (max_timeout);// Sets the timeout configbuilder.setconnectionrequesttimeout (max_timeout) for getting the connection instance from the connection pool; requestconfig = Configbuilder.build ();}  /** * GET request with input parameter * @param URL request host address * @param params parameter * @return */public static string HttpGet (string Url,map<string, Object>params) {//Returns the result String results = null;//stitching Urlstringbuilder builder = new StringBuilder (URL); if (Url.contains ("?")) {Builder.append ("&");} Else{builder.append ("?");} int I=0;for (String key:params.keySet ()) {if (I! = 0) {builder.append ("&");} Builder.append (key); Builder.append ("="); Builder.append (Params.get (key)); i++;} String Apiurl = builder.tostring ();//create clienthttpclient client = Httpclients.createdefAult (); try {httpget get = new HttpGet (Apiurl); HttpResponse response = Client.execute (get);//Get Request status code int statusCode = Response.getstatusline (). Getstatuscode (); System.out.println (StatusCode); httpentity entity = response.getentity (), if (entity! = null) {result = Entityutils.tostring (entity, "UTF-8");}} catch (Exception e) {e.printstacktrace ();} return result;} /** * POST request * @param URL Request URL * @param params POST Submit parameter * @return */public Stati C string HttpPost (String url,map<string, Object>params) {HttpClient client = Httpclients.createdefault (); String result = Null;try {HttpPost post = new HttpPost (URL);//Add post submit parameter arraylist<namevaluepair> pairlist = new Arra    Ylist<namevaluepair> (); For (map.entry<string, object> entry:params.entrySet ()) {Namevaluepair pair = new Basicnamevaluepair (entry.get    Key (), Entry.getvalue (). toString ());    Pairlist.add (pair); } post.setentity (New Urlencodedformentity (Pairlist, "UTF-8 "));    HttpResponse response = Client.execute (POST);    Get the status code int statuecode = Response.getstatusline (). Getstatuscode ();        System.out.println (Statuecode);    httpentity entity = response.getentity ();    if (Entity! = null) {result = Entityutils.tostring (entity);} } catch (Exception e) {e.printstacktrace ();} return result;}}

To do a simple test:

               Httputil util = new Httputil (); map<string, object> params = new hashmap<string, object> ();p arams.put ("Q", "good");p arams.put ("Salt", " 1496238482428 ");p arams.put (" sign "," 02e15cdaf871b698fe04ee32fd2cf155 ");p the Arams.put (" from "," en ");p arams.put (" AppKey "," 7743eee7f7e11d75 ");p arams.put (" to "," Zh-chs "); String result = Util.httppost (urlstr, params); SYSTEM.OUT.PRINTLN (result);

Output Result:

{"Tspeakurl": "https://dict.youdao.com/dictvoice?audio=%e5%a5%bd&le=auto&channel=7743eee7f7e11d75&            Rate=4 "," Web ": [{" Value ": [" good "," good "," commodity "                ], "key": "Good"}, {"Value": ["Public goods", "philanthropy", "Public Wealth"], "key": "Good"}, {"Value": ["good job] "Good job", "good work"], "key": "Good Job"}], "Query": "Good" , "translation": ["good"], "ErrorCode": "0", "basic": {"us-phonetic": "ɡ?d", "phonetic":            "G?d", "uk-phonetic": "G?d", "explains": ["N. benefits; good deeds; generous deeds", "adj. fine, fine, pleasant, pious", "Adv. Good", "N." (good) name, (English) Speakurl, (Sweden) "]}," Https://dict.youdao.com/dictvoice ":" Audio=good&le=auto&channEl=7743eee7f7e11d75&rate=4 "} 

If you do not need to pass in the parameters, the second passed in the parameter to NULL, which is simply encapsulated, in the subsequent writing of the automated test framework we may still have to add a variety of judgments and log output, after all, testing the most important is the assertion and so on such test results.

Simple encapsulation of data requests for Java interface Automation testing

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.