改造2:将图像上传到服务器并获得奇怪的响应

时间:2016-04-12 08:40:36

标签: android retrofit2

我使用Retrofit版本2.0.1将图像从我的Android手机上传到服务器,我收到了一个奇怪的错误。 这是Post to server的API接口:

@POST("/vistek/myservice.php")
    Call<String> send(@Part("myFile") RequestBody file);

我的Okttp客户端是:

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);

我将图像发送到服务器的功能:

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());
            }
        });
    }

在通话功能之后,我得到了奇怪的回答,如下:

JFIFCC&#34;
04-12 17:30:11.144 11669-13785 / mmlab.visualsearch D / OkHttp:�����������}��!1AQa&#34;q2���#B��R��$ 3 BR
04-12 17:30:11.144 11669-13785 / mmlab.visualsearch D / OkHttp:%&amp;&#39;()* 456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz������������������
04-12 17:30:11.144 11669-13785 / mmlab.visualsearch D / OkHttp:���������w��!1AQaq&#34;2�B����#3R�br�

当我使用Postman测试api时,我的服务器正常工作:

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

请帮助我了解我的代码会发生什么。 提前谢谢。

1 个答案:

答案 0 :(得分:1)

NOT 奇怪的回复。它被压缩(gzip)。

好像您已在"accept-encoding", "gzip"中添加header到您的请求中。在这种情况下,您有责任解压缩回复。

所以你可以做的是:

只需忽略代码中的accept-encoding标头即可。 OkHttp将添加自己的accept-encoding标头,如果服务器使用gzip响应,那么OkHttp将默默地为您解压缩。

你也可以像这样手动解压缩它:

StringBuilder stringBuilder = new StringBuilder();
ByteArrayInputStream bais = new ByteArrayInputStream(response.body().getBytes());
GZIPInputStream gzis = new GZIPInputStream(bais);
InputStreamReader reader = new InputStreamReader(gzis);
BufferedReader in = new BufferedReader(reader);

String readed;
while ((readed = in.readLine()) != null) {
    stringBuilder.append(readed);
}
in.close();
reader.close();
gzis.close();
String unZippedResponse = stringBuilder.toString();