How can I post in Android?
I was using Android API, to send some data using http POST method:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://myapp.com/");
try {
List parameters = prepareHttpParameters();
HttpEntity entity = new UrlEncodedFormEntity(parameters);
httppost.setEntity(entity);
Respons开发者_C百科eHandler responseHandler = new BasicResponseHandler();
response = httpclient.execute(httppost, responseHandler);
Toast.makeText(this, response, Toast.LENGTH_LONG).show();
} catch (IOException e) {
// TODO: manage ClientProtocolException and IOException
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
and my parameters are prepared here:
List parameters = new ArrayList(2);
parameters.add(new BasicNameValuePair("usr", "foo" ));
parameters.add(new BasicNameValuePair("pwd", "bar" ));
return parameters;
But it seems to be wrong because I do not get any expected response.
I have tested the same request with same parameters using Curl and I get expected response.
Am I wrong with my code?
Thank you very much
I'd consider the UrlEncodedFormEntity
constructor that takes an encoding as the second parameter. Otherwise, off the cuff, this looks OK. You might check on your server logs what you are receiving for these requests. You might also make sure your emulator has Internet connectivity (i.e., has two bars of signal strength), if you are using the emulator.
Here is the relevant portion of a sample app that uses HTTP POST (and a custom header) to update a user's status on identi.ca:
private String getCredentials() {
String u=user.getText().toString();
String p=password.getText().toString();
return(Base64.encodeBytes((u+":"+p).getBytes()));
}
private void updateStatus() {
try {
String s=status.getText().toString();
HttpPost post=new HttpPost("https://identi.ca/api/statuses/update.json");
post.addHeader("Authorization",
"Basic "+getCredentials());
List<NameValuePair> form=new ArrayList<NameValuePair>();
form.add(new BasicNameValuePair("status", s));
post.setEntity(new UrlEncodedFormEntity(form, HTTP.UTF_8));
ResponseHandler<String> responseHandler=new BasicResponseHandler();
String responseBody=client.execute(post, responseHandler);
JSONObject response=new JSONObject(responseBody);
}
catch (Throwable t) {
Log.e("Patchy", "Exception in updateStatus()", t);
goBlooey(t);
}
}
精彩评论