How httpclient handles 302 redirection

Posted by keeB on Tue, 03 Sep 2019 05:17:17 +0200

When using httpclient for interface testing, we encounter a redirected interface, which must be redirected to another domain name due to framework reasons. This problem was solved by modifying the request method, which had not been encountered before. The general idea is: if you find that HTTP code is 302, you will go to the header array to find the location field, and put the results of the field into the response body, my response body is in json format.

  • A part of the configuration of HTTP client connection pool and request config needs to be modified.

The code is as follows:

    /**
     * Getting response entities
     * <p>Cookies are automatically set, but each project needs to implement cookie management on its own.</p>
     * <p>This method only deals with text information. For file processing, two expired methods can be invoked to solve the problem.</p>
     *
     * @param request Request object
     * @return Returns an object of type json
     */
    public static JSONObject getHttpResponse(HttpRequestBase request) {
        if (!isRightRequest(request)) return new JSONObject();
        beforeRequest(request);
        JSONObject res = new JSONObject();
        RequestInfo requestInfo = new RequestInfo(request);
        if (HEADER_KEY) output("===========request header===========", Arrays.asList(request.getAllHeaders()));
        long start = Time.getTimeStamp();
        try (CloseableHttpResponse response = ClientManage.httpsClient.execute(request)) {
            long end = Time.getTimeStamp();
            long elapsed_time = end - start;
            if (HEADER_KEY) output("===========response header===========", Arrays.asList(response.getAllHeaders()));
            int status = getStatus(response, res);
            JSONObject setCookies = afterResponse(response);
            String content = getContent(response);
            int data_size = content.length();
            res.putAll(getJsonResponse(content, setCookies));
            int code = iBase == null ? -2 : iBase.checkCode(res, requestInfo);
//            if (!iBase.isRight(res))
//                new AlertOver("Response Status Code Error:"+status,""Status Code Error:"+status, requestInfo.getUrl(), requestInfo).sendSystemMessage();
            MySqlTest.saveApiTestDate(requestInfo, data_size, elapsed_time, status, getMark(), code, LOCAL_IP, COMPUTER_USER_NAME);
        } catch (Exception e) {
            logger.warn("The acquisition request failed accordingly!", e);
            if (!SysInit.isBlack(requestInfo.getHost()))
                new AlertOver("Interface request failed", requestInfo.toString(), requestInfo.getUrl(), requestInfo).sendSystemMessage();
        } finally {
            HEADER_KEY = false;
            if (!SysInit.isBlack(requestInfo.getHost())) {
                if (requests.size() > 9) requests.removeFirst();
                boolean add = requests.add(request);
            }
        }
        return res;
    }
    
    
        /**
     * Get the response state and process the redirected url
     *
     * @param response
     * @param res
     * @return
     */
    public static int getStatus(CloseableHttpResponse response, JSONObject res) {
        int status = response.getStatusLine().getStatusCode();
        if (status != HttpStatus.SC_OK) logger.warn("Response status code error:{}", status);
        if (status == HttpStatus.SC_MOVED_TEMPORARILY)
            res.put("location", response.getFirstHeader("Location").getValue());
        return status;
    }

The following is the configuration:

    /**
     * Acquisition request timeout controller
     * <p>
     * cookieSpec:That is cookie policy. Some fields whose parameters are cookiespecs. Effect:
     * 1,If there is set-cookie field in the website header, it may be rejected by cookie by default and cannot be written to cookie. Setting this property to CookieSpecs.STANDARD_STRICT avoids this situation.
     * 2,If you want to ignore cookie access, set this property to CookieSpecs.IGNORE_COOKIES.
     * </p>
     *
     * @return
     */
    private static RequestConfig getRequestConfig() {
        return RequestConfig.custom().setConnectionRequestTimeout(HttpClientConstant.CONNECT_REQUEST_TIMEOUT).setConnectTimeout(HttpClientConstant.CONNECT_TIMEOUT).setSocketTimeout(HttpClientConstant.SOCKET_TIMEOUT).setCookieSpec(CookieSpecs.IGNORE_COOKIES).setRedirectsEnabled(false).build();
    }

Request config can be set either when creating an HTTP client connection pool or when setting up an HTTP request base. Here I take the first approach.

In learning selenium 2 java, I encountered a drop-down box when I wrote the use case of the receiving address. I just practiced the use of select. Now I share it for your reference.

	//Delete Add Receiving Address
	public static void deleteAndAddUserAdress(WebDriver driver) throws InterruptedException {
		clickUser(driver);
		findElementByTextAndClick(driver, "Personal information");
		findElementByTextAndClick(driver, "Receiving address");
		clickDeleteAdress(driver);
		sleep(0);
		clickSure(driver);
		AddAddress(driver);
		String name = getTextByXpath(driver, ".//*[@id='main']/div[2]/div/div/div[1]/p[1]");
		assertTrue("Failed to add harvest address!", name.equals("Consignee:Test consignee"));
	}

The following is a specific way to add the receiving address:

//Add Receiving Address
	public static void AddAdress(WebDriver driver) {
		findElementByIdAndClick(driver, "add-address-btn");//Click Add Address
		findElementByXpathAndClearSendkeys(driver, ".//* [@id='LAY_layuipro1a']/div/div[1]/table/tbody/tr[1]/td[2]/div/input,""Test consignee";//Add consignee"
		findElementByXpathAndClearSendkeys(driver, ".//* [@id='LAY_layuipro1a']/div/div[1]/table/tbody/tr[2]/td[2]/div/input,""13120454218";//input mobile phone number
		//Selection of provinces, cities and counties, and detailed addresses
		Select province = new Select(findElementByid(driver, "province-select"));
		province.selectByIndex(1);
		Select city = new Select(findElementByid(driver, "city-select"));
		city.selectByIndex(1);			
		Select area = new Select(findElementByid(driver, "area-select"));
		area.selectByIndex(1);
		findElementByClassnameAndClearSendkeys(driver, "textarea", "I'm the test address.");
		clickSave(driver);
	}

Selection of previous articles

  1. One line of java code prints a heart
  2. Chinese Language Version of Linux Performance Monitoring Software netdata
  3. Interface Test Code Coverage (jacoco) Scheme Sharing
  4. Performance testing framework
  5. How to Enjoy Performance Testing on Linux Command Line Interface
  6. Graphic HTTP Brain Map
  7. Writing to everyone about programming thinking
  8. How to Test Probabilistic Business Interface
  9. httpclient handles multi-user simultaneous online
  10. Ten Steps to Become a Great Java Developer
  11. Automatically convert swagger documents into test code
  12. Five lines of code to build static blogs
  13. How httpclient handles 302 redirection

Public Number Map ☢️ Together ~FunTester

Topics: Programming Java JSON Linux Selenium