zoukankan      html  css  js  c++  java
  • 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()));
            }
  • 相关阅读:
    Spring AOP总结(三)
    Spring AOP源码解析(二)
    java9新特性
    BeanFactory和ApplicationContext的区别总结
    Elasticsearch7.X为什么移除类型(type)
    elasticsearch性能优化(二)
    elasticsearch性能优化(一)
    elasticsearch的master选举机制
    自动化构建和部署应用系统平台
    关系型数据库之mysql-01
  • 原文地址:https://www.cnblogs.com/hzm112567/p/3838263.html
Copyright © 2011-2022 走看看