Reputation: 1178
Does Basic HTTP Authentication work when attempting an HTTP POST via Android?
I've been working with some code that uses Basic Authentication when completing an HTTP GET request and it works perfectly. I need to use the same authentication when completing an HTTP POST.
HttpPost request = new HttpPost(baseUrl+"events.json");
String credentials = email + ":" + password;
String base64EncodedCredentials = Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
request.setHeader("Authorization", "Basic " + base64EncodedCredentials);
request.setHeader(HTTP.CONTENT_TYPE,"application/json");
try
{
ArrayList<NameValuePair> vars = new ArrayList<NameValuePair>(2);
vars.add(new BasicNameValuePair("event[name]",currentEvent.name));
vars.add(new BasicNameValuePair("event[location]",currentEvent.location));
vars.add(new BasicNameValuePair("event[num_expected]",new Integer(currentEvent.num_expected).toString()));
request.setEntity(new UrlEncodedFormEntity(vars));
} catch (Exception e) {
// Log exception
Log.e("CreateEvent", "doInBackground — " + Errors.getStackTrace(e));
}
HttpClient httpclient = new DefaultHttpClient();
try {
HttpResponse response = httpclient.execute(request);
if (response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity, "UTF-8");
return 1;
}
}
catch (Exception e) {
// Log exception
Log.e("CreateEvent", "doInBackground — " + Errors.getStackTrace(e));
}
The response is an HTTP 500 error. It's not returning any details, so I can't tell exactly what's wrong, but the only difference is the POST and the passing of form data.
Upvotes: 2
Views: 1229
Reputation: 3474
Looking your code with more detail it looks like you are setting the Content-Type
to application/json
but then sending application/x-www-form-urlencoded
data (I guess that's what UrlEncodedFormEntity
does), thus the web service is failing to parse the data as a JSON.
Upvotes: 3