正在向服务器发送 JSON 数据和图像
Sending JSON data and Image to Server
我不确定我是否在努力实现我的 objective。
我正在尝试将 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 以便它聚合它们?谢谢你们
将两个参数添加到 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);
我不确定我是否在努力实现我的 objective。
我正在尝试将 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 以便它聚合它们?谢谢你们
将两个参数添加到 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);