While developing a helper for the Twitter API to be used in the Android application which I’m writing I ran into a nasty problem. While trying to post to Twitter Twitter kept sending “417 – Expectation Failed” responses. I solved this by specifically setting the UseExpectContinue flag to false.
The following snippets are part of my helper class to talk to twitter, it runs fine on my ADP1 using Android 1+ :
[java]
private static final DefaultHttpClient httpclient = new DefaultHttpClient();
private static final AuthScope AUTH_SCOPE = new AuthScope(“twitter.com”, 80, AuthScope.ANY_REALM);
private static JSONObject post(final String url, final Map fields, final UsernamePasswordCredentials credentials) throws Exception {
final HttpParams params = createParamsForPosting();
// Tell twitter who we are
httpclient.getCredentialsProvider().setCredentials(AUTH_SCOPE, credentials);
httpclient.setParams(params);
final HttpPost post = new HttpPost(url);
// Setup the form data to post
final UrlEncodedFormEntity requestEntity = mapToFormEntity(fields);
post.setEntity(requestEntity);
final HttpResponse response = httpclient.execute(post);
final HttpEntity responseEntity = response.getEntity();
final String data = IOUtils.convertStreamToString(responseEntity.getContent());
return new JSONObject(data);
}
private static HttpParams createParamsForPosting() {
final HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, UTF_8);
HttpProtocolParams.setUseExpectContinue(params, false); // solves the ’417′ issue
return params;
}
private static UrlEncodedFormEntity mapToFormEntity(final Map fields) throws UnsupportedEncodingException {
final ArrayList values = new ArrayList(fields.size());
for (final Entry entry : fields.entrySet()) {
values.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
final UrlEncodedFormEntity entity = new UrlEncodedFormEntity(values, UTF_8);
return entity;
}
[/java]
When complete I’ll probably opensource the twitter API wrapper in full, at the moment it is not complete enough to do so.