码迷,mamicode.com
首页 > 移动开发 > 详细

Android HttpClient 用法以及乱码解决

时间:2014-07-12 16:22:05      阅读:182      评论:0      收藏:0      [点我收藏+]

标签:android   style   blog   http   java   color   

一、Post提交 并可以实现多文件上传

// 创建DefaultHttpClient对象
        HttpClient httpclient = new DefaultHttpClient();
        // 创建一个HttpGet对象
        HttpPost post = new HttpPost(realUrl);
        
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        
        if (params != null) {
            for (String key : params.keySet()) {
                if (params.get(key) instanceof File) {
                    // If the key equals to "image", we use FileBody to
                    // transfer the data
                    entity.addPart(key, new FileBody((File) params.get(key)));
                } else {
                    // Normal string data
                    if (params.get(key) != null) {
                        entity.addPart(key, new StringBody(params.get(key).toString(), java.nio.charset.Charset.defaultCharset())); //此处防止乱码
                    }
                }
            }
        }

        post.setEntity(entity);

        // 获取HttpResponse对象
        HttpResponse response = httpclient.execute(post);
        // 判断是否链接成功
        if (response.getStatusLine().getStatusCode() == 200) {
            // 实体转换为字符串
            String content = EntityUtils.toString(response.getEntity(), HTTP.UTF_8);
            LogUtil.i("response:" + content);
            return new JSONObject(content);
        } else {
            LogUtil.i("realurl: " + getCode(response.getStatusLine().getStatusCode()));
        }

 

二、Get方式

// 创建DefaultHttpClient对象
        HttpClient httpclient = new DefaultHttpClient();

        // 实例化HTTP方法  
        HttpGet get = new HttpGet();  
        get.setURI(new URI(realUrl));  


        // 获取HttpResponse对象
        HttpResponse response = httpclient.execute(get);
        // 判断是否链接成功
        if (response.getStatusLine().getStatusCode() == 200) {
            // 实体转换为字符串
            String content = EntityUtils.toString(response.getEntity(), HTTP.UTF_8);
            LogUtil.i("response:" + content);
            return new JSONObject(content);
        } else {
            LogUtil.i("realurl: " + getCode(response.getStatusLine().getStatusCode()));
        }

 

Android HttpClient 用法以及乱码解决,布布扣,bubuko.com

Android HttpClient 用法以及乱码解决

标签:android   style   blog   http   java   color   

原文地址:http://www.cnblogs.com/hzm112567/p/3838263.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!