我正在尝试使用 this API在我的 Android 应用程序中。很简单,你给它一个tiny URL并返回原来的。
这是我第一次使用 API。所以,这就是我的做法:
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");
}
我的问题是:
- 使用
HttpGet
是处理 API 的正确方法吗? - 如果是, 那么我在那里犯了什么错误?我的 TextView 中总是出现“异常”。
最佳答案
确保在转换字符串时将“resEntityget”分配给字符串并重新使用该字符串,而不是尝试再次转换它。这样做会导致错误。
试试这个:
if (resEntityGet != null) {
String response = EntityUtils.toString(resEntityGet);
Log.i("GET RESPONSE",response);
output.setText(response); //This is a TextView
}
关于android - 如何在 Android 中使用 API?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9673638/