• 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();
            }
        }
  • 相关阅读:
    Java 线程池
    eclipse 创建Java web项目 Cannot change version of project facet Dynamic web module to xxx
    Maven maven-compiler-plugin 编译问题
    设计模式 单例模式
    Spring 配置文件注入
    Java HashMap、HashTable与ConCurrentHashMap
    Java Web ActiveMQ与WebService的异同
    Java Web 拦截器和过滤器的区别
    html2canvas 使用指南
    js动态改变setInterval的时间间隔
  • 原文地址:https://www.cnblogs.com/wuyou/p/3427601.html
Copyright © 2020-2023  润新知