首页 > 代码库 > Android HttpClient 用法以及乱码解决
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())); }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。