Guidelines for the use of communication APIs in JDK

Source: Internet
Author: User
Tags html header http post alphanumeric characters
1 Overview

The URLConnection, sockets, and servlet in the JDK are very popular in Web application interface development. In this paper, the HTTP interface mode, socket interface and other methods are analyzed, the code examples and difficult problems are explained.

HttpURLConnection use of the guide, the main reference to some technical information on the Internet.

This document is suitable for all Java developers. 2 basic knowledge 2.1 http requests

HTTP defines different methods of interacting with the server, and the most basic method is get and POST.

L de facto get applies to most requests, while the reserved POST is used only for updating the site. According to the HTTP specification, get is used for information acquisition, and should be secure and idempotent. The so-called safe means that the operation is used to obtain information rather than modify information. In other words, get requests should not generally have side effects. Idempotent means that multiple requests to the same URL should return the same result. The complete definition is not as strict as it seems. Fundamentally, the goal is that when a user opens a link, she can be sure that it doesn't change resources from its perspective. For example, the front pages of news sites are constantly being updated. Although the second request returns a different batch of news, the operation is still considered safe and idempotent, as it always returns the current news. Vice versa. POST requests are not that easy. POST represents a request that might change resources on the server. Still, for example, a news site, the reader's note to the article should be implemented through post requests, because the site has been different after the annotation was submitted (for example, an annotation appears below the article);

l When the form is submitted, if no method is specified, the default is GET request, and the data submitted in the form is appended to the URL to separate it from the URL. Alphanumeric characters are sent as is, but spaces are converted to "+", and other symbols are converted to%XX, where XX is the ASCII (or ISO Latin-1) value that the symbol is in 16. A GET request requests that the data submitted be placed in the HTTP request protocol header, while the post-submitted data is placed in the Entity data;

Concrete Example see: Post request Content instance 2.2 Get and post differences

1. Get is to obtain data from the server, post is to transfer data to the server. 2. Get is to add the parameter data queue to the URL of the action attribute that submits the form, and the value corresponds to each field one by one in the form, which can be seen in the URL. Post is the HTTP post mechanism that places the fields in the form and their contents in the HTML header to the URL address that the action attribute refers to. This process is not visible to the user. 3. For Get way, server end uses Request.QueryString to obtain variable value, for post way, server end uses Request.Form to obtain the submitted data. 4. The amount of data transferred by get is small and cannot be greater than 2KB. Post transfers have a large amount of data, which is generally default to unrestricted. In theory, however, the maximum number of IIS4 is 100KB in 80KB,IIS5. 5. Get security is very low, post security is high. 2.3 httpurlconnection

A URLConnection with support for Http-specific features. The spec for details.

Each httpurlconnection instance are used to make a single request but the underlying network connection to the HTTP server May is transparently shared by the other instances. Calling the Close () methods on the InputStream or OutputStream of ' a httpurlconnection after a ' request may free network re Sources associated with this instance but has no effect on any shared persistent connection. Calling the disconnect () method could be close the underlying socket if a persistent connection was otherwise idle at this time. 3 HttpURLConnection Use Guide 3.1 urlconnection object problem c7>

URLConnection object, as shown in the following code example:

The following index.jsp are mapped by <servlet-mapping> to//a servlet (com.quantanetwork.getClientDataServlet)// A URL url = new URL ("http://localhost:8080/TestHttpURLConnectionPro/index.jsp") is mentioned below in the servlet's attention point;

URLConnection rulconnection = url.openconnection ()//The URLConnection object here is actually generated based on the URL's//Request Protocol (here is HTTP) urlconnect Ion class//subclass HttpURLConnection, so it is best to convert it//to the HttpURLConnection type of object, in order to use//HttpURLConnection more Many APIs, as follows:

httpurlconnection httpurlconnection = (httpurlconnection) rulconnection; 3.2 httpurlconnection Object parameter Problem

Set whether to output to httpurlconnection, because this is a POST request, the parameter should be placed in//HTTP body, so you need to set to true, by default, false; Httpurlconnection.setdooutput (TRUE);

