Java--> Server Response (Servlet--doget&dopost)

Source: Internet
Author: User

--Servelet: for receiving requests (client, browser), responding, server-side, Java class

--Servletlogin--Java implementation of Web Project Server response

 PackageCom.dragon.java.servlet;Importjava.io.IOException;ImportJava.io.PrintWriter;Importjava.io.UnsupportedEncodingException;Importjavax.servlet.ServletException;ImportJavax.servlet.annotation.WebServlet;ImportJavax.servlet.http.HttpServlet;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;/*** Servlet Implementation class Servletlogin*/@WebServlet ("/servletlogin") Public classServletloginextendsHttpServlet {Private Static Final LongSerialversionuid = 1L; protected voiddoget (httpservletrequest request, httpservletresponse response)throwsservletexception, IOException {String user= Parse (request.getparameter ("User")); String pwd= Parse (Request.getparameter ("pwd")); System.out.println (User+ ":" +pwd); Response.setcontenttype ("Text/html;charset=utf-8"); PrintWriter writer=Response.getwriter (); Writer.println (User+ "Successful landing!"); //The server will automatically turn off the stream    }    protected voidDoPost (httpservletrequest request, httpservletresponse response)throwsservletexception, IOException {request.setcharacterencoding ("Utf-8");//solve only POST request garbled problemdoget (request, response); }     PublicString Parse (String msg)throwsunsupportedencodingexception {return NewString (Msg.getbytes ("iso8859-1"), "Utf-8"); }}

1, Doget Method:

--Httpurlconnectionutil Tool class

 PackageCom.dragon.java.urlbyget;Importjava.io.IOException;ImportJava.io.InputStream;Importjava.net.HttpURLConnection;ImportJava.net.URL; Public classHttpurlconnectionutil { Public Staticinputstream getinputstreambyget (String url) {Try{HttpURLConnection conn= (httpurlconnection)Newurl (url). OpenConnection (); Conn.setrequestmethod ("GET"); Conn.setreadtimeout (10000); Conn.setconnecttimeout (10000); //Use this method to set the HTTP request header//conn.addrequestproperty ("Accept", "...");            if(Conn.getresponsecode () = =HTTPURLCONNECTION.HTTP_OK) {                //Get the encoding//String contentType = Conn.getcontenttype (); //string string = Contenttype.split ("=") [1];InputStream InputStream=Conn.getinputstream (); returnInputStream; }        } Catch(IOException e) {e.printstacktrace (); }        return NULL; }}

--Test class

 PackageCom.dragon.java.urlbyget;ImportJava.io.BufferedReader;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.io.InputStreamReader; Public classTest { Public Static voidMain (string[] args) {InputStream inputstreambyget=httpurlconnectionutil. Getinputstreambyget ("Http://www.baidu.com"); Try{bufferedreader br=NewBufferedReader (NewInputStreamReader (Inputstreambyget,"GB2312")); String Line= "";  while(line = Br.readline ())! =NULL) {System.out.println (line); }        } Catch(IOException e) {e.printstacktrace (); }    }}

----------------------------------the evil dividing line------------------------------------

2. DoPost method

--Httpurlconnectionutil Tool class

 PackageCom.dragon.java.urlbypost;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.io.OutputStream;Importjava.net.HttpURLConnection;ImportJava.net.URL; Public classHttpurlconnectionutil {Private StaticString CharSet;  Public Staticinputstream getinputstreambypost (string url, string parms) {Try{HttpURLConnection conn= (httpurlconnection)Newurl (url). OpenConnection (); Conn.setreadtimeout (5000); Conn.setconnecttimeout (5000); Conn.setrequestmethod ("POST"); Conn.setdooutput (true); OutputStream OutputStream=Conn.getoutputstream ();            Outputstream.write (Parms.getbytes ()); if(Conn.getresponsecode () = =HTTPURLCONNECTION.HTTP_OK) {String ContentType=Conn.getcontenttype (); CharSet= Contenttype.split ("=") [1]; InputStream InputStream=Conn.getinputstream (); returnInputStream; }        } Catch(IOException e) {e.printstacktrace (); }        return NULL; }     Public StaticString Getcharset () {returnCharSet; }}

--Inputstreamutil the conversion class to stream to string

 PackageCom.dragon.java.urlbypost;ImportJava.io.BufferedReader;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.io.InputStreamReader; Public classInputstreamutil { Public Staticstring inputstreamtostring (InputStream is, string charset) {StringBuffer sb=NewStringBuffer (); Try(BufferedReader br =NewBufferedReader (NewInputStreamReader (IS, CharSet));) {            Char[] buffer =New Char[1024]; intLen =-1;  while(len = br.read (buffer))! =-1) {sb.append (buffer,0, Len); }            returnsb.tostring (); } Catch(IOException e) {e.printstacktrace (); }        return NULL; }}

--Test class

 Package Com.dragon.java.urlbypost; Import Java.io.InputStream;  Public class Test {    publicstaticvoid  main (String args[]) {

    The Chinese parameter in the URL needs to be encoded.
String user = Urlencoder.encode ("Zhang San", "Utf-8");
String pwd = urlencoder.encode ("Hello", "utf-8");
InputStream Inputstreambypost = Httpurlconnectionutil
. Getinputstreambypost (
"Http://192.168.2.11:8080/08-23/ServletLogin", "user="
+ user + "&pwd=" + pwd);

        System.out.println (inputstreamutil.inputstreamtostring (                inputstreambypost, Httpurlconnectionutil.getcharset ()));    }}

---> Note Import the Web project to the server and run ...

Java--> Server Response (Servlet--doget&dopost)

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.