Java Post data request and receive __java

Source: Internet
Author: User
Tags readline ascii hex values stringbuffer

These two days in the HTTP server to do the request operation, the client post data to the server, the server through the Request.getparameter () to request, unable to read the data, search for the discovery is because the set to Text/plain mode is not read data

   Urlconn.setrequestproperty ("Content-type", "Text/plain; Charset=utf-8");
If set to the following way, the data can be read by Request.getparameter ()

   Urlconn.setrequestproperty ("Content-type", "application/x-www-form-urlencoded");

Three kinds of coding of enctype

The Enctype property in form forms can be used to control how the form data is encoded before it is sent to the server, where all characters are encoded (spaces are converted to "+" plus signs, and special symbols are converted to ASCII HEX values). The default is application/x-www-form-urlencoded.

Multipart/form-data used to send binary files, two other types cannot be used to send files

Text/plain is used to send plain text content, not to encode special characters, generally used for email and the like.

The difference between application/x-www-form-urlencoded and Text/plain is simply to send HTML content, one to send plain text content application/x-www-form-urlencoded Encode all characters before sending (default) Multipart/form-data not character encoding. You must use this value when you use a form that contains file upload controls. Text/plain spaces are converted to "+" plus, but no special characters are encoded.
When you define enctype as application/x-www-form-urlencoded, you receive data by using the following methods

       Request.getparameter (name of parameter);

When you define enctype as Text/plain, you receive data by using the following methods

        Receive request data
        BufferedReader reader = Request.getreader ();
        char[] buf = new char[512];
        int len = 0;
        StringBuffer contentbuffer = new StringBuffer ();
        while (len = Reader.read (buf))!=-1) {
            contentbuffer.append (buf, 0, Len);
        }
String content = contentbuffer.tostring ();
if (content = = null) {
content = "";
}
Post and get

Post and get can be transferred by key-value pairs, and the server will request data through Request.getparameter.
Client post data to server, service side receive processing

public class URLConnection {          @SuppressWarnings ("finally")      public static Boolean response (String url,string content) {        string line  &nbsp ;
     = "";
        string message        = "";
        string returndata   = "";
        boolean poststate     = false;
        bufferedreader bufferedreader = null;                  try {      
     url urlobject = new URL (URL);             httpurlconnection urlconn = (httpurlconnection)
Urlobject.openconnection ();
            urlconn.setdooutput (true);             /* Settings Disable cache *              Urlconn.setrequestproperty ("Pragma:", "No-cache");             
     urlconn.setrequestproperty ("Cache-control", "No-cache");            /* Maintain long connection * *              urlconn.setrequestproperty ("Connection", "keep-alive");              /* Setting Character Set */    
        urlconn.setrequestproperty ("Charset", "UTF-8");            /* Set output format for json*/             urlconn.setrequestproperty ("Content-type", "application/json;charset=
Utf-8 ");             /* Set use post to send * *             urlconn.setrequestmethod (" POST ");                          /* Settings do not use cache/          
  Urlconn.setusecaches (FALSE);            /* Set allowable output */             Urlconn.setdooutput (TRUE);              /* Set allowable input */             Urlconn.setdoinput (True);                           
Urlconn.connect ();                       & nbsp;  OutputStreamWriter outstreamwriter = new OutputStreamWriter (Urlconn.getoutputstream (), "UTF-8");
            outstreamwriter.write (content);
            Outstreamwriter.flush ();
            Outstreamwriter.close ();                          /* If post failure/            if ( Urlconn.getresponsecode ()!=) {             
   returndata = "{\" jsonstrstatus\ ": 0,\" processresults\ ": []}";                 message = "Send post failed.
"+" code= "+urlconn.getresponsecode () +", "+" failure message: "+ urlconn.getresponsemessage ();                //define BufferedReader input stream to read URL response                  InputStream Errorstream = 
Urlconn.geterrorstream ();                                   if (errorstream!= null)                  {                     InputStreamReader
InputStreamReader = new InputStreamReader (Errorstream, "utf-8");                      BufferedReader = new BufferedReader (InputStreamReader);
                                     while (line = Bufferedreader.readline ())!= null) {                           message + + line;                         }                  
            Inputstreamreader.close ();                }    
             Errorstream.close ();                 System.out.println (" Send failed. The error message is: "+message";                                }else{                 /* Send successful return send successfully status/          
     poststate = true;                                   //defines bufferedreader input stream to read URL response                  InputStream InputStream = Urlconn.getinputstream ();                                     InputStreamReader
InputStreamReader = new InputStreamReader (InputStream, "utf-8");                 BufferedReader = new BufferedReader (InputStreamReader);                               while (line = Bufferedreader.readline ())!= null) {                       message + = line;                  }                       
   returndata = message;
                Inputstream.close ();                
Inputstreamreader.close ();                                   System.out.println ("Send post successfully. Back to: "+ message";                                     }        &nbsp} catch (Exception e) {            
E.printstacktrace ();         }finally{            try {                     if ( BufferedReader!= null) {                      bufferedreader.close ();                 &NBSp }                               } catch (IOException ex) {                   Ex.printstacktrace ();              }           &
nbsp;           return poststate;        &nbsp}    &nbsp}          /* Read request data */& nbsp;   public static String getrequestdata (HttpServletRequest request) throws ioexception{  
     bufferedreader reader = Request.getreader ();
        char[] buf = new char[512];
        int len = 0;         stringbuffer contentbuffer = new STringbuffer ();         while (len = Reader.read (buf))!=-1) {        &nbs
p;   contentbuffer.append (buf, 0, Len);         }                  
String content = contentbuffer.tostring ();                  if (content = = null) {    &
nbsp;       content = "";         }                  
return content;    &nbsp}}




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.