Java uses Tomcat as the server's HTTP communication with Android

Source: Internet
Author: User

Write a program on the Android phone, the function is to complete a two-digit operation. This operation is done in Java background, the Android side uses the HTTP communication to pass the relevant parameters, the background after the calculation of the results back to the client.


Post the client part code

Click the button to package the parameters in JSON format to send to the background

Public void send (view v) {    string str1 = tv1.gettext (). ToString ();     string str2 = tv2.gettext (). ToString ();     if (Str1.equals ("")  | |  str2.equals ("")) {        toast.maketext ("") {MainActivity.this,  "Parameter cannot be empty!",  toast.length_long). Show ();        return;     }    final int a = integer.parseint (STR1);     final int b = integer.parseint (STR2);     new thread ( New runnable ()  {     @Override          Public void run ()  {             Jsonobject jsonobject = new jsonobject ();        &nbsP;    jsonarray jsonarray = new jsonarray ();         try {             Jsonobject.put ("Parm1", a +  "");             jsonobject.put ("Parm2", b +  "");             jsonarray.put (jsonobject);         } catch   (jsonexception e)  {             E.printstacktrace ();         }result = new httputils (). Getdatafromserver (Consant.url, jsonarray.tostring (),  method, a, b); Mhandler.sendemptymessage (0x0001);}}). Start ();}


I'm here to pass the parameters in two different ways.

One is Setrequestproperty (key, value);

The other is the usual output stream


/**

* Get relevant information from the server according to the phone number

* Get the specified content from the server-post

*

*/

Public string getdatafromserver (String svrurl, string paramstr, string type ,  int a, int b)  {try {    //  convert to specified format      byte[] requestdata = paramstr.getbytes ("UTF-8");     httpurlconnection  conn = null;    DataOutputStream outStream = null;     String MULTIPART_FORM_DATA =  "Multipart/form-data";     //   constructs an HTTP header for a POST request     url url = new url (Svrurl); //  Server address     conn =  (httpurlconnection)  url.openconnection ();     conn.setdoinput (TRUE); //  allow input     conn.setdooutput (true); //  Allow output     conn.setusecaches (false); //  do not use caches     Conn.setrequestmethod ("POST"); &nBsp;   conn.setrequestproperty ("Connection",  "keep-alive");     Conn.setrequestproperty ("Content-type",  multipart_form_data);     Conn.setrequestproperty ("Content-length",  long.tostring (requestdata.length));     Conn.setrequestproperty ("Method",  type);     conn.setrequestproperty ("One",  a  +  "");     conn.setrequestproperty (", b + ");     //  Request parameter Content,  get the connected Stream object that is output to the network     outStream = new  DataOutputStream (Conn.getoutputstream ());     outstream.write (requestData, 0,  Requestdata.length);     outstream.flush ();     outstream.close ();     bytearrayoutputstream outstream2 = new bytearrayoutputstream ();     int cah = conn.getresponsecode();    if  (cah != 200)  {         LOG.V ("Data",  "Server Response error code:"  + cah);         return   "0";     }else if (cah == 200) {         LOG.V ("Data",  "Server responded successfully:"  + cah);    }     Inputstream inputstream = conn.getinputstream ();     int len =  0;    byte[] data = new byte[1024];    while   (Len = inputstream.read (data)  != -1)  {         outstream2.write (Data, 0, len);    }     Outstream2.close ();     inputstream.close ();     string responsestr  = new string (outstreAm2.tobytearray ());     LOG.V ("Data",  "data = "  + responsestr);     return responsestr;}  catch  (exception e)  {    return  "";}}



Next look at Java Server side processing

A servlet was created in a Java Web project to receive data sent by the client

Because the client uses the Post method, we process the data in the servlet's post method

The client uses two ways to pass the parameters, and in the background we still take the parameters in two different ways

The first String method = Request.getheader ("method"). ToString ();

The second is the output stream to fetch the value.

Protected void dopost (httpservletrequest request, httpservletresponse response)   Throws servletexception, ioexception {    system.out.println ("--------- 00000000----");    int a;    int b;     int res = 0;    double res2 = 0;     String result;    string method = request.getheader ("Method"). toString ();     string str1 = request.getheader ("one"). ToString ();     string str2 = request.getheader ("both"). ToString ();     System.out.println (method +  "/"  + str1 +  "/"  + STR2);     try{        a = integer.parseint (STR1);         B = integer.parseint (STR2);     }catch (exception e) {         response.getwriter (). Append (E.getmessage ()  +  "");         return;    }    if (Method.equals ("+")) {         res = new utils (). Plus (a, b);     }else if (Method.equals ("-")) {        res = new  utils (). Minus (A, b),     }else if (Method.equals ("*")) {         res = new utils (). Multy (a, b);     }else  if (Method.equals ("/")) {        res2 = new utils () . Trad (a, b);     }    if (Method.equals ("/")) {         result = res2 +  "";    }else{         result = res +  "";    }         response.setcharacterencoding ("Utf-8");         Response.getwriter (). Append (result +  "");         getdata ( request);}
Public string getdata (httpservletrequest req) {    string result =  null;    try {        //input stream for package request         bufferedreader br = new bufferedreader (           new inputstreamreader ((ServletInputStream)  req.getinputstream (),  "Utf-8");         //buffer character          stringbuffer sb=new stringbuffer ("");         string line;        while ((line= Br.readline ())!=null) {            sb.append (line);         }        br.close ();// Close buffered Stream     &NBsp;   result=sb.tostring ();//convert to character          System.out.println ("result = "  + result);    } catch  ( exception e)  {        e.printstacktrace ();     }      return result;}

Also pay attention to the coding format problem, in the client with the Utf-8 encoding, we still have to use Utf-8 code on the server, otherwise there is a Chinese garbled phenomenon.


The IP address of the computer

The phone and the computer are in the same LAN, so you can access the intranet tomcat via IP

public static String URL = "Http://192.168.1.122:8080/MathTest/action?";


650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M00/72/74/wKiom1XkAlfREIQFAAc6rj7CCHw010.jpg "style=" float: none; "title=" Qq20150831151442.png "alt=" Wkiom1xkalfreiqfaac6rj7cchw010.jpg "/>

650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M01/72/71/wKioL1XkBHiDLwqTAAMG0tIg1T4286.jpg "style=" float: none; "title=" Qq20150831151503.png "alt=" Wkiol1xkbhidlwqtaamg0tig1t4286.jpg "/>

650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M01/72/74/wKiom1XkAlrB_gCzAAESPvPZKRA192.jpg "style=" float: none; "title=" app Bao screenshot 2015083101.png "alt=" Wkiom1xkalrb_gczaaespvpzkra192.jpg "/>


This article is from the "climb over the mountains to see the Sea" blog, please be sure to keep this source http://670176656.blog.51cto.com/4500575/1690163

Java uses Tomcat as the server's HTTP communication with Android

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.