Httpclient

Posted nangongyibin

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Httpclient相关的知识,希望对你有一定的参考价值。

  • httpclient实现get和post提交
  • 代码实现过程 
    • 到包 compile ‘com.loopj.android:android-async-http:1.4.9’ 把这个包导入到build.gradle里 
    • httlclient实现get提交数据
    private void httpclientGET() {
        try {
            String username = mName.getText().toString().trim();
            String password = mPwd.getText().toString().trim();
            String path = "http://192.168.0.156:8080/loginServlet/loginServlet?username=" + username + "&&password=" + password;
            //使用httpclient提交数据
            HttpClient client = new DefaultHttpClient();
            //实现向服务器放松请求
            HttpGet httpGet = new HttpGet(path);
            HttpResponse httpResponse = client.execute(httpGet);
            InputStream is = httpResponse.getEntity().getContent();
            String content = StreamUtils.StreamToString(is);
            showToast(content);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

 

    • 使用httpclient实现post提交
    private void httpclientPost() {
        try {
            String username = mName.getText().toString().trim();
            String password = mPwd.getText().toString().trim();
            String path = "http://192.168.0.156:8080/loginServlet/loginServlet";
            //定义请求体
            String data = "username=" + username + "&&password=" + password;
            HttpClient client = new DefaultHttpClient();
            HttpPost post = new HttpPost(path);
            //定义请求体
            List<NameValuePair> list = new ArrayList<>();
            BasicNameValuePair nameValuePair = new BasicNameValuePair("username", username);
            list.add(nameValuePair);
            BasicNameValuePair passwordValuePair = new BasicNameValuePair("password", password);
            list.add(passwordValuePair);
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list);
            post.setEntity(entity);
            HttpResponse response = client.execute(post);
            InputStream is = response.getEntity().getContent();
            String content = StreamUtils.StreamToString(is);
            showToast(content);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

 

以上是关于Httpclient的主要内容,如果未能解决你的问题,请参考以下文章

WP8,怎么使用HttpClient?

android的自带的httpClient 怎么上传文件

怎么用http协议实现安卓数据

HttpClient配置及示例代码

HttpClient学习--HttpClient的POST请求过程源码解读

java用httpclient 执行到httpclient.execute(request); 这句代码假死不往下执行不报错