AndroidはHttpClient方式でGETリクエストを提出

4548 ワード

public void httpClientGet(View view) {

        final String username = usernameEditText.getText().toString().trim();

        final String password = passwrodEditText.getText().toString().trim();

        //Android           10.0.2.2,   localhost 127.0.0.1

        final String serverPath = "http://10.0.2.2:8080/LoginServlet";

        if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) {

            //

        } else {

            new Thread(new Runnable() {

                @Override

                public void run() {

                    try {

                        //     

                        HttpClient httpClient = new DefaultHttpClient();

                        //    get    

                        HttpGet httpGet = new HttpGet(serverPath + "?username=" + URLEncoder.encode(username, "UTF-8") + "&password=" + URLEncoder.encode(password, "UTF-8"));

                        //         ,         HttpResponse

                        HttpResponse httpResponse = httpClient.execute(httpGet);

                        //              

                        int statusCode = httpResponse.getStatusLine().getStatusCode();

                        if (200 == statusCode) {

                            InputStream inputStream = httpResponse.getEntity().getContent();

                            final String responseMsg = StreamTool.getString(inputStream);

                            runOnUiThread(new Runnable() {

                                @Override

                                public void run() {

                                    Toast.makeText(MainActivity.this, responseMsg, Toast.LENGTH_LONG).show();

                                }

                            });

                        } else {

                            System.out.println("statusCode = " + statusCode);

                            //       ,     :responseCode               

                            //....

                        }

                    } catch (Exception e) {

                        e.printStackTrace();

                    }

                }

            }).start();

        }

    }