I used Retrofit version 2.0.1 for uploading image from my Android phone to server and I got a strange error. This is my API interface for Post to server:
@POST("/vistek/myservice.php")
Call<String> send(@Part("myFile") RequestBody file);
My Okttp client is:
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
HttpLoggingInterceptor interceptor2 = new HttpLoggingInterceptor();
interceptor2.setLevel(HttpLoggingInterceptor.Level.HEADERS);
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
httpClient.addInterceptor(interceptor);
httpClient.addInterceptor(interceptor2);
And my function for sending image to server:
public void sendImage(byte[] data)
{
MediaType MEDIA_TYPE_JPEG = MediaType.parse("image/jpeg");
FileUploadService service = ServiceGenerator.createService(FileUploadService.class);
RequestBody requestBody = RequestBody.create(MEDIA_TYPE_JPEG, data);
Call<String> call = service.send(requestBody);
call.enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, retrofit2.Response<String> response) {
Log.d("Upload", "success = " + response.body());
}
@Override
public void onFailure(Call<String> call, Throwable t) {
Log.d("Upload","failure: " + t.getMessage());
}
});
}
After call function, I got strange response, something like this:
������JFIF����������������C������C�������"��������������������������
04-12 17:30:11.144 11669-13785/mmlab.visualsearch D/OkHttp: �����������}��!1AQa"q2���#B��R��$3br�
04-12 17:30:11.144 11669-13785/mmlab.visualsearch D/OkHttp: %&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz�������������������������������������������������������������������������������������������
04-12 17:30:11.144 11669-13785/mmlab.visualsearch D/OkHttp: ���������w��!1AQaq"2�B���� #3R�br�
My server works normally when I test api with Postman:
POST /vistek/myservice.php HTTP/1.1
Host: demo.mmlab.uit.edu.vn
Cache-Control: no-cache
Postman-Token: ba965fb1-f7b9-7344-8b8a-ab46095668d1
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW
----WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="myFile"; filename=""
Content-Type:
----WebKitFormBoundary7MA4YWxkTrZu0gW
Please help me to know what happen with my code. Thanks in advance.