Basic authentication with HttpClient on Android using https and PUT

‘ve been beating my head against a wall for hours with this one. The examples I’d been using all returned HTTP 400 Bad Request, and Apache’s HttpClient is cryptic enough so that the reason for this wasn’t obvious. The reason for this response still isn’t obvious, but thanks to Kyle Lampe, I now have some code that actually works:

try {
    String data = "YOUR REQUEST BODY HERE";
    //
    CredentialsProvider credProvider = new BasicCredentialsProvider();
    credProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
        new UsernamePasswordCredentials("YOUR USER NAME HERE", "YOUR PASSWORD HERE"));
    //
    DefaultHttpClient http = new DefaultHttpClient();
    http.setCredentialsProvider(credProvider);
    //
    HttpPut put = new HttpPut("YOUR HTTPS URL HERE");
    try {
        put.setEntity(new StringEntity(data, "UTF8"));
    } catch (UnsupportedEncodingException e) {
        Log.e(TAG, "UnsupportedEncoding: ", e);
    }
    put.addHeader("Content-type","SET CONTENT TYPE HERE IF YOU NEED TO");
    HttpResponse response = http.execute(put);
    Log.d(TAG, "This is what we get back:"+response.getStatusLine().toString()+", "+response.getEntity().toString());
} catch (ClientProtocolException e) {
    //
    Log.d(TAG, "Client protocol exception", e);
} catch (IOException e) {
    //
    Log.d(TAG, "IOException", e);
}

Comments are closed.

Related Links

Resource Links