• 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();
            }
        }
  • 相关阅读:
    对返回的json数据重写格式,用特性JsonConverter
    dev 的NavBarControl动态菜单
    获取oracel数据库的结构
    Java-背单词程序(俄语)
    实现同或操作 C++
    输入字符串先用cin后用getline函数失效原因
    C++全局变量与局部变量
    4.Redis事务
    3.持久化配置
    2.常用数据类型
  • 原文地址:https://www.cnblogs.com/wuyou/p/3427636.html
Copyright © 2020-2023  润新知