我是新来的Android工作室,我试图从Github的API(例如https://api.github.com/users/froala),并显示在我的应用程序请求API数据。高效的方式/正确的方法来检索JSON数据
我不知何故应用做检索来自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。有关第二个查询的更多信息,请参阅http://www.vogella.com/tutorials/JavaLibrary-Gson/article.html – bond007
,此网址是正确的,但您面临服务器端的一些错误,如403状态码。在restclient或postman中检查相同的网址。并添加需要的标题发送成功的请求 – bond007
@ bond007你是什么意思添加需要的标题?我对这个东西很陌生。你能解释还是帮忙? – user6792790