如何使用发布请求发送图像

时间:2011-10-26 12:59:37

标签: java android network-programming

我需要发送带有key = value等格式的数据的post请求,我正在工作(url是ws的url,没关系)

 HttpEntityEnclosingRequestBase post=new HttpPost();
 String result = "";
 HttpClient httpclient = new DefaultHttpClient();
 post.setURI(URI.create(url));
 List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
 for (Entry<String, String> arg : args.entrySet()) {
    nameValuePairs.add(new BasicNameValuePair(arg.getKey(), arg
                    .getValue()));
    }
 http.setEntity(new UrlEncodedFormEntity(nameValuePairs));
 HttpResponse response;
 response = httpclient.execute(post);
 HttpEntity entity = response.getEntity();
 if (entity != null) {
    InputStream instream = entity.getContent();
    result = getStringFromStream(instream);
    instream.close();
    }    
 return result;

当我发送字符串数据时,这是可以的。我的问题是当一个参数是图片时修改什么,其他参数是字符串?

3 个答案:

答案 0 :(得分:1)

当您使用多种数据类型通过HttpClient发送时,必须使用MultipartEntityBuilder(org.apache.http.entity.mime中的类)

尝试一下

MultipartEntityBuilder s= MultipartEntityBuilder.create();
File file = new File("sample.jpeg");
String message = "This is a multipart post";
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
System.out.println(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addBinaryBody("upfile", file, ContentType.DEFAULT_BINARY, "sample.jpeg");
builder.addTextBody("text", message, ContentType.DEFAULT_BINARY);
HttpEntity entity = builder.build();
httppost.setEntity(entity);
}

答案 1 :(得分:0)

如果您希望将图像作为发布请求的数据部分发送,则可以按照评论中发布的一些链接进行操作。

如果图像/二进制数据必须绝对是标题(我不建议使用),那么您应该使用Base64 Android类中的encodeToString方法。我不建议将此用于大图像,因为您需要将整个图像作为字节数组加载到内存中,然后才能将其转换为字符串。将它转换为字符串后,它的前一个大小也是4/3。

答案 2 :(得分:0)

我认为您正在寻找的答案在这篇文章中:

How to send an image through HTTPPost?

灵光

相关问题