Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Http post with parameters not working

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

like image 812
Maaz Avatar asked May 11 '11 01:05

Maaz


3 Answers

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);  
like image 168
Femi Avatar answered Nov 14 '22 23:11

Femi


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"}
like image 23
dmon Avatar answered Nov 14 '22 22:11

dmon


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.

like image 1
Sumant Avatar answered Nov 14 '22 22:11

Sumant