【发布时间】:2018-04-02 05:57:49
【问题描述】:
我是 Android Studio 新手,我正在尝试从 Github API(例如https://api.github.com/users/froala)请求 API 数据并显示在我的应用中。
我以某种方式使应用程序从 API 中检索 JSON:
public class MainActivity extends AppCompatActivity {
private TextView tvData;
private static final String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate: Starting.");
// Set up the ViewPager with the sections adapter
// Github tab
Button buttonHit = (Button) findViewById(R.id.buttonHit);
tvData = (TextView) findViewById(R.id.tvJsonItem);
buttonHit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new JSONTask().execute("https://api.github.com/users/froala");
}
});
}
public class JSONTask extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
// Pass in a String and convert to URL
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
// for reading data line by line
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer strBuffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
strBuffer.append(line);
}
// If we are able to get the data
String retreivedJson = strBuffer.toString();
JSONObject parentObject = new JSONObject(retreivedJson);
JsonReader jsonReader = new JsonReader(responseBody);
return retreivedJson;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
//cant close null
if (connection != null) {
// close both connection and the reader
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
tvData.setText(result);
}
}
}
看起来像:
现在我只需要使用它来解析 JSON。但问题是,当我在 JSON 中使用不同的 URL(如 https://api.github.com/users/froala/repos)时,检索 JSON 数据不起作用,并且在单击按钮时应用程序不显示任何内容。这很奇怪,因为 /users/id 页面和 /users/id/repos 页面都是 JSON,看起来并没有什么不同。我不知道为什么另一个不起作用。
两个问题:
- 我是否使用正确的方式从 API 中检索 JSON?
- 为什么其他链接 (https://api.github.com/users/froala/repos) 不适用于我的代码实现?
请帮忙!我真的很困惑。
【问题讨论】:
-
您可以使用 json 到 java 转换的库,如 gson、jackson。欲了解更多信息vogella.com/tutorials/JavaLibrary-Gson/article.html
-
对于您的第二次查询,此网址是正确的,但您正面临来自服务器端的一些错误,例如 403 状态码。在 restclient 或 postman 中检查相同的 url。并添加所需的标头以发送成功的请求
-
@bond007 添加所需的标题是什么意思?我对这些东西很陌生。你能解释一下或帮忙吗?
-
您可以安装 google chrome 插件 rest 客户端并尝试直接从那里发送请求并查看响应,它可能涉及添加一些标头作为请求的一部分,以便返回 200。访问此链接到添加表头stackoverflow.com/questions/12732422/…