5

I found so many samples for requesting a REST API, but all together are confusing, can some one please explain me a way to use http requests.

My Requirement is, I want to get data from a REST API by providing username, pwd and a key.

What I have Used was,

        HttpClient client = new DefaultHttpClient();  
        HttpPost post = new HttpPost("REST API url"); 
        post.setHeader("Content-type", "application/json");

        JSONObject obj = new JSONObject();
        obj.put("username", "un");
        obj.put("pwd", "password");
        obj.put("key","123456");

        post.setEntity(new StringEntity(obj.toString(), "UTF-8"));
        HttpResponse response = client.execute(post);

But the response is always null and these working fine when tested with browser tool by posting the same data.Is some thing wrong with my approach? please suggest me the correct way. Thank you

4 Answers 4

6

(1) Google I/O video session for developing REST clients

(2) search in android developer blog

(3) https://github.com/darko1002001/android-rest-client

Please try after that post your question, I can share code snippet from my rest client developed based on (1) & (2)

Do not use Cloud to Device Messaging, instead use the latest cloud approach with android application development.

There is new library called Volley, which looks better than AsyncTask. It should be useful in developing RESTful clients.

Sign up to request clarification or add additional context in comments.

Comments

4

You probably forgot to add the internet permission to the manifest file. Add the following line.

 <uses-permission android:name="android.permission.INTERNET" />

Comments

2

I thing you should try this,

HttpContext localContext = new BasicHttpContext();
HttpClient client = new DefaultHttpClient();  
HttpPost post = new HttpPost("REST API url"); 
post.setHeader("Content-type", "application/json");

JSONObject obj = new JSONObject();
obj.put("username", "un");
obj.put("pwd", "password");
obj.put("key","123456");

post.setEntity(new StringEntity(obj.toString(), "UTF-8"));
HttpResponse response = client.execute(post,localContext);

Hope this will help.

1 Comment

No I tried this, still same issue. I am not able to get the response data. Could some one help me. Should I use UrlConnection instead of Http classes?
0

By any chance, is the server expecting a GET request for this operation? If so, you may want to use HttpGet instead of HttpPost.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.