我需要将图像上传到某个 URL。经典的 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()
.