一、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 用法以及乱码解决
时间: 2024-10-12 17:40:26