The setting is read from HttpURLConnection and is true by default; Httpurlconnection.setdoinput (TRUE);

The Post request cannot use the cache Httpurlconnection.setusecaches (false);

Set the delivered content type is a serializable Java object//(if not set, the java.io.EOFException may be thrown when the serialization object is routed when the Web service defaults to this type) Httpurlconnection.setrequestproperty ("Content-type", "Application/x-java-serialized-object");

The method to set the request is "POST" and the default is get Httpurlconnection.setrequestmethod ("post");

//connection, from the above 2nd url.openconnection () the configuration must be completed before Connect, Httpurlconnection.connect (); 3.3 httpurlconnection connectivity issues

Here Getoutputstream will implicitly carry connect (that is, like calling the Connect () method above,//So do not invoke the above connect () in development). OutputStream OUTSTRM = Httpurlconnection.getoutputstream ();

3.4 httpurlconnection write data and send data problem

Object output stream objects are now constructed from the output stream object to achieve output-serializable objects. ObjectOutputStream OBJOUTPUTSTRM = new ObjectOutputStream (OUTSTRM);

Writes out the data to the object output stream, which is stored in the memory buffer Objoutputstrm.writeobject (new String ("I am test data");

Refreshes the object output stream, writes any bytes into the potential stream (some at ObjectOutputStream) Objoutputstm.flush ();

Closes the stream object. At this point, no data can be written to the object output stream, the previously written data exists in the memory buffer, and//When the getInputStream () function is invoked, the prepared HTTP request is formally sent to the server Objoutputstm.close ();

Call the getInputStream () function of the HttpURLConnection connection object,///Send the full HTTP request message encapsulated in the memory buffer to the server. InputStream INSTRM = Httpconn.getinputstream (); <=== Note that the code snippet that actually sent the request is here

//The top Httpconn.getinputstream () method has been invoked, the HTTP request has ended, and the output from the bottom to the object output stream is meaningless,//the object output stream does not call the close () method.  The following operation also does not write any data to the object output stream.  Therefore, to resend the data, you need to re-create the connection, reset the parameters, recreate the stream object, write the data again,//Resend the data (as to whether you need to re-examine these operations) Objoutputstm.writeobject (New String (""));  Httpconn.getinputstream (); 3.5 Summary

The Connect () function of httpurlconnection, in effect, simply establishes a TCP connection to the server and does not actually send HTTP requests. Either post or Get,http request is actually sent to the HttpURLConnection getInputStream () function.

l when sending a URL request by post, the order of the URL request parameters is the most important, and all configuration of the connection object (that stack of set functions) must be completed before the Connect () function executes.     For OutputStream, the write operation must be preceded by a InputStream read operation.     These orders are actually determined by the format of the HTTP request. If the InputStream read operation is preceded by a outputstream write operation, an exception is thrown: Java.net.ProtocolException:Cannot write output after reading input ....

L HTTP requests are actually made up of two parts, one is the HTTP header, all the configuration about this HTTP request is defined in the HTTP header, one is the text content. The Connect () function generates HTTP header information based on the configuration value of the HttpURLConnection object, so you must have all the configuration ready before calling the Connect function.

l followed by the HTTP header is the body of the HTTP request, the content of the body is written through the OutputStream stream, in fact OutputStream is not a network stream, at best is a string stream, to write something inside will not immediately send to the network, but save     In the memory buffer, the HTTP body is generated based on the input when the OutputStream stream is closed. At this point, all the HTTP requests are ready. When the getInputStream () function is invoked, the prepared HTTP request is officially sent to the server, and an input stream is returned to read the server's return information for this HTTP request. Because HTTP requests have been sent out at getInputStream (including HTTP headers and bodies), the getInputStream () It makes no sense to set the connection object after the function (modify the information on the HTTP header) or write OutputStream (modify the body), and performing these actions can cause an exception to occur. 4 servlet Development Guide

L for the Post type sent by the client

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.