Standing on the shoulders of giants, gradually progress.
Original link: http://www.blogjava.net/supercrsky/articles/247449.html
For the JDK in the URLConnection connection servlet problem, although the Internet has been involved, but only to explain a certain or a few problems, is the way to solve the FAQ, and relatively fragmented, now on the use of this class I in the project experience to do the following summary:
1:> the category of the URL request:
Divided into two categories, get and post requests. The difference between the two is:
A:) Get request can get a static page, or you can put the parameters behind the URL string, passed to the servlet,
B: The difference between post and get is that the post parameter is not placed inside the URL string, but is placed inside the body of the HTTP request.
2:> URLConnection Object problem:
URLConnection object, the following code example:
The following index.jsp is mapped from <servlet-mapping> to
A servlet (Com.quantanetwork.getClientDataServlet)
The servlet's attention points are mentioned below
1URL url =NewURL ("http://localhost:8080/TestHttpURLConnectionPro/index.jsp"); 2 3URLConnection rulconnection = Url.openconnection ();//the URLConnection object here is actually based on the URL's4 //the URLConnection class that the request protocol (here is HTTP) generates5 //sub-class httpurlconnection, so it is best to convert it6 //is an object of type httpurlconnection for use with the7 //httpurlconnection more APIs. The following:8 9HttpURLConnection httpurlconnection = (httpurlconnection) rulconnection;
3:> HttpURLConnection Object parameter problems
1 //set whether to output to httpurlconnection, because this is a POST request, the parameters to be placed in the2 //http in the body, so it needs to be set to True, false by default;3Httpurlconnection.setdooutput (true); 4 5 //sets whether to read in from HttpURLConnection, true by default;6Httpurlconnection.setdoinput (true); 7 8 //The Post request cannot use the cache9Httpurlconnection.setusecaches (false); Ten One //sets the content type of the transfer to be a serializable Java object A //(if this item is not set, the java.io.EOFException may be thrown when the serialized object is passed, when the Web service defaults to this type) -Httpurlconnection.setrequestproperty ("Content-type", "Application/x-java-serialized-object"); - the //The method for setting the request is "POST", and the default is get -Httpurlconnection.setrequestmethod ("POST"); - - //connection, from the 2nd above url.openconnection () the configuration must be completed before connect, +Httpurlconnection.connect ();
4:> HttpURLConnection Connectivity Issues:
1 // 2//3
5:> httpurlconnection Write data and send data problems:
1 //The object output stream object is now built from the output stream object to implement the output serializable object. 2ObjectOutputStream OBJOUTPUTSTRM =NewObjectOutputStream (OUTSTRM);3 4 //writes out the data to the object output stream, which is stored in the memory buffer5Objoutputstrm.writeobject (NewString ("I am the test data")); 6 7 //refreshes the object output stream and writes any bytes to the potential stream (ObjectOutputStream)8 Objoutputstm.flush ();9 Ten //closes the Stream object. At this point, no data can be written to the object output stream, and the previously written data exists in the memory buffer. One //The prepared HTTP request is formally sent to the server when the getInputStream () function is called below A objoutputstm.close (); - - //Call the getInputStream () function of the HttpURLConnection connection object, the //A complete HTTP request message encapsulated in the memory buffer is sent to the server. -InputStream INSTRM = Httpconn.getinputstream ();//<=== Note that the code snippet that actually sent the request is here - - //the Httpconn.getinputstream () method above has been called, the HTTP request has ended, and the output of the bottom-to-object output stream is meaningless. + //Even if the object output stream does not call the close () method, the bottom operation does not write any data to the object output stream. - //Therefore, you need to re-create the connection, reset the parameters, recreate the stream object, re-write the data , + //Resend the data (as to whether you need to re-examine these operations again) AObjoutputstm.writeobject (NewString ("")); atHttpconn.getinputstream ();
Summary: A:) The Connect () function of httpurlconnection actually only establishes a TCP connection to the server and does not actually send an HTTP request.
Either the post or the Get,http request is actually sent out until the httpurlconnection getInputStream () function.
B:) When sending a URL request by post, the URL request parameters are set in the order of the most heavy,
All configuration of the connection object (that heap of set functions)
Must be completed before the Connect () function executes. The write operation to OutputStream must be preceded by the InputStream read operation.
These orders are actually determined by the format of the HTTP request.
If the InputStream read operation precedes the write operation of OutputStream, an exception is thrown:
Java.net.ProtocolException:Cannot write output after reading input ....
C:) The HTTP request actually consists of two parts,
One is the HTTP header, and 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 values of the HttpURLConnection object, so before calling the Connect function, the
You have to get all the configurations ready.
D:) After the HTTP header is followed by 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 a string stream, and what is written into it is not immediately sent to the network,
Instead, it exists in the memory buffer, and the HTTP body is generated based on what is entered when the OutputStream stream is closed.
At this point, the HTTP request is ready for everything. When the getInputStream () function is called, the prepared HTTP request is
is officially sent to the server, and then an input stream is returned to read the server's return information for this HTTP request. Because the HTTP
The request was sent out at getInputStream (including the HTTP header and body), so the getInputStream () function
The connection object is then set (modification of the HTTP header information) or written to OutputStream (the body is modified)
is meaningless, performing these operations can cause an exception to occur.
6:> servlet Side Development Note:
A:) For the HTTP request of the Post type sent by the client, the servlet must implement the Dopost method instead of the Doget method.
B:) Use the HttpServletRequest getInputStream () method to obtain InputStream objects, such as:
InputStream instream = Httprequest.getinputstream ();
Now call Instream.available () (the method used to "return this input to the stream" where a method call can be unblocked
The estimated number of bytes read (or skipped) from this input stream is always reversed back to 0. An attempt was made to allocate a buffer using the return value of this method.
It is incorrect to save all the data in this stream. So, the solution now is
This end of the servlet is implemented as follows:
InputStream instream = Httprequest.getinputstream ();
ObjectInputStream objinstream = new ObjectInputStream (instream);
Object obj = Objinstream.readobject ();
Do the follow-up processing
。。。。。。
。。。 。。。
The client, regardless of whether the actual data is sent or not, is written to an object (which is afraid of this object), such as:
ObjectOutputStream OBJOUTPUTSTRM = new ObjectOutputStream (OUTSTRM);
Objoutputstrm.writeobject (New String ("")); Send an empty data here
You can even send a null object, and the service end is taken and then processed.
Objoutputstrm.writeobject (NULL);
Objoutputstrm.flush ();
Objoutputstrm.close ();
Note: When you create an object output stream ObjectOutputStream, the input stream that is taken from HttpServletRequest
(i.e., OUTSTRM in new ObjectOutputStream (OUTSTRM) is wrapped in a bufferedoutputstream flow,
Must have Objoutputstrm.flush (); This sentence, in order to brush the flow information into the buffered output stream.
ObjectOutputStream OBJOUTPUTSTRM = new ObjectOutputStream (new Bufferedoutputstream (OUTSTRM));
Objoutputstrm.writeobject (NULL);
Objoutputstrm.flush (); <====== must have it here.
Objoutputstrm.close ();
HttpURLConnection is based on the HTTP protocol, and its underlying is implemented via socket communication. If you do not set a time-out (timeout), in the case of a network exception, it may cause the program to zombie without continuing to execute. The corresponding timeout can be set by the following two statements:
System.setproperty ("Sun.net.client.defaultConnectTimeout", time-out number of milliseconds string);
System.setproperty ("Sun.net.client.defaultReadTimeout", time-out number of milliseconds string);
Where: Sun.net.client.defaultConnectTimeout: Time-out for connecting the host (in milliseconds)
Sun.net.client.defaultReadTimeout: timeout (in milliseconds) to read data from the host
For example:
System.setproperty ("Sun.net.client.defaultConnectTimeout", "30000");
System.setproperty ("Sun.net.client.defaultReadTime
In Java, you can use HttpURLConnection to request Web resources.
The HttpURLConnection object cannot be constructed directly and needs to be url.openconnection () to obtain the HttpURLConnection object, as shown in the example code:
1 String szurl = "http://www.ee2ee.com/"; 2 New URL (szurl); 3
It is important to note that The author in the JDK1.4.2 environment, found that in the case of setting up Defaultreadtimeout, if a network timeout occurs, HttpURLConnection will automatically resubmit the request, a request call, the request server two times the problem (trouble). I think this is a bug in JDK1.4.2. In JDK1.5.0, this issue has been resolved and there is no automatic re-occurrence. Out "," 3000
1. Use WebView do not forget to add <uses-permission android:name= "Android.permission.INTERNET" ></uses-permission>
Although WebView also inherits from view, its package name is Ndroid.webkit
2. websettings : The WebView component has an auxiliary class called WebSettings, which manages the setting state of the WebView, which can be obtained through the Webview.getsettings () method.
Get the WebSettings object, set the parameters that support JavaScript
Webview.getsettings (). Setjavascriptenabled (True);
Settings can support zooming
Webview.getsettings (). Setsupportzoom (True);
Set default scaling mode size is far
Webview.getsettings (). Setdefaultzoom (WebSettings.ZoomDensity.FAR);
Set the zoom tool to appear
Webview.getsettings (). Setbuiltinzoomcontrols (True);
3
WebView makes it easy to invoke resources such as local Web pages and pictures under the assets directory, to allow WebView to load the Assets,android SDK from the APK file with a schema prefixed with file:///android_asset/. WebView encountered such a schema, go to the current package in the assets directory to find content, such as:
Webview.loadurl (file:///android_asset/html/test1.html);
4.WebChromeClient and Webviewclient
Auxiliary objects associated with WebView, in addition to the websettings are webchromeclient and webviewclient.
Webviewclient primarily helps WebView handle various notifications, request events, such as:
Onloadresource
Onpagestart
Onpagefinish
Onreceiveerror
Onreceivedhttpauthrequest
Webchromeclient main Auxiliary webview Processing JavaScript dialog box, website icon, website title, loading progress, etc., such as:
Onclosewindow (Close WebView)
Oncreatewindow ()
Onjsalert (WebView on alert is invalid and requires custom Webchromeclient processing popup)
Onjsprompt
Onjsconfirm
Onprogresschanged
Onreceivedicon
Onreceivedtitle
If only used to deal with some HTML page content, only with webviewclient on the line, if you need more rich processing effect, such as JS, progress bar, it is necessary to use the webchromeclient.
5.WebView Call JS function, and get the return value, in Android must register to a Java object in WebView, and after the JS function executes, through the object corresponding to the name of the method to call its return value. But this requires that every JS function in the HTML that will be actively invoked by the Java code must know beforehand that the object is registered, and that its callback function is known.
Here the two fixed JS function is added to the HTML, to assist the call of Java code and get the return value, so that other JS function does not have to write the registration object Callback code: (1) in WebView HTML: <script>//must be added to the function
function Calljs (Param,tag)
{
var result=getcallresult (param);
Javahome.handlejsresult (Result,tag);
}//functions that must be added in
function Getcallresult (param)
{
return param;
}//This is an arbitrary function
function fun1 (param)
{
var a=1+9;
Return param+ "--" +a;
}
</script> (2) in the Java class//To register this class object with the name Javahome to Webviewwebview.addjavascriptinterface (this, "javahome");// Get click-to-place content in Ontouchlistener
Webview.setontouchlistener (New View.ontouchlistener ()
{
public boolean OnTouch (View V, motionevent event)
{
if (Event.getaction () ==motionevent.action_up)
{
LOG.I ("Raw X, Y", event.getrawx () + "" +event.getrawy ());
LOG.I ("x, Y", event.getx () + "" +event.gety ());
String Str=string.format ("Elementfromviewportpoint (%f,%f). TagName", Event.getx (), event.gety ());
Calljs (str, "Tag21");
}
return false;
}
});
Encapsulates a layer, which is used as a flag for each invocation so that the callback identifies
public void Calljs (String jsfunparam,string tag)
{
String Str=string.format ("Javascript:calljs (%s, '%s ')", Jsfunparam,tag);
LOG.I ("Loadurl", str);
Webview.loadurl (str);
}
In this method, the return value of the JS function call is received.
public void Handlejsresult (String str,string tag)
{
LOG.I ("Handlejsresult" +tag, str);
}
"Go" Personally think, this is the most detailed android------HttpURLConnection class usage. Some of the textbooks did not talk about it, it talked about