Android 使用HttpClient方式提交GET请求

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();
        }
    }
原文地址:https://www.cnblogs.com/wuyou/p/3427601.html