简体   繁体   English

在android Application和java之间进行通信

[英]Communicate between android Application and java

Every body i am new in program world , I am getting a issue,My Request is related to Communication between Android tablet to Desktop PC using JAVA Code. 每个身体我是程序世界的新手,我遇到了一个问题,我的请求与使用JAVA Code的Android平板电脑与台式PC之间的通信有关。

   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 is my servlet code which is running in my local system server (Tomcat 6.0 ) here i am sending message through println and i want to reveive same message in my Android app which is running in another system. 上面的代码是我的servlet代码,它运行在我的本地系统服务器(Tomcat 6.0)这里我通过println发送消息,我想在我的Android应用程序中运行相同的消息,该应用程序在另一个系统中运行。 Now i am going to post my android code which is running on another system. 现在我要发布我在其他系统上运行的android代码。

          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 the activity is 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;
        for (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 and 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 is ip address of system where servlet code is running in my local system (Tomcat6.0 server which has port no 9999) .But it is not working for me.Both the system are in same wifi network Any help is really very appreciated. 这里192.68.0.2是系统的ip地址,其中servlet代码在我的本地系统中运行(Tomcat6.0服务器,端口号为9999)。但它对我不起作用。系统在同一个wifi网络中任何帮助都是真的非常感激。 Thanks in advance to all 在此先感谢所有人

try this i will work for you. 试试这个我会为你工作。 This is android code 这是android代码

         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 现在这是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 最后这是servlet代码

        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";
     }}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在Android活动和Java类之间进行交流 - Communicate between Android Activity and Java Class 在Java Servlet和普通Java应用程序之间进行通信的更好方法 - Better way to communicate between Java Servlet and a normal Java Application 如何在Java FX FXML应用程序中的Model和View之间进行通信? - How to communicate between the Model and View in a Java FX FXML application? 在 Windows 应用程序 (c#) 和 andriod 应用程序 (java) 之间进行连接和通信 - connect and communicate between Windows application (c#) and andriod apllication (java) 在Java中的类之间进行通信 - Communicate between classes in java 在 Android 应用程序和 JavaFX 应用程序之间进行通信的最佳方式 - Best way to communicate between an Android App and a JavaFX Application 在android中的2个类之间进行通信 - communicate between 2 classes in android 如何通过网络在Java和Android之间通信二进制和字符串数据? - How to communicate binary and string data between Java and Android over network? Android应用程序(客户端)可以使用套接字与Java Web服务器通信吗? - Can an android application(client) communicate with a java web server using sockets? 在两个 java 程序之间进行通信 - Communicate between two java programs
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM