Communicate between android Application and java

大兔子大兔子 提交于 2019-11-29 08:13:11

try this i will work for you. This is android code

         protected Integer doInBackground(String... arg0) {
       /** According with the new StrictGuard policy,  running long tasks on the Main UI thread is not possible
       So creating new thread to create and 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 the new thread we cannot update the main thread
       So updating the main thread outside the new thread */
       try {

       }catch (Exception e) {  
    error.setText(e.getMessage());    
          // e.printStackTrace();
       }
    return null;
      }   

Now this is another class for android

           public class SimpleHttpClient {
           public static    String result="";
 /** The time it takes for our client to timeout */
    public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds

    /** Single instance of our HttpClient */
    private static HttpClient mHttpClient;

    /**
     * Get our single instance of our HttpClient object.
     *
     * @return an HttpClient object with 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 an HTTP Post request to the specified url with the
     * specified parameters.
     *
     * @param url The web address to post the request to
     * @param postParameters The parameters to send via the request
     * @return The result of the 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");
        }

        finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    /**
     * Performs an HTTP GET request to the specified url.
     *
     * @param url The web address to post the request to
     * @return The result of the 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");
        }
        finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }}

And finally this is servlet code for 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();
           }
           finally {            
               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";
     }}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!