我试图开发Android的一个简单的POST的API调用,所以我提出一个想法,该请求内容类型是JSON。原来它是期待一个multipart/form-data
格式和我挣扎改变我的功能。 我想知道是否有任何库来管理这一点。如果不是,我想知道如何以多部分格式传递我的论点。更改JSON post请求为multipart/form-数据
@Override
public boolean post(String poiId, String description, ArrayList<String> tags, Resource resource) {
RequestQueue queue = mRequestQueue;
poiId = "1";
description = "Test post";
final HashMap<String, Object> params = new HashMap<>();
params.put("poiID", poiId);
params.put("description", description);
System.out.println("POI ID " + description);
params.put("tags", tags);
params.put("resource", resource);
RequestFuture<JSONObject> future = RequestFuture.newFuture();
JsonObjectRequest request = new JsonObjectRequest(
Request.Method.POST,
API_POST_URL,
new JSONObject(params),
future, future) {
@Override
public HashMap<String, String> getHeaders() {
System.out.println(PostRepositoryImpl.this.getHeaders());
return PostRepositoryImpl.this.getHeaders();
}
};
queue.add(request);
try {
future.get(TIMEOUT, TIMEOUT_TIME_UNIT); // this will block
}catch (InterruptedException | ExecutionException | TimeoutException e){
e.printStackTrace();
return false;
}
return true;
}
我硬编码一些值,因为我想与poiID
和description
所以我想在我的multipart /表单日期发送这些类型的值来测试: - poiID:字符串 - 描述:字符串 - 资源:图像 - 标签
有没有办法做到这一点类似于我在我的JSON请求的方式吗?
亲切的问候
编辑:
@Override
public boolean post(String poiId, String description, ArrayList<String> tags, Resource resource) {
RequestQueue queue = mRequestQueue;
StringRequest postRequest = new StringRequest(Request.Method.POST, API_POST_URL,
new Response.Listener<String>()
{
@Override
public void onResponse(String response) {
// response
Log.d("Response", response);
}
},
new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", "400");
}
}
) {
@Override
protected HashMap<String, String> getParams()
{
HashMap<String, String> params = new HashMap<String, String>();
params.put("poiID", "Alif");
params.put("description", "http://itsalif.info");
return params;
}
};
queue.add(postRequest);
return true;
}
如何添加标题?
您是否使用Volley ?,我建议您使用Retrofit 2,它更好,更好,让我知道如果您想要一个关于如何使用Retrofit发送多部分数据的示例。 Regards –
不幸的是,我正在使用Volley。但非常感谢:) –
花点时间来检查这个要点https://gist.github.com/alphamu/684d8ae311d95831ce1c –