我需要将图片上传到特定网址。经典的HTTP请求构建看起来像这样:
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(
getString(R.string.WebServiceURL)
+ "/cfc/iphonewebservice.cfc?method=uploadPhoto");
MultipartEntity entity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 100, bos);
byte[] data = bos.toByteArray();
entity.addPart("photoId", new StringBody(getIntent()
.getStringExtra("photoId")));
entity.addPart("returnformat", new StringBody("json"));
entity.addPart("uploaded", new ByteArrayBody(data,
"myImage.jpg"));
entity.addPart("photoCaption", new StringBody(caption.getText()
.toString()));
httpPost.setEntity(entity);
简而言之,假设我需要做的是使用httpPost.setEntity()
方法将图像放入请求中。
我已经知道如何使用Volley库构建请求;必须覆盖getBody
类中的com.android.volley.Request
方法,例如:
public byte[] getBody() throws AuthFailureError {
JsonObject json = new JsonObject();
Set<String> keySet = mParameters.keySet();
for (String key : keySet) {
json.addProperty(key, mParameters.get(key));
}
return json.toString().getBytes();
}
现在的问题是如何在Request
类中设置实体?没有类似setEntity()
的方法。