使用HttpClient方式请求网络

Android中有两种基于Http的网络访问对象,一种是Java自带的HttpURLConnection,另一种是HttpClient。但是新版本的Android SDK中将不再支持HttpClient。

实现步骤:
1. 定义一个HttpClient客户端对象
2. 定义方法,如HttpGet,HttpPost
3. 使用客户端执行定义的方法,返回HttpResponse响应对象
4. 使用响应对象,获得状态码,处理内容

/**GET方式进行访问
     * 
     * @param userName
     * @param password
     * @return
     */
    public static String loginOfGet(String userName, String password) {
        HttpClient client = null;
        try {
            client = new DefaultHttpClient();
            //定义一个get请求方法
            String data = "username=" + userName + "&password=" + password;
            HttpGet get = new HttpGet("......." + data);

            //设置请求头消息
            //post.addHeader("Content-Length", "20");

            //服务器相应对象,其中包含了状态信息和服务器返回的数据
            HttpResponse response = client.execute(get); //开始执行get方法,请求网络

            //获得响应码
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                InputStream is = response.getEntity().getContent();
                String text = getStringFromInputStream(is);
                return text;
            } else {
                Log.i(TAG, "请求失败" + statusCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (client != null) {
                client.getConnectionManager().shutdown(); //关闭连接,释放资源
            }
        }
        return null;

    }
/**POST方式进行访问
     * 
     * @param userName
     * @param password
     * @return
     */
    public static String loginOfPost(String userName, String password) {
        HttpClient client = null;
        try {
            //1.定义一个客户端
            client = new DefaultHttpClient();

            //2.定义post方法
            HttpPost post = new HttpPost(".......");

            List<NameValuePair> parameters = new ArrayList<NameValuePair>();
            parameters.add(new BasicNameValuePair("username", userName));
            parameters.add(new BasicNameValuePair("password", password));
            //把post请求的参数包装了一层
            //不写编码名称,服务器收取数据时乱码。需要指定字符集为utf-8
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters, "utf-8");
            //设置参数
            post.setEntity(entity);

            //设置请求头消息
            //post.addHeader("Content-Length", "20"); //...........

            //3.使用客户端执行post方法
            HttpResponse response = client.execute(post);

            //4.使用响应对象,获得状态码,处理内容
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                //使用响应对象获得实体,获得输入流
                InputStream is = response.getEntity().getContent();
                String text = getStringFromInputStream(is);
                return text;
                }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (client != null) {
                client.getConnectionManager().shutdown(); //关闭连接,释放资源
            }
        }
        return null;
    }
/**
     * 根据流返回一个字符串信息
     * @param is
     * @return
     * @throws IOException 
     */
    private static String getStringFromInputStream(InputStream is) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream(); //定义缓存流
        byte[] buffer = new byte[1024]; //定义一个字节数组
        int len = -1;
        while((len = is.read(buffer))!= -1) { //如果没有结束,执行写入操作
            baos.write(buffer, 0, len);
        }
        is.close();

        //String html = baos.toString(); //把流中的数据转换成字符串,采用编码:utf-8

        String html = new String(baos.toByteArray(), "GBK");
        baos.close();

        return html;
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值