okHttpClient响应给出垃圾值

问题描述 投票:1回答:2

我正在尝试使用okHttpClient 4.2.1库注册用户,并且作为响应,我得到了一些垃圾值

Respone is  �������������V*.MNN-.V�JK�)N�Q�r�S���rR�SSR��K2��t�RK���ck�NY�<������

我使用邮递员,响应是我所期望的。我不明白为什么它不能在Android Studio中使用。

{"result": {"OTP": 1113401845,"id": 143},"success": true,"message": "User Registered In Successfully"}

这是我使用的代码

OkHttpClient client = new OkHttpClient();

MediaType mediaType = MediaType.parse("application/json; charset=utf-8");

JSONObject postdata = new JSONObject();
try {
    postdata.put("action", "registrationFirst");
    postdata.put("User_name", "abcd");
    postdata.put("password", "12345");
    postdata.put("email", "[email protected]");
    postdata.put("street", "qa");
    postdata.put("Gender", "1");
    postdata.put("Religion", "3");
    postdata.put("caste", "Other");
    postdata.put("Country", "UAE");
    postdata.put("mobile", "0123456");
    postdata.put("Locaion", "SHJ");
} catch(JSONException e){
    // TODO Auto-generated catch block
    e.printStackTrace();
}

RequestBody body = RequestBody.create(mediaType,postdata.toString());

Request request = new Request.Builder()
        .url(myUrl)
        .post(body)
        .addHeader("content-type", "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW")
        .addHeader("Content-Type", "application/json")
        .addHeader("Authorization", "Basic aW5mb0Bhbm9vbnouY29tOjEyMTIxMg==")
        .addHeader("User-Agent", "PostmanRuntime/7.20.1")
        .addHeader("Accept", "application/json")
        .addHeader("Cache-Control", "no-cache")
        .addHeader("Postman-Token", "cf631a82-2570-4c20-9c39-be0563240c67,f9cecf3d-2340-4fce-bb6f-c060c9f8894f")
        .addHeader("Accept-Encoding", "gzip, deflate")
        .addHeader("Content-Length", "1278")
        .addHeader("Connection", "keep-alive")
        .addHeader("cache-control", "no-cache")
        .build();

Response response = null;

try {
    response = client.newCall(request).execute();

    if (response.isSuccessful()) {

        String result = response.body().string();
        Log.d("Hola","Response is "+result);

    }

} catch (Exception e) {
    e.printStackTrace();
    Log.d("Hola","Failed exception "+e);

}
java json android-studio okhttp
2个回答
0
投票

使用Request.Builder建立请求时,您应删除以下行:

addHeader("Accept-Encoding", "gzip, deflate")

[当您指定自己的Accept-Encoding值时,意味着您要进行自己的解压缩,但您不希望这样做。


0
投票

Android Studio可能不解压缩响应并将其显示给您压缩的情况。您可能想要删除标题“ Accept-Encoding”,“ gzip,deflate”,以使其正常工作。

© www.soinside.com 2019 - 2024. All rights reserved.