I need to create an HTTP POST request with parameters. I know there are many examples out there, I have tried using HTTPparams, NameValuePair etc but cant seem to get the correct format for the server.
Server Type: REST based API utilizing JSON for data transfer
Content-type: application/json
Accept: application/json
Content-length: 47
{"username":"abcd","password":"1234"}
I can pass these headers but I cant seem to pass these params "username","password". Here is my code:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://www.mymi5.net/API/auth/login");
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("username","abcd"));
pairs.add(new BasicNameValuePair("password","1234"));
post.setHeader("Content-type", "application/json");
post.setHeader("Accept", "application/json");
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs,"UTF-8");
post.setEntity(entity);
HttpResponse response = client.execute(post);
I tried to debug, but cant see if entity is attached properly or not... What am I doing wrong?
Thanks in Advance. Maaz
Try this:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://www.mymi5.net/API/auth/login");
post.setHeader("Content-type", "application/json");
post.setHeader("Accept", "application/json");
JSONObject obj = new JSONObject();
obj.put("username", "abcd");
obj.put("password", "1234");
post.setEntity(new StringEntity(obj.toString(), "UTF-8"));
HttpResponse response = client.execute(post);
I'm not quite sure, from your description, but it would seem that your server expects a JSON content object instead of the data being encoded in the URL. Send something like this as the body of your post:
{"username":"abcd","password":"1234"}
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://www.mymi5.net/API/auth/login");
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("username","abcd"));
pairs.add(new BasicNameValuePair("password","1234"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs,HTTP.UTF_8);
post.setEntity(entity);
HttpResponse response = client.execute(post);
just try this coz it works perfect for me when i am trying to HTTP post.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With