[英]cant get request body sent from retrofit in php
我正在嘗試使用改造將多個圖像發送到服務器,我正在做的是發送RequestBody的映射,這是我的代碼
@Multipart
@POST("imageuload")
Call<ResponseBody> postImage(@PartMap Map<String, RequestBody> files );
在我的活動中
Map<String, RequestBody> filestosend = new HashMap<>();
for (int pos = 0; pos < files.size(); pos++) {
RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), files.get(pos));
filestosend.put("photo_" + String.valueOf(pos + 1), requestBody);
}
Call<ResponseBody> call = apiSerice.postImage(filestosend);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()) {
try {
Toast.makeText(getBaseContext(),response.body().string(),Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
}else {
try {
AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
alert.setMessage(response.errorBody().string());
alert.show();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
t.printStackTrace();
}
});
當我想測試我得到的東西時,從服務器返回一個空響應,而我的響應中什么也沒有。
echo file_get_contents('php://input');
我什至用一個請求正文進行了測試
RequestBody test = RequestBody.create(MediaType.parse("text/plain"), "test");
Call<ResponseBody> call = apiSerice.postImage(test);
但我仍會在回應中得到空洞的回應,我將不勝感激任何幫助或評論
可以通過$_FILES
在PHP中訪問分段上傳。 關於php://input
, PHP手冊有以下說法:
php:// input不能與enctype =“ multipart / form-data”一起使用。
完整的工作示例(減去正確的端點URL,硬編碼字節數組):
public class Sample {
interface SampleService {
@Multipart
@POST("/test.php")
Call<ResponseBody> postImage(@Part List<MultipartBody.Part> files);
}
public static void main(String[] args) throws IOException {
Retrofit retrofit = new Retrofit.Builder().baseUrl("http://...").build();
SampleService service = retrofit.create(SampleService.class);
RequestBody file1 = RequestBody.create(MediaType.parse("image/jpeg"), new byte[]{0x00});
MultipartBody.Part part1 = MultipartBody.Part.createFormData("A kitten", "Kitten.jpg", file1);
RequestBody file2 = RequestBody.create(MediaType.parse("image/jpeg"), new byte[]{0x00});
MultipartBody.Part part2 = MultipartBody.Part.createFormData("Another kitten", "Kitten2.jpg", file2);
System.out.println(service.postImage(Arrays.asList(part1, part2)).execute().body().string());
}
}
服務器代碼:
<?php var_dump($_FILES); ?>
客戶的輸出:
array(2) {
["A_kitten"]=>
array(5) {
["name"]=>
string(10) "Kitten.jpg"
["type"]=>
string(10) "image/jpeg"
["tmp_name"]=>
string(14) "/tmp/phpml5PIP"
["error"]=>
int(0)
["size"]=>
int(1)
}
["Another_kitten"]=>
array(5) {
["name"]=>
string(11) "Kitten2.jpg"
["type"]=>
string(10) "image/jpeg"
["tmp_name"]=>
string(14) "/tmp/phpzhgXm0"
["error"]=>
int(0)
["size"]=>
int(1)
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.