HTTP POST mode to connect to the server, send data to the service side, and get data on the service side

Source: Internet
Author: User
Tags http post

The approximate process is: the client filled out the user name and password, on the service side to judge, verify the password if correct, then return login success, if the password is wrong, then return login failed

The client is a Java program with the following code:

Package Lgx.java.test;import Java.io.bytearrayoutputstream;import Java.io.ioexception;import java.io.InputStream; Import Java.io.outputstream;import Java.io.unsupportedencodingexception;import Java.net.httpurlconnection;import Java.net.malformedurlexception;import Java.net.url;import Java.net.urlencoder;import Java.util.HashMap;import Java.util.map;public class Httppostdemo {private static String PATH = "Http://192.168.1.48:8080/myapp2/LoginAction"; private static URL url;static {try {url = new URL (PATH);} catch (Malformedurlexception e) {e.printstacktrace ()}} /** * @param args */public static void main (string[] args) {map<string, string> param = new hashmap<string, Strin G> ();p aram.put ("username", "admin");p aram.put ("password", "123"); String result = Sendpostmessage (param, "utf-8"); SYSTEM.OUT.PRINTLN ("result is" + result);} private static String Sendpostmessage (map<string, string> param,string encode) {StringBuffer buffer = new Stringbuf Fer (); if (param! = null &&!paraM.isempty ()) {for (map.entry<string, string> entry:param.entrySet ()) {try {buffer.append ()). Append ("="). Append (Urlencoder.encode (Entry.getvalue (), encode)). Append ("&");} catch (Unsupportedencodingexception e) {e.printstacktrace ();}} try {httpurlconnection connection = (httpurlconnection) url.openconnection (); Connection.setrequestmethod ("POST"); Connection.setdoinput (True); Connection.setdooutput (true); byte[] data = buffer.tostring (). GetBytes ();// The type of the set request is the text type, the string inside is the default Connection.setrequestproperty ("Content-tyte", "application/x-www-form-urlencoded"); Connection.setrequestproperty ("Content-length", String.valueof (Data.length));//output stream, sending data to server server OutputStream OutputStream = Connection.getoutputstream (); outputstream.write (data); int requestcode = Connection.getresponsecode () if (Requestcode = = 200) {//input stream, get data from the server return streamtostring (Connection.getinputstream (), encode);}} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();}} Return "";} /** * will be a lostInto the stream into a specified encoded string * * @param inputstream input streams * @param encode encoded format * @return string */private static strings Streamtostring (INP Utstream InputStream, String encode) {Bytearrayoutputstream arrayoutputstream = new Bytearrayoutputstream (); byte[] Data = new byte[1024]; String result = ""; int len = 0;try {while (len = inputstream.read (data))! =-1) {arrayoutputstream.write (data, 0, Len);} result = new String (Arrayoutputstream.tobytearray (), encode);} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();} return result;}}

The server is the Tomcat service side, and in the project, the code of the Servlet,servlet is set up as follows:

Package Com.login.manager;import Java.io.ioexception;import Java.io.printwriter;import Javax.servlet.servletexception;import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import javax.servlet.http.httpservletresponse;/** * servlet implementation    Class Loginaction */public class Loginaction extends HttpServlet {private static final long serialversionuid = 1L;      /** * Default constructor. */Public Loginaction () {//TODO auto-generated constructor stub}/** * @see Httpservlet#doget (httpservletre Quest request, HttpServletResponse response) */protected void doget (HttpServletRequest request, HttpServletResponse Response) throws Servletexception, IOException {//TODO auto-generated Method Stubthis.dopost (request, response);} /** * @see Httpservlet#dopost (httpservletrequest request, httpservletresponse response) */protected void DoPost ( HttpServletRequest request, HttpServletResponse response) throws Servletexception, IOException {RESPONSE.SEtcontenttype ("Text/html;charset=utf-8"); Request.setcharacterencoding ("Utf-8"); Response.setcharacterencoding (" Utf-8 "); PrintWriter Out=response.getwriter (); String Username=request.getparameter ("username"); String password=request.getparameter ("password"); System.out.println (username+ "---->username"); System.out.println (password+ "----->password"), if (Username.equals ("admin") &&password.equals ("123")) { Out.print ("Longin is Success");} Else{out.print ("Login is Failed");}}}

Through these two codes, first open the server, and then run the client, if the user name and password are correct,

The client's console is:



The result is the Longin is success



The console on the server side is:


Admin---->username
123----->password


HTTP POST mode to connect to the server, send data to the service side, and get data on the service side

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.