我必须使用MultipartEntity发布这样的json。
{
arrayName":[
{
// object one
},
{
// object two
}]
}我不知道如何在发布multipartEntity对象后创建这样的结构,到目前为止我已经尝试过了。
MultipartEntity entity = new MultipartEntity();
entity.addPart("key","value");
.....
.....
..... all keys
httppost.setEntity(entity);有没有什么方法可以让我做MultipartEntity数组或者别的什么?
注意:对于单独发布一个json对象,它可以很好地工作。我只想学习如何创建JSONarry格式,一旦与MultipartEntity发帖。
发布于 2015-11-05 21:00:55
您必须将json数组转换为string。
使用Gson库可以做到这一点。Gson
现在你只需要像这样使用。不管你的模型是什么
ArrayList<CustomClass> objects = new ArrayList<>();
objects.add(object);
objects.add(object);然后使用gson。
String stringToPost = new Gson().toJson(objects);然后将multipart this string添加为
Stringbody服务器端将反序列化字符串到Json Array.
您还可以将文件作为filebody添加到multipart中。
发布于 2017-04-21 17:54:42
这是一个使用MultipartEntity上传图像和JSONArray的示例-- lib:org.apache.http.entity.mime
List students = getStudentList();
MultipartEntity studentList = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
for(int i=0; i<students.size();i++){
try {
studentList.addPart("studentList[][name]", new StringBody(String.valueOf(students.get(i).getName())));
studentList.addPart("studentList[][addmission_no]", new StringBody(String.valueOf(students.get(i).getAddmissionNo)));
studentList.addPart("studentList[][gender]", new StringBody(String.valueOf(students.get(i).getGender)));
File photoImg = new File(students.get(i).getImagePath());
studentList.addPart("studentList[][photo]",new FileBody(photoImg,"image/jpeg"));
}catch(Exception e){
e.getMessage();
}
}
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(URL);
post.addHeader("X-Auth-Token", mUserToken);
post.setEntity(studentList);
org.apache.http.HttpResponse response = null;
try {
response = client.execute(post);
} catch (IOException e) {
e.printStackTrace();
}
HttpEntity httpEntity = response.getEntity();
JSONObject myObject;
try {
String result = EntityUtils.toString(httpEntity);
// do your work
} catch (IOException e) {
e.printStackTrace();
}https://stackoverflow.com/questions/33543767
复制相似问题