我不确定我是否采取了正确的方法来实现我的目标。
我正在尝试将JSON数据和图像发送到服务器。当用户单击按钮时,异步调用激活,收集具有数据的JSON容器并获取图像路径。这是我到目前为止所做的:
protected String doInBackground(String... data) {
gatherEditTextStringValue();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
try {
ArrayList<NameValuePair> postVars = new ArrayList<NameValuePair>();
postVars.add(new BasicNameValuePair("JSON", String.valueOf(JSONMainContainer)));
httppost.setEntity(new UrlEncodedFormEntity(postVars));
if (questionTitleImageUri != null) {
questionTitleImageFile = new File(getRealPathFromURI(questionTitleImageUri));
FileBody bin1 = new FileBody(questionTitleImageFile);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("uploadedfile1", bin1);
httppost.setEntity(reqEntity);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
HttpResponse response = httpclient.execute(httppost);
responseBody = EntityUtils.toString(response.getEntity());
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return responseBody;
}
现在的问题是我可以发送或者两者都发送。有没有办法将图像数据附加到setEntity,以便它们聚合它们?谢谢你。
答案 0 :(得分:2)
将这两个参数添加到MultipartEntity
而不是调用setEntity
两次,因为setEntity
方法的第二次调用将覆盖第一个方法调用设置,如下所示:
MultipartEntity reqEntity = new MultipartEntity();
// add file
reqEntity.addPart("uploadedfile1", bin1);
// add JSON String
reqEntity.addPart("JSON", new StringBody(String.valueOf(JSONMainContainer)));
httppost.setEntity(reqEntity);