Java implements the get and post methods for Network Interactions

Source: Internet
Author: User

I finally finished all the courses I was about to attend. The intensity was too high. I was too tired to write my blog. I haven't written it for a long time... But now we have to summarize it gradually!

Since we are mainly studying network interaction recently, let's start with the most basic java implementation of get and post requests:

First, we need to understand the http get and post request methods,
1. Additional information after the URL address in get mode;
After the URL, the browser uses "?" Format with data. Multiple Data are separated by &, for example, http: // localhost: 8080/MyApp/myServlet? Name1 = value1 & age = value2

Request example:
GET/myApp/1.html? Name = tom & age = 21 HTTP/1.1
Accept-Language: zh-cn
Accept-Encoding: gzip, deflate
Host: localhost: 8080
Connection: Keep-Alive

2. entity content in the HTTP request message in post mode;
The form method attribute is set to "post". The HTTP request method generated when the form is submitted is Content-Type: application/x-www-form-urlencoded.
Form of parameters transmitted in POST mode: transmitted as the entity Content Part of the Request Message

Request example:
POST/myApp/1.html HTTP/1.1
Accept-Language: zh-cn
Accept-Encoding: gzip, deflate
Host: localhost: 8080
Connection: Keep-Alive

Name = tom & age = 21

The following code is implemented using java:


1. We first use the underlying Socket to implement:
Get method:
Socket socket = new Socket ("localhost", 8080); StringBuffer sb = new StringBuffer (); sb. append ("POST/Servlett? Name = tom & age = 21 HTTP/1.1 \ r \ n "); // request address and parameter sb. append ("Connection: close \ r \ n"); // Connection status sb. append ("Host: localhost: 8080 \ r \ n"); // network address, port sb. append ("\ r \ n ");
Socket. getOutputStream (). write (sb. toString (). getBytes (); // send to server

Post method:

StringBuffer sb = new StringBuffer (); sb. append ("POST/Servlett HTTP/1.1 \ r \ n"); sb. append ("Connection: close \ r \ n"); sb. append ("Host: localhost: 8080 \ r \ n"); sb. append ("Content-Type: application/x-www-form-urlencoded \ r \ n"); // The parameter Content sb. append ("\ r \ n"); sb. append ("name = tom & age = 21"); socket. getOutputStream (). write (sb. toString (). getBytes ());

To accept the information sent from the server, you can directly obtain it using InputStream and then process it. ye can use the formatIsToString () method mentioned below to process the result as a String type.

In fact, the difference between the get method and the post method should be clear here, because the get method places the parameters (user data) in the url, which is easy to get in the browser and extremely insecure; the post method places parameters in the content, which is secure and will not be found during the request process. Therefore, in web projects, the submission methods for user information are post.


2. In fact, there is a class in java: HttpURLConnection, which has encapsulated these things. We can use it to implement
First, we need a method to convert an InputStream object into a String object (a simple method)
public static String formatIsToString(InputStream is)throws Exception{ByteArrayOutputStream baos = new ByteArrayOutputStream();byte[] buf = new byte[1024];int len = -1;try {while( (len=is.read(buf)) != -1){baos.write(buf, 0, len);}baos.flush();baos.close();is.close();} catch (IOException e) {e.printStackTrace();}return new String(baos.toByteArray(),"utf-8");}

Get method implementation:
Public static String get (String apiUrl) throws Exception {String str = null; URL url = new URL (apiUrl); HttpURLConnection con = (HttpURLConnection) url. openConnection (); con. setReadTimeout (5000); // set the read timeout value to the specified timeout value, in milliseconds. Use a non-zero value to specify the timeout value for reading data from the Input stream after the connection to the resource is established. If the timeout period expires before the data can be read, a java.net. SocketTimeoutException is triggered. Con. setDoInput (true); // indicates that the application needs to read data from the URL Connection. Con. setRequestMethod ("GET"); // sets the request method if (con. getResponseCode () = 200) {// when the request is successful, the received data (status code "200" indicates a successful connection "OK") InputStream is = con. getInputStream (); str = formatIsToString (is);} return str ;}


Post method implementation:

Put the request parameter content in a Map and parse it before sending it (the following getContent () method is used here)

Public static String post (String apiUrl, HashMap
  
   
Params) throws Exception {String str = null; URL url = new URL (apiUrl); // create a URL object HttpURLConnection con = (HttpURLConnection) url based on parameters. openConnection (); // get the HttpURLConnection object con. setRequestMethod ("POST"); con. setreadtimeouts (5000); con. setDoInput (true); con. setDoOutput (true); // indicates the application to write data to a URL Connection. String content = getContent (params); // resolution parameter (request content) con. setRequestProperty ("Content-Type", "application/x-www-form-urlencoded"); // sets the Content con. setRequestProperty ("Content-Length", content. length () + ""); // set the content length OutputStream OS = con. getOutputStream (); OS. write (content. getBytes ("UTF-8"); // sends the parameter content OS. flush (); OS. close (); if (con. getResponseCode () == 200) {str = formatIsToString (con. getInputStream ();} return str ;}
  

Parse parameters in map
Private static String getContent (HashMap
  
   
Params) throws UnsupportedEncodingException {String content = null; Set
   
    
> Set = params. entrySet (); // The Map. entrySet method returns the ing collection view, where the elements belong to this type of StringBuilder sb = new StringBuilder (); for (Entry
    
     
I: set) {// resolve the parameter to the "name = tom & age = 21" Mode sb. append (I. getKey ()). append ("= "). append (URLEncoder. encode (I. getValue (), "UTF-8 ")). append ("&");} if (sb. length ()> 1) {content = sb. substring (0, sb. length ()-1);} return content ;}
    
   
  
The advantage of using the Entry is that you do not need to know the key value. You can use the getKey () and getValue () methods to obtain all values in the map.

Related Article

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.