How do I use the API in Android?
I am trying to use this API in my android app. It's very simple, you give a tiny URL and it returns the original one.
This is the first time I use the API. So, this is how I did it:
try {
HttpClient client = new DefaultHttpClient();
String url = "http://tiny.pl/htk" //The tiny URL
String getURL = "http://untiny.me/api/1.0/extract?url="+url+"&format=text"; //The API service URL
HttpGet get = new HttpGet(getURL);
HttpResponse responseGet = client.execute(get);
HttpEntity resEntityGet = responseGet.getEntity();
if (resEntityGet != null) {
//do something with the response
Log.i("GET RESPONSE",EntityUtils.toString(resEntityGet));
output.setText(EntityUtils.toString(resEntityGet)); //This is a TextView
}
else {
output.setText("null reponse");
}
} catch(Exception e) {
output.setText("exception");
}
My questions:
HttpGet
Is using the correct way to work with APIs?- If so, what mistakes did I make there? I always get an "exception" in my TextView.
source to share
Make sure you assign the string "resEntityget" when you convert it and reuse the string rather than trying to convert it again. This will lead to errors.
Try the following:
if (resEntityGet != null) {
String response = EntityUtils.toString(resEntityGet);
Log.i("GET RESPONSE",response);
output.setText(response); //This is a TextView
}
source to share
Is using HttpGet the correct way to work with the API?
YES
If so, what mistakes did I make there? I always get an "exception" in my TextView. :
because you are passing the wrong url to HttpGet
The right way:
Fist Add url parameters to url:
YOUR NEEDED:
String strurl="http://stackoverflow.com/questions/tagged/android?page=5&sort=newest&pagesize=15";
USE TinyURL "API":
HttpClient httpclient = new DefaultHttpClient();
HttpGet httppost = new HttpGet("http://tinyurl.com/api-create.php");
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("url",strurl));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntityGet = response.getEntity();
tinyUrl=EntityUtils.toString(resEntityGet);
Now to use this url means tinyUrl as:
try {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(tinyUrl);
HttpResponse responseGet = client.execute(get);
HttpEntity resEntityGet = responseGet.getEntity();
if (resEntityGet != null) {
//do something with the response
Log.i("GET RESPONSE",EntityUtils.toString(resEntityGet));
output.setText(EntityUtils.toString(resEntityGet)); //This is a TextView
}
else {
output.setText("null reponse");
}
} catch(Exception e) {
output.setText("exception");
}
OR IF YOU WANT TO USE A STATIC URL, CONFIRM ENCODE tinyurl URL with parameters, then go to HttpGet()
DONE!
source to share