Android Rest Client - java

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

(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.

You probably forgot to add the internet permission to the manifest file.
Add the following line.
<uses-permission android:name="android.permission.INTERNET" />

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.

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

Related

HttpClient redirecting

I am trying to write a video downloader from kissanime.to . I am using HttpClient library. This site is using cloudflare. It redirects after 5 secs. How can I set so my application will go to the redirected link? My code below isnt working. Where am I going wrong and how can I fix it.
HttpGet request = new HttpGet(url);
HttpClient httpClient = HttpClientBuilder.create()
.setRedirectStrategy(new LaxRedirectStrategy()).build();
HttpResponse response = httpClient.execute(request);
HttpEntity entity = response.getEntity();
String entityContents = EntityUtils.toString(entity);`
It means that given site is under DDOS protection mode (maybe you try to open it too often?) to workaround you would need to stop hitting it that much (e.g. wait some time between tries). Or if you insist use some javascript executing library (Rhino?) that would execute javascript that cloudflare is using.

Sharepoint REST Api in Java: Unable to access site documents

I am trying to access sharepoint site documents using SP REST API in java. I am able to authenticate and get a response for the below URL
http://sharepoint_server_url/_api/lists/getbytitle('Documents')
But I want to get the list of folders and files inside my site. I tried the following URL, but it gives me 401 Unauthorized.
http://sharepoint_server_url/sites/mysitename/_api/lists/getbytitle('Documents')
I am using the NTCredentials class, to authenticate.
Please let me know if
I have to make some setting in the Sharepoint server for mysite, so that I can access it through API?
Or, The URL above is wrong, I have to change it?
This is the code used for authentication :
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
new AuthScope(AuthScope.ANY),
new NTCredentials("username", "password", "http://server_DNS", "DOMAIN"));
CloseableHttpClient httpclient = HttpClients.custom()
.setDefaultCredentialsProvider(credsProvider)
.build();
HttpGet httpget = new HttpGet(url);
httpclient.execute(httpget);
I am sure someone must have done this already.
Thanks in advance.
You can take a look of this project i've created for using the ShareopintRestAPI from java. I decided to make my own implementation as I've struggled a lot with other APIs i found and i was not able to make them work.
You can take a look here
https://github.com/kikovalle/PLGSharepointRestAPI-java

Do intents no longer work for posting images on Facebook?

I created an app some time back, using intents. Now it is not working. I learned somewhere that text and image posting through intents are not allowed. I just want to confirm this is the case.
If this is true, then is the only method to post via the Facebook SDK or are there any other simple ways to do it?
What you can do is utilize the facebook graph api to do HTTP requests on behalf of the user to the facebook server using the access token.
In order to get the access token you need to implement the facebook login, you need to be familiar with oauth and oauth2 protocols for doing this.
Once you have the access token you can post the image to the facebook account at the /me/photosendpoint.
Store you image in a Bitmap. And use the following code.
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(
"https://graph.facebook.com/me/photos?access_token="
+ AccessTokens.fbaccesstoken);
MultipartEntity entity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 100, bos);
byte[] data = bos.toByteArray();
entity.addPart("source", new ByteArrayBody(data, "myImage.jpg"));
entity.addPart("message", new StringBody(caption.getText()
.toString()));
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost,localContext);
The facebook sdk is built on top of this API, the sdk considerably reduces the complexity in using these features for us developers.
P.S: Facebook has a review for any apps trying to implement oauth login. More info at https://developers.facebook.com/docs/facebook-login/review

Android login and redirect

I am trying to get some data from a webpage that needs login in a page. I could do with htmlunit but gave me problems import these libraries on Android. So I am trying to do it with apache http client.
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("https://inside.cineca.it/cgi-bin/uinside/marcature.pl");
BasicNameValuePair usernameBasicNameValuePair = new BasicNameValuePair("j_username", "user");
BasicNameValuePair passwordBasicNameValuePAir = new BasicNameValuePair("j_password", "pass");
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
nameValuePairList.add(usernameBasicNameValuePair);
nameValuePairList.add(passwordBasicNameValuePAir);
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairList);
HttpResponse httpResponse = httpClient.execute(httpPost);
System.out.println(EntityUtils.toString(httpResponse.getEntity()));
But is giving me error. I am affraid i should manage the redirect but i don't know how. I would be happy if someone could give me some advice.
Best regards
You're performing an http POST to a login page. Maybe the server that serves you back the login page doesn't know to handle the post. Anyway, I am sure your intention is to perform the login actually. You need to figure out what is the server API where you should post the credentials and process the result. Performing a quick investigation with Chrome Network profiler, the login API for above link actually resides at: https://idp-is.cineca.it/idp/Authn/Multilogin. That is the URL that you should be using and there is where you need to POST.
Also, make sure the request you're making is done on a non-UI thread as this is a common mistake done by beginners.

"Illegal Characters" in URL for HttpGet in Android get double-encoded

I am trying to find a solution to this the whole evening now...
I write an app which requests data from a web server. The Server answers in JSON format.
Everything works well except when I enter a umlaut like ä into my App.
In the following I assume the request URL is http://example.com/?q= and I am searching for "Jäger"
The correct call would then be h++p://example.com/?q=J%C3%A4ger
(Sorry for plus-signs but the spam protection doesnt let me post it correctly.)
So my problem is now:
When I give my URL String encoded or unencoded over to HttpGet it will always result in a doublee-encoded URL.
The Request to my Server is then http://example.com/?q=J%25C3%25A4ger (It encodes the percent signs)
which leads to the server searching in database for J%C3%A4ger what is obviously wrong.
So my question is how can I achive that if the user enters "Jäger" my app calls the correctly encoded URL?
Thanks for any help!
Here is the currently used code... Ist probably the worst possible idea I had...
URI url = new URI("http", "//example.com/?q=" + ((EditText)findViewById(R.id.input)).getText().toString(), null);
Log.v("MyLogTag", "API Request: " + url);
HttpGet httpGetRequest = new HttpGet(url);
// Execute the request in the client
HttpResponse httpResponse;
httpResponse = defaultClient.execute(httpGetRequest);
Update: Sorry, HttpParams isn't meant for request parameters but for configuring HttpClient.
On Android, you might want to use Uri.Builder, like suggested in this other SO answer:
Uri uri = new Uri.Builder()
.scheme("http")
.authority("example.com")
.path("someservlet")
.appendQueryParameter("param1", foo)
.appendQueryParameter("param2", bar)
.build();
HttpGet request = new HttpGet(uri.toString());
// This looks very tempting but does NOT set request parameters
// but just HttpClient configuration parameters:
// HttpParams params = new BasicHttpParams();
// params.setParameter("q", query);
// request.setParams(params);
HttpResponse response = defaultClient.execute(request);
String json = EntityUtils.toString(response.getEntity());
Outside of Android, your best bet is building the query string manually (with all the encoding hassles) or finding something similar to Android's Uri.Builder.

Categories