Below is a method I'm using to make calls to a REST API. It works fine with POST (i.e. param isHttpPOST=true), and returns results from the server (which requires basic authentication).
But when using the GET code path (isHttpPOST=false), the authentication fails, as if I provided no credentials at all. I cannot see why, as the auth code applies to POST and GET.
What else needs doing to authenticate on a GET request?
private static HttpResponse makeHttpApiCall(String url, String json, boolean isHttpPOST, String username, String password)
{
DefaultHttpClient httpClient = new DefaultHttpClient();
UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password);
开发者_Go百科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;
}
i got the same problem, but the other way around, it works on GET but not on POST.
if the server is yours, i would recommend to use a freeware called Wireshark, to check what's going on in the transmition itself.
using that tool, showed me that the client sometimes makes a first annonymous request before making a second authorized request, but then the server kinda loses it and doesn't respond.. i still can't solve this issue.. it's driving me nuts.
精彩评论