网络访问之HttpClient

本文介绍了在Android中如何使用HttpClient进行网络请求,包括GET和POST请求的具体实现方式,并提供了将输入流转换为字符串的方法。

HttpClient从Android6.0被移除了。
1、添加网络权限
流转换成字符串工具类

public class StreamUtils {
    public static String is2Str(InputStream is) throws IOException{
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int len = -1;
        byte[] buffer = new byte[1024];
        while((len=is.read(buffer))!=-1){
            baos.write(buffer, 0, len);
        }
        return baos.toString();
    }
}

2、get请求

new Thread(new Runnable() {
    @Override
    public void run() {
        try {
            // 1. 创建一个核心对象
            DefaultHttpClient httpClient = new DefaultHttpClient();
            // 创建一个HttpGet对象,代表了一个Get请求
            HttpGet httpGet = new HttpGet(pathUrl);
            // 访问网络,并接受返回值
            HttpResponse httpResponse = httpClient.execute(httpGet);
            // 获取状态行
            StatusLine statusLine = httpResponse.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (200 == statusCode) {
                // 获取返回的数据对象
                HttpEntity httpEntity = httpResponse.getEntity();
                // 获取服务器返回的流对象
                InputStream inputStream = httpEntity.getContent();
                String str = StreamUtils.is2Str(inputStream);
            } else {
            }
        } catch (Exception e) {
        }
    }
}).start();

3、post请求

new Thread(new Runnable() {
    @Override
    public void run() {
        try {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(pathUrl);
        List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
        parameters.add(new BasicNameValuePair("参数1", "参数1"));
        parameters.add(new BasicNameValuePair("参数2", "参数2"));
        //创建一个表单对象,设置编码,HttpCLient默认的编码不是utf-8
        UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(parameters,"utf-8");
        //设置请求体
        httpPost.setEntity(urlEncodedFormEntity);
        HttpResponse httpResponse = httpClient.execute(httpPost);
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        if (200==statusCode) {
            InputStream inputStream = httpResponse.getEntity().getContent();
            String is2Str = StreamUtils.is2Str(inputStream);
        }else {
        }
        } catch (Exception e) {
        }
    }
}).start();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值