Android 使用HttpClient方式提交POST请求

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();
                        //创建一个post请求对象
                        HttpPost httpPost = new HttpPost(serverPath);
                        //创建请求参数
                        List<NameValuePair> parameters = new ArrayList<NameValuePair>();
                        parameters.add(new BasicNameValuePair("username",username));
                        parameters.add(new BasicNameValuePair("password",password));
                        //请求参数设置到httpPost的实体里
                        httpPost.setEntity(new UrlEncodedFormEntity(parameters, "UTF-8"));
                        //浏览器提交这个请求,然后服务器返回一个HttpResponse
                        HttpResponse httpResponse = httpClient.execute(httpPost);
                        //通过返回信息获取返回的状态码
                        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();
        }
    }

 

posted @ 2013-11-17 11:27  无忧之路  阅读(606)  评论(0编辑  收藏  举报
无忧之路