void postRequest() throws IOException {
OkHttpClient client = new OkHttpClient();
File file = new File(Environment.getExternalStorageDirectory().toString() + "/Image_ref.jpg");
RequestBody requestbody = RequestBody.create(MultipartBody.FORM, file);
Request request = new Request.Builder().
addHeader("Authorization", "test").
post(requestbody).
url("MY_API").
build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
call.cancel();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.d("TAG",response.body().string());
}
});
}
但是我得到了回复说
“请求内容格式错误:带有多部分的Content-Type 媒体类型必须具有“边界”参数。
如果我做错了什么,'border'参数以及如何设置,请告诉我?
答案 0 :(得分:0)
RequestBody requestbody = RequestBody.create(MultipartBody.FORM, file);
我建议尝试使用,我使用相同的方式发送图像,并使用以下方法在一个请求中发送多个图像
MultipartBody.Builder multipartBodyBuilder = new MultipartBody.Builder();
multipartBodyBuilder.setType(MultipartBody.FORM); //this may not be needed
multipartBodyBuilder.addFormDataPart("file", "Image_ref.jpg", RequestBody.create(MEDIA_TYPE, file) );
然后可以使用相同的请求来执行此操作
try {
Response response = oKclient.newCall(request).execute();
line = response.body().string();
}catch
(Exception e ){
e.printStackTrace();
}
变量行将包含响应的主体,而响应对象是来自执行的实际响应,下面是我的代码显示如何同时添加多个文件,这实际上是我如何使用它不是很优雅但是完成工作
String order_data = "asdsd";
String images = getImages(id); //my funciton returns a json array Stringified
net.minidev.json.JSONArray fileArray = (net.minidev.json.JSONArray) net.minidev.json.JSONValue.parse(images);
MultipartBody.Builder multipartBodyBuilder = new MultipartBody.Builder();
multipartBodyBuilder. setType(MultipartBody.FORM);
multipartBodyBuilder.addFormDataPart("email", basicFunction.getUsername());
multipartBodyBuilder.addFormDataPart("password", basicFunction.getPassword());
multipartBodyBuilder.addFormDataPart("order_data",order_data);
int filer = 0; // adding a php based filter this can be the php array counter
MediaType MEDIA_TYPE = MediaType.parse("image/png" ); //
for (Iterator<Object> flavoursIter = fileArray.iterator(); flavoursIter.hasNext();){
net.minidev.json.JSONObject temp = (net.minidev.json.JSONObject) flavoursIter.next();
String path = (String)temp.get("path");
if(path.isEmpty() || path ==null ) continue;
path = path.substring(6);
// path = "fila://"+path;
File file = new File(path);
multipartBodyBuilder.addFormDataPart("file", "img.png", RequestBody.create(MEDIA_TYPE, file) );
//如果只显示一个文件,则可以使用此代码
// multipartBodyBuilder.addFormDataPart(&#34; file [&#34; + filer ++&#34;]&#34;,&#34; img.png&#34;,RequestBody.create(MEDIA_TYPE,文件));
}
MultipartBody multipartBody = multipartBodyBuilder.build();
Request request = new Request.Builder()
.url("Url_to_use")
.post(multipartBody)
.build();