Android HttpClient 用法以及乱码解决

一、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 用法以及乱码解决,,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。