在android Application和java之间进行通信

时间:2013-09-03 19:42:08

标签: java android communication

每个身体我是程序世界的新手,我遇到了问题,我的请求与使用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 !!!!");
}
}

上面的代码是我的servlet代码,它在我的本地系统服务器(Tomcat 6.0)中运行,我在这里通过println发送消息,我想在我的Android应用程序中显示相同的消息,该应用程序在另一个系统中运行。现在我要发布我在另一个系统上运行的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);
    }
}}

这里192.68.0.2是系统的ip地址,其中servlet代码在我的本地系统中运行(Tomcat6.0服务器,端口号为9999)。但它对我不起作用。系统在同一个wifi网络中帮助真的非常感激。在此先感谢所有

1 个答案:

答案 0 :(得分:2)

试试这个,我会为你工作。这是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;
      }   

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

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