About how to initiate an http request in java

Source: Internet
Author: User

How far can we go series (41)

Nonsense:

  I haven't summarized some things for a long time. I have no technical summary, and I feel that my work is empty. I have been tired recently.

Share something for the benefit of all mankind ~

Subject:

1. java simulates an http request

With HttpURLConnection, you can use the setRequestProperty method to set the http header content.
/*** Post Request * @ param strUrl * @ param content * @ param charset * @ return */public static String sendPost (String strUrl, String content, String charset) {URL httpurl = null; HttpURLConnection httpConn = null; String returnStr = ""; PrintWriter outs = null; try {httpurl = new URL (strUrl); httpConn = (HttpURLConnection) httpurl. openConnection (); httpConn. setRequestMethod ("POST"); // The default value is post // set No output to httpUrlConnection. Because this is a post request, the parameter must be placed in the http body, so it must be set to true. The default value is false; httpConn. setDoOutput (true); // sets whether to read data from httpUrlConnection. The default value is true; httpConn. setDoInput (true); httpConn. setRequestProperty ("Content-Type", "text/xml"); outs = new PrintWriter (httpConn. getOutputStream (); outs. print (content); outs. flush (); outs. close (); // byte stream reads all content including the line break returnStr = inputStreamToString (httpConn. getInputSt Ream (), charset);} catch (Exception e) {log. error ("executing HTTP Post request" + strUrl + ", an Exception occurred! ", E); if (outs! = Null) {outs. close (); outs = null;} return returnStr;} finally {if (httpConn! = Null) httpConn. disconnect (); if (outs! = Null) {outs. close (); outs = null;} return returnStr;} public static String inputStreamToString (InputStream in, String encoding) throws Exception {ByteArrayOutputStream outStream = new ByteArrayOutputStream (); byte [] data = new byte [BUFFER_SIZE]; int count =-1; while (count = in. read (data, 0, BUFFER_SIZE ))! =-1) outStream. write (data, 0, count); in. close (); data = null; return new String (outStream. toByteArray (), encoding );}
In the following code, we separate an inputStreamToString method to read the content of the request response. Here ByteArrayOutputStream is used to read the complete content of the response body. line breaks are not lost. note this. For example, if BufferedReader is used, the code is similar to this:
            String line, result = "";            BufferedReader in = new BufferedReader( new InputStreamReader(conn.getInputStream(), "utf-8" ));            while ((line = in. readLine()) != null) {                result += line + "\n";            }            in.close();

 

In order not to discard the line feed, you need to splice "\ n" by yourself. Another problem is that "+" is used to concatenate strings in a loop, and the performance is poor. Reference: You can also use HttpClient to send post requests. Feel the following:
Public static String sendPost (String url, Map <String, String> params, String charset) {StringBuffer response = new StringBuffer (); HttpClient client = new HttpClient (); httpMethod method = new PostMethod (url); method. getParams (). setCookiePolicy (CookiePolicy. IGNORE_COOKIES); method. setRequestHeader ("Cookie", "special-cookie = value"); method. setRequestHeader ("", ""); // sets the Http Post data if (params! = Null) {HttpMethodParams p = new HttpMethodParams (); for (Map. entry <String, String> entry: params. entrySet () {p. setParameter (entry. getKey (), entry. getValue ();} method. setParams (p);} try {client.exe cuteMethod (method); if (method. getStatusCode () = HttpStatus. SC _ OK) {BufferedReader reader = new BufferedReader (new InputStreamReader (method. getResponseBodyAsStream (), charset); String line; w Hile (line = reader. readLine ())! = Null) {response. append (line);} reader. close () ;}} catch (IOException e) {log. error ("executing HTTP Post request" + url + ", an exception occurred! ", E) ;}finally {method. releaseConnection () ;}return response. toString ();}

 

2. Simulate logon to the public platform

Since we can simulate post requests, we can also simulate logon theoretically. Generally, the login process is to initiate a post request and send the account and password to the server. After the server passes verification, write cookies in resopnse and jump to the page. Then, the interaction with the server is based on cookies. What we need to do is to initiate a request and save the cookies returned successfully. Each subsequent operation that requires logon status to interact with the server carries cookies. CookiesIn fact, this is the process: client --- post request ---> server client <-- Return cookies -- server client-request with cookies -- server first, the login request is as follows: public final static String REFERER_H = "Referer"; private LoginResult _ login (String username, String pwd) {LoginResult loginResult = new LoginResult (); try {PostMethod post = new PostMethod (LOGIN_URL); post. setRequestHeader ("Referer", "https://mp.weixin.qq.com/"); post. setRequestHeader (response, USER_AGENT); NameValuePair [] params = new NameValuePair [] {new NameValuePair ("username", username), new NameValuePair ("pwd", DigestUtils. md5Hex (pwd. getBytes (), new NameValuePair ("f", "json"), new NameValuePair ("imagecode", "")}; post. setQueryString (params); int status = client.exe cuteMethod (post); if (status = HttpStatus. SC _ OK) {String ret = post. getResponseBodyAsString (); LoginJson retcode = JSON. parseObject (ret, LoginJson. class); // System. out. println (retcode. getRet (); if (retcode. getBase_resp (). getRet () = 302 | retcode. getBase_resp (). getRet () = 0) {loginResult. setCookie (client. getState (). getCookies (); StringBuffer cookie = new StringBuffer (); // process cookies for (Cookie c: client. getState (). getCookies () {cookie. append (c. getName ()). append ("= "). append (c. getValue ()). append (";"); cookiemap. put (c. getName (), c. getValue ();} loginResult. setCookiestr (cookie. toString (); loginResult. setToken (getToken (retcode. getRedirect_url (); loginResult. setLogin (true); return loginResult;} else {loginResult. setLogin (false); return loginResult ;}} catch (Exception e) {String info = "[Logon Failed] [Exception:" + e. getMessage () + "]"; System. err. println (info); log. debug (info); log.info (info); return loginResult ;}

 

All the code has been shared:Github hopes to help you ~

 

3,Redirection Problems

  Have you ever been asked during the interview: The difference between forword and redirect.

There are also a lot of answers on the Internet. Let's look back at this question. In fact, forword is a request initiated by the server to access resources under its own application. Because it was initiated by the server itself, the parameters previously passed by the client can be kept, and the content returned by the accessed internal resource is used as the response of the client's initial request, so the browser url will not change.

  Then redirectPrinciple: Actually, after receiving a request from the client, the server adds a location item to the header in the response. The principle of this item is as follows:

When the browser accepts Location: xxxx in the header information, it will automatically jump to the URL address pointed to by xxxx, which is similar to writing a jump using js. But this jump is only known by the browser, no matter whether there is anything in the body, the user can not see it. Example: header ("Location: http://www.xker.com/"); that is to say RedirectIts implementation also relies on the combination of browser mechanisms. In this way, we can understand that a response with location is returned first, and then the browser initiates a new request to the value under location. Because it is a request initiated by the browser, the parameters in the first request cannot be kept. Because it is a new request, the url of the browser will change. You can also know whether the http status code is 302 in the response with location. This may be a deeper understanding ~

  

 

Let's move on

----------------------------------------------------------------------

Hard work may fail, but not hard work will certainly fail.

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.