我创建了一个应用程序,其中我想列出我的所有关注者。为此我必须通过twitter api,
https://api.twitter.com/1/followers/ids.json?cursor=-1&screen_name=twitterapi
我正在研究它,我尝试下面的代码来获取它的响应,
HttpPost post = new HttpPost("https://api.twitter.com/1/followers/ids.json?cursor=-1&screen_name=twitterapi");
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
String responseText = EntityUtils.toString(entity);
Log.i(TAG,"Response---"+responseText);
并且该日志打印如下,
Response---{"error":"\u0907\u0938 \u0935\u093f\u0927\u093f \u0915\u094b \u091c\u0940\u0908\u091f\u0940 \u0915\u0940 \u0906\u0935\u0936\u094d\u092f\u0915\u0924\u093e \u0939\u0948.","request":"\/1\/followers\/ids.json?cursor=-1&screen_name=twitterapi"}
你能告诉我从中获取响应的正确方法,所以我可以获取Json数组吗?
提前致谢。
答案 0 :(得分:2)
使用以下代码......
首先创建主类,
public class FollowersData
{
String url = "http://api.twitter.com/1/followers/ids.json?screen_name=twitterapi";
private String[] s;
public void FollowersIdDetails()
{
InputStream source = retrieveStream(url);
Gson gson = new Gson();
Reader reader = new InputStreamReader(source);
SearchResponse response = gson.fromJson(reader, SearchResponse.class);
s = response.getTwitterUserId();
}
private InputStream retrieveStream(String url)
{
DefaultHttpClient client = new DefaultHttpClient();
HttpGet getRequest = new HttpGet(url);
try
{
HttpResponse getResponse = client.execute(getRequest);
final int statusCode = getResponse.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK)
{
Log.w(getClass().getSimpleName(), "Error " + statusCode + " for URL " + url);
return null;
}
HttpEntity getResponseEntity = getResponse.getEntity();
return getResponseEntity.getContent();
}
catch (IOException e)
{
getRequest.abort();
Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
}
return null;
}
}
比创建第二个类进行解析,
public class SearchResponse
{
@SerializedName("ids")
private String[] twitterUserId;
public String[] getTwitterUserId()
{
return twitterUserId;
}
public void setTwitterUserId(String[] twitterUserId)
{
this.twitterUserId = twitterUserId;
}
}
最后,您将在主类中获得响应(String [] s).... :)