具有基本身份验证的Loopj Put和Post返回空响应,没有错误

时间:2018-11-10 00:12:58

标签: json post android-asynctask put loopj

这是尝试使用Loopj进行HTTP实用程序类的同步放置和调用。该代码使用的是AsyncTask内部使用的同步客户端,并且某些UI交互在很大程度上取决于json响应,因此AsyncTask正在管理异步调用。

HTTP实用程序类中的所有get调用均正常运行。帖子和放置不这样做,它们似乎都存在完全相同的问题。

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

构造put和post调用都不会引发错误。基本授权正在添加(如客户端实例所示)。使用空上下文参数调用SyncHTTPClient put方法。我做了一些研究,并找到了一个成功完成此操作的帖子。

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

会发出put调用,但不会输入处理程序的任何覆盖方法。它只是返回null。我已经包括了一部分工人阶级的观点:

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

1 个答案:

答案 0 :(得分:0)

因此,显然,使用上述代码将json张贴或放置到API时,必须显式添加标头。一旦我从此更改了标题验证行:

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

传递空上下文也可以。