Java connection to remote server URLConnection

Source: Internet
Author: User
Tags ftp site

URLs in the network (Uniform Resource Locator) are abbreviations for Uniform Resource locators. It represents the address of a resource on the Internet. Through the URL we can access various network resources on the Internet, such as the most common www,ftp site. URLs can be thought of as "pointers" to Internet resources, which can be used to obtain information about Internet resources, including information about the InputStream object acquiring the URL, and a connection urlconnection to the remote object referenced by the URL. The URLConnection object can send requests and read the URL's resources to the URL represented. Typically, creating a connection to a URL requires the following steps:

    1. Create the URL object and obtain the URLConnection object by calling the OpenConnection method;

    2. Set URLConnection parameters and normal request properties;

    3. Send a request to a remote resource;

    4. When a remote resource becomes available, the program can access the remote resource's header field and read the information returned by the remote resource through the input stream.

package com.wa.axis2.test;import java.io.bufferedinputstream;import java.io.bufferedreader; import java.io.file;import java.io.fileinputstream;import java.io.ioexception;import  java.io.inputstream;import java.io.inputstreamreader;import java.net.httpurlconnection;import  java.net.url;import java.net.urlconnection;import org.junit.test;public class upload  {     @Testpublic  void upload () {try {url url=new url ("HTTP/ Localhost:8090/audit/uploadfilehttpservlet?name=hello "); httpurlconnection urlconnection= (HttpURLConnection)  url.openconnection (); UrlConnection.setDoInput ( true); Urlconnection.setdooutput (true); Urlconnection.setusecaches (false); Urlconnection.setrequestproperty (" Content-type ", " Application/octet-stream ") Urlconnection.setrequestproperty (" ReturnFileUploadPath ",  "D://test//a.txt"); File file=new file ("E:\\aa.txt"); int len=0;byte[] by=new byte[1024*1024]; Bufferedinputstream bi=new bufferedinputstream (New fileinputstream (file)); while ((Len=bi.read (by )) (!=-1) {urlconnection.getoutputstream (). write (By, 0, len);}   Get response status Int responsecode = urlconnection.getresponsecode ();if  ( Httpurlconnection.http_ok == responsecode)  {//  Process data System.out.println ("") when the response is correct; System.out.println ("Http response ok ...");//  process the response stream and must be consistent with the encoding of the server response stream output stringbuffer  Responsebuffer = new stringbuffer (); string readline; Bufferedreader responsereader = new bufferedreader (New inputstreamreader ( Urlconnection.getinputstream (), "Utf-8"));while  ((Readline = responsereader.readline ())  !=  null)  {responsebuffer.append (readLine). Append ("n");} System.out.println ("Http response:"  + responsebuffer); Responsereader.close ();} Bi.close ();}  catch  (exception e)  {e.printstacKtrace ();}}} 


The server servlet code is as follows:

Protected void dopost (Httpservletrequest request,httpservletresponse response)  throws  ServletException, IOException {    String name =  Request.getparameter ("name");         string path= Request.getheader ("Returnfileuploadpath");         system.out.println ( path);         file file=new file (path);         if (!file.exists ()) {         File.getparentfile (). Mkdirs ();        }         //read sent files and save to local         BufferedOutputStream  Bo=new bufferedoutputstream (New fileoutputstream (file));         int len=0;        byte[] by=new byte[1024*1024];        while (len =request.getinputstream (). Read (by)!=-1) {        bo.write (by, 0,  len);        }         Bo.flush ();         bo.close ();         response.setcontenttype ("Text/plain; charset=utf-8");         response.setcharacterencoding ("UTF-8");         Response.getwriter (). Write ("it is ok!");}



precautions;

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 order of the URL request parameters is the most important, and all configuration of the connection object (that heap of set functions) must be done 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, all the configuration about this HTTP request is defined in the HTTP header, so the server needs to use GetHeader to obtain parameters, Request.getheader ("Returnfileuploadpath");

One is the text content.

The Connect () function generates HTTP header information based on the configuration values of the HttpURLConnection object, so all configurations must be ready before calling the Connect function.

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 formally sent to the server, and an input stream is returned to read the server's return information for this HTTP request.  Since the HTTP request was sent out at getInputStream (including the HTTP header and the body), the getInputStream () function It makes no sense to set the connection object later (modify the information of the HTTP header) or write OutputStream (modify the body), which causes the exception to occur.


This article is from the "BREEZEWINDLW" blog, make sure to keep this source http://breezewindlw.blog.51cto.com/6504579/1633493

Java connection to remote server URLConnection

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.