下面是我用来调用 REST API 的方法。它适用于 POST(即参数 isHttpPOST=true),并从服务器返回结果(需要基本身份验证)。
但是当使用 GET 代码路径 (isHttpPOST=false) 时,身份验证失败,就好像我根本没有提供任何凭据一样。我不明白为什么,因为授权代码适用于 POST 和 GET。
还需要做什么来对 GET 请求进行身份验证?
private static HttpResponse makeHttpApiCall(String url, String json, boolean isHttpPOST, String username, String password)
{
DefaultHttpClient httpClient = new DefaultHttpClient();
UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password);
httpClient.getCredentialsProvider().setCredentials(new AuthScope("blah.com", 80), creds);
HttpResponse response;
try {
if ( isHttpPOST )
{
HttpPost httppost = new HttpPost(url);
StringEntity se = new StringEntity(json);
se.setContentEncoding("UTF-8");
httppost.setHeader("Content-Type", "application/json");
httppost.setEntity(se);
response = httpClient.execute(httppost);
}
else
{
HttpGet get = new HttpGet(url);
response = httpClient.execute(get);
}
} catch (ClientProtocolException e) {
Trace.e(TAG, "There was a protocol based error making API call", e);
return null;
} catch (IOException e) {
Trace.e(TAG, "There was an IO Stream related error making API call", e);
return null;
} catch (Exception e) {
Trace.e(TAG, "Failed to get a response from API call (unknown error)", e);
return null;
}
return response;
}
最佳答案
我遇到了同样的问题,但反过来,它适用于 GET 但不适用于 POST。
如果服务器是您的,我建议您使用名为 Wireshark 的免费软件来检查传输本身发生了什么。
使用该工具,向我展示了客户端有时会在发出第二个授权请求之前发出第一个匿名请求,但随后服务器有点丢失它并且没有响应..我仍然无法解决这个问题..它是快把我逼疯了。
关于java - 为什么我的基本身份验证适用于 POST 而不是 GET 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7098153/