Loopj Put and Post with basic auth return null response with no error

Loopj Put and Post with basic auth return null response with no error

这是尝试使用 Loopj 从 HTTP 实用程序 class 进行同步放置和 post 调用。该代码使用同步客户端,因为它在 AsyncTask 中使用,一些 UI 交互在很大程度上依赖于 json 响应,因此 AsyncTask 正在管理异步调用。

来自 HTTP 实用程序 class 的所有 get 调用均成功运行。 post 和 put 没有,它们似乎有完全相同的问题。

json 字符串是使用 Gson 创建的。我已经在 Postman 中直接测试了应用程序的 json 输出,它 post 与 API 的预期完全一样,因此它看起来格式正确并且完全符合预期,没有任何错误。

put 和 post 调用的构造都没有引发错误。正在添加基本授权(如客户端实例所示)。使用空上下文参数调用 SyncHTTPClient put 方法。我做了一些研究,发现了一个 post 成功完成的地方。

https://github.com/loopj/android-async-http/issues/1139

put 调用会触发但不会进入处理程序的重写方法。它只是 returns 空。我已经包含了一部分工作 class 以供查看:

public void executePutSave(String name, String pass, String jsonBody) {
    client.setBasicAuth(name, pass);
    executeLoopJPutCall("/api/Save", jsonBody);
}

public void executeLoopJPutCall(String relativeUrl, String jsonBody) {
    String url = getAbsoluteUrl(relativeUrl);
    StringEntity entity = new StringEntity(jsonBody, "UTF-8");
    jsonResponse = null;
    client.put(null, url, entity, "application/json", new JsonHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                    super.onSuccess(statusCode, headers, response);
                    jsonResponse = response.toString();
                    Log.i(TAG, "onSuccess: " + jsonResponse);
                }
                @Override
                public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) { 
                    super.onFailure(statusCode, headers, throwable, errorResponse);
                    jsonResponse = errorResponse.toString();
                    Log.e(TAG, "onFailure: " + statusCode + errorResponse );
                }
            }
    );
}

因此,显然在将上述代码用于 Post 或将 json 用于 API 时,必须显式添加 header。一旦我从这里更改了 header 身份验证行:

client.setBasicAuth(name, pass);

为此:

    String userpass = name + ":" + pass;
    String encoded = new String(Base64.encode(userpass.getBytes(),Base64.NO_WRAP));
    client.addHeader("Authorization", "Basic "+encoded);

...一切都按预期进行。

我在这个博客上找到了信息:https://github.com/loopj/android-async-http/issues/113

传递空上下文也有效。