Android应用和Java之间的沟通Android、Java

2023-09-04 09:55:10 作者:陌生的你我最熟悉不过

每一个身体我是新方案的世界里,我得到一个问题,我的要求是用JAVA code与通信相关的Andr​​oid平板,以台式电脑之间。

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.

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

以上code是它在我的本地系统中的服务器上运行(的Tomcat 6.0)我在这里过的println发送消息我的servlet code,我想reveive相同的消息,其中在另​​一个运行我的Andr​​oid应用系统。现在我要发布它在另一个系统上运行我的Andr​​oid code。

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. Now i am going to post my android code which is running on another 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 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);
    }
}}

下面192.68.0.2是系统所在的servlet code是我的本地系统中运行(其中有端口号9999 Tomcat6.0服务器),而这是不工作的me.Both系统都在同一个IP地址wifi网络任何帮助真的非常AP preciated。在此先感谢所有

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. Thanks in advance to all

推荐答案

试试这个,我会为你工作。这是Android的code

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

现在,这是另一个类Android版

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

最后,这是servlet的code为您

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