Communicate between android Application and java -


every body new in program world , getting issue,my request related communication between android tablet desktop pc using java code.

   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;     public class helloworldservlet extends httpservlet {    private static final long serialversionuid = 1l;      public helloworldservlet() {     super();     }  protected void doget(httpservletrequest request,         httpservletresponse response) throws servletexception, ioexception {     printwriter out = response.getwriter();     out.println("hello android !!!!"); } } 

above code servlet code running in local system server (tomcat 6.0 ) here sending message through println , want reveive same message in android app running in system. going post android code running on system.

          import java.io.bufferedreader;           import java.io.ioexception;           import java.io.inputstream;           import java.io.inputstreamreader;           import java.net.httpurlconnection;           import java.net.url;           import java.net.urlconnection;           import android.app.activity;           import android.os.asynctask;           import android.os.bundle;           import android.view.view;           import android.view.view.onclicklistener;           import android.widget.button;           import android.widget.textview;       public class httpgetservletactivity3 extends activity implements     onclicklistener { button button; textview outputtext;  public static final string url =     "http://192.168.0.2:9999/httpgetservlet/helloworldservlet";  /** called when activity first created. */ @override public void oncreate(bundle savedinstancestate) {     super.oncreate(savedinstancestate);     setcontentview(r.layout.main);      findviewsbyid();      button.setonclicklistener(this); }  private void findviewsbyid() {     button = (button) findviewbyid(r.id.button);     outputtext = (textview) findviewbyid(r.id.outputtxt); }  public void onclick(view view) {     getxmltask task = new getxmltask();     task.execute(new string[] { url }); }  private class getxmltask extends asynctask<string, void, string> {     @override     protected string doinbackground(string... urls) {         string output = null;         (string url : urls) {             output = getoutputfromurl(url);         }         return output;     }      private string getoutputfromurl(string url) {         stringbuffer output = new stringbuffer("");         try {             inputstream stream = gethttpconnection(url);             bufferedreader buffer = new bufferedreader(                     new inputstreamreader(stream));             string s = "";             while ((s = buffer.readline()) != null)                 output.append(s);         } catch (ioexception e1) {             e1.printstacktrace();         }         return output.tostring();     }      // makes httpurlconnection , returns inputstream     private inputstream gethttpconnection(string urlstring)             throws ioexception {         inputstream stream = null;         url url = new url(urlstring);         urlconnection connection = url.openconnection();          try {             httpurlconnection httpconnection = (httpurlconnection) connection;             httpconnection.setrequestmethod("get");             httpconnection.connect();              if (httpconnection.getresponsecode() == httpurlconnection.http_ok) {                 stream = httpconnection.getinputstream();             }         } catch (exception ex) {             ex.printstacktrace();         }         return stream;     }      @override     protected void onpostexecute(string output) {         outputtext.settext(output);     } }} 

here 192.68.0.2 ip address of system servlet code running in local system (tomcat6.0 server has port no 9999) .but not working me.both system in same wifi network appreciated. in advance all

try work you. android code

         protected integer doinbackground(string... arg0) {        /** according new strictguard policy,  running long tasks on main ui thread not possible        creating new thread create , execute http operations */        new thread(new runnable() {          @override          public void run() {          arraylist<namevaluepair> postparameters = new arraylist<namevaluepair>();          postparameters.add(new basicnamevaluepair("username",un.gettext().tostring()));          postparameters.add(new basicnamevaluepair("password",pw.gettext().tostring()));           string response = null;          try {           response = simplehttpclient.executehttppost("http://xxx.168.1.x:5555/loginservlet/loginservlet.do", postparameters);            res = response.tostring();            system.out.println("response :"+res);            } catch (exception e) {                  // e.printstacktrace();           errormsg = e.getmessage();            }           }         }).start();           /** inside new thread cannot update main thread        updating main thread outside new thread */        try {         }catch (exception e) {       error.settext(e.getmessage());               // e.printstacktrace();        }     return null;       }    

now class android

           public class simplehttpclient {            public static    string result="";  /** time takes our client timeout */     public static final int http_timeout = 30 * 1000; // milliseconds      /** single instance of our httpclient */     private static httpclient mhttpclient;      /**      * our single instance of our httpclient object.      *      * @return httpclient object connection parameters set      */     private static httpclient gethttpclient() {         if (mhttpclient == null) {             mhttpclient = new defaulthttpclient();             final httpparams params = mhttpclient.getparams();             httpconnectionparams.setconnectiontimeout(params, http_timeout);             httpconnectionparams.setsotimeout(params, http_timeout);             connmanagerparams.settimeout(params, http_timeout);         }         return mhttpclient;     }      /**      * performs http post request specified url      * specified parameters.      *      * @param url web address post request      * @param postparameters parameters send via request      * @return result of request      * @throws exception      */     public static string executehttppost(string url, arraylist<namevaluepair> postparameters) throws exception {         bufferedreader in = null;         try {             httpclient client = gethttpclient();             httppost request = new httppost(url);             urlencodedformentity formentity = new urlencodedformentity(postparameters);             request.setentity(formentity);            // string str1=  request.setentity(formentity);             system.out.println("actual request"+formentity);             httpresponse response = client.execute(request);             system.out.println("response in class"+response);             in = new bufferedreader(new inputstreamreader(response.getentity().getcontent()));              stringbuffer sb = new stringbuffer("");             string line = "";             string nl = system.getproperty("line.separator");             while ((line = in.readline()) != null) {                 sb.append(line + nl);             }             in.close();               result = sb.tostring();         }catch(exception e){             e.printstacktrace();             system.out.println("catch");         }          {             if (in != null) {                 try {                     in.close();                 } catch (ioexception e) {                     e.printstacktrace();                 }             }         }         return result;     }      /**      * performs http request specified url.      *      * @param url web address post request      * @return result of request      * @throws exception      */     public static string executehttpget(string url) throws exception {         string result="";         bufferedreader in = null;         try {             httpclient client = gethttpclient();             httpget request = new httpget();             request.seturi(new uri(url));             httpresponse response = client.execute(request);             in = new bufferedreader(new inputstreamreader(response.getentity().getcontent()));              stringbuffer sb = new stringbuffer("");             string line = "";             string nl = system.getproperty("line.separator");             while ((line = in.readline()) != null) {                 sb.append(line + nl);             }             in.close();               result = sb.tostring();          }         catch(exception e){             e.printstacktrace();             system.out.println("catch2");         }         {             if (in != null) {                 try {                     in.close();                 } catch (ioexception e) {                     e.printstacktrace();                 }             }         }         return result;     }} 

and servlet code you

        public class loginservlet extends httpservlet {     protected void service(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {             response.setcontenttype("text/html;charset=utf-8");            printwriter out = response.getwriter();            try {            string un,pw;            un=request.getparameter("username");            pw=request.getparameter("password");            system.out.println("username :"+un);            system.out.println("password :"+pw);            if(un.equals("") || pw.equals("") ){                    out.print("null");            }            else if(un.equalsignorecase("hello") && pw.equals("world"))            {                      out.print("success");             }             else{                    out.print("failed");            }            system.out.println("after :");            request.getattribute("user"+un);            request.getattribute("pass"+pw);            requestdispatcher rd=request.getrequestdispatcher("home.jsp");             rd.forward(request, response);             }catch(exception e){                    system.out.println("inside exception");                    e.printstacktrace();            }            {                            out.close();            }        }      @override        protected void doget(httpservletrequest request, httpservletresponse response)                throws servletexception, ioexception {            service(request, response);        }      @override        protected void dopost(httpservletrequest request, httpservletresponse response)                throws servletexception, ioexception {              service(request, response);        }      @override        public string getservletinfo() {            return "short description";      }} 

Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -