Java implementation put request

Source: Internet
Author: User

HTTP request has eight methods Get,post,head,put,delete,options,trace,connect,get and post are commonly used, due to project development needs, began to study the PUT request method, in fact, and the Post request method is similar. Here's a look at common request methods and less commonly used put methods.

First, the head method is the same as the Get method, except that the message body is not returned by the server response. In response to a head request, the HTTP header contains the same original information as the response message for a GET request. This method can be used to get the meta information that is implied in the request without transmitting the entity itself. It is also often used to test the validity, usability, and recent modification of hyperlinks.

Head requests are often overlooked, but can provide a lot of useful information, especially at limited speeds and bandwidth. The main features are as follows:

1, only the first request for resources;

2, check the validity of hyperlinks;

3, check whether the webpage is modified;

4, more for automatic search robot to obtain Web page logo information, access to RSS seed information, or transmission of security certification information, etc.

The GET request method is one of the most common HTTP requests and has the following features:

1, the default request method;

2, get requests are usually used to obtain information, so should be safe, idempotent.

3. The request data is represented on the URL and sent in the form of a name/value. There is a limit to the length of the request,

4, in IE and opera and other browsers will generate a URL cache. If you do not increase the redundant request parameters, the response returns data in the cache, resulting in inconsistent results.

5, Low security. is directly behind the request header and is clear.

Third, POST method

    • Labeling the resources that already exist;
    • Submit data
    • Expand the database with additional operations

The Post method has the following characteristics:

1, mainly used to submit data to the server, and get is mainly used to obtain;

2, the data encapsulated in the request, not the URL, so there is no length limit;

3, can not be cached, and get requests are cached, in IE and other browsers will directly return the cached data.

Iv. Put method

The Put method is typically used to send a request to the server, and if the URI does not exist, it asks the server to create the resource based on the request, and if so, the server accepts the request and modifies the original version of the URI resource. is commonly known as the upload resources.

http/1.1 does not define how a put request affects the state of the original server, and the put request must comply with the information transfer requirements.

Directly on the code:

  Public Static voidGetuploadinformation (String path,string obj)throwsIOException, jsonexception {//Create a connectionURL url =NewURL (path);        HttpURLConnection connection; StringBuffer Sbuffer=NULL; Try {        //Add Request Contentconnection=(HttpURLConnection) url.openconnection (); //setting HTTP connection PropertiesConnection.setdooutput (true);//http in the body, so it needs to be set to True, false by default;Connection.setdoinput (true);//sets whether to read in from HttpURLConnection, true by default;Connection.setrequestmethod ("PUT");//the ability to submit HTTP features such as GET, POST, DELETE, put, etc. , as needed//connection.setusecaches (false);//set the cache, note that the set request method is post cannot be cached//connection.setinstancefollowredirects (true);Connection.setrequestproperty ("Host", "*******");//set the requested server URL, domain name, such as ***.**.***.***Connection.setrequestproperty ("Content-type", "Application/json");//set the request format JSON, or you can set the XML formatConnection.setrequestproperty ("Accept-charset", "utf-8");//Setting the encoding languageConnection.setrequestproperty ("X-auth-token", "Token");//set the token for the requestConnection.setrequestproperty ("Connection", "keep-alive");//to set the status of a connectionConnection.setrequestproperty ("transfer-encoding", "chunked");//Set transfer encodingConnection.setrequestproperty ("Content-length", obj.tostring (). GetBytes (). Length + "");//set the length of a file requestConnection.setreadtimeout (10000);//set the Read timeout timeConnection.setconnecttimeout (10000);//Setting the connection time-out periodConnection.connect (); OutputStream out= Connection.getoutputstream ();//writes out the data to the object output stream, which is stored in the memory bufferOut.write (Obj.tostring (). GetBytes ());//Out.write (New String ("Test Data"). GetBytes ()); //refreshes the object output stream, writes any bytes to the potential streamOut.flush (); //closes the stream object, at which point no data can be written to the object output stream and the previously written data exists in the memory bufferOut.close (); //Read Response            if(Connection.getresponsecode () ==200)            {                //get an input stream from the serverInputStreamReader InputStream =NewInputStreamReader (Connection.getinputstream ());//Call the getInputStream () function of the HttpURLConnection connection object to send a complete HTTP request message encapsulated in the memory buffer to the server. BufferedReader reader =NewBufferedReader (InputStream);                String lines; Sbuffer=NewStringBuffer ("");  while((lines = Reader.readline ())! =NULL) {lines=NewString (Lines.getbytes (), "Utf-8");                Sbuffer.append (lines);                 } reader.close (); }Else{log.i (TAG,"Request Failed" +Connection.getresponsecode ()); }            //Disconnect ConnectionConnection.disconnect (); } Catch(IOException e) {e.printstacktrace (); }}json Data Public  Staticstring Queryloginbody (string type,string userid,string checksum) {string JSON= "{\" type\ ": \" "+type+" \ "," + "\" jid\ ": \" "+userid+" \ "," + "\" checksum\ ": \" "+checksum+" \ "}"; returnJSON;} Call the method, enter the parameters to pass in, and put the JSON data directly in it. String JSON=apputils.queryloginbody ("Login", "usr", "123132"); Apputils.getuploadinformation ("Http://www.xxx.com", JSON);

Java implementation put request

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.