如何从 HTTP 获取字符串并使用它来构建 JSON 对象?
How to get a String from HTTP and use it to build a JSON Object?
我尝试从 HTTP 服务器获取字符串(实际上是 JSON 文件)来存储有关 Twitch 流的数据。
连接得到的字符串:api.twitch.tv/kraken/streams/lainkk
我想在 String 变量中获取这个 String 并从这个 String 构建一个 JSON 对象。
我写了一些方法,但在调用这些方法时总是在日志中出现 SystemErr:
这是我自己的 Twitch API class :
package com.linkpulsion.bibix;
import android.util.Log;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class Twitch {
private String channel;
public final static String TWITCH_API_SERVER = "https://api.twitch.tv/kraken/";
/**
* Constructor of Java Twitch API Json Generator
* @param channel The cannel name to get the infos
*/
public Twitch(String channel){
if(channel != null){
this.channel = channel;
}
}
/**
* Getter for channel name
* @return String the channel name
*/
public String getChannel(){
return this.channel;
}
protected String getJson(String mode){
String apiUri = TWITCH_API_SERVER + mode + "/" + this.channel;
try{
URL website = new URL(apiUri);
URLConnection connection = website.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder response = new StringBuilder();
String inputLine;
while ((inputLine = in.readLine()) != null)
response.append(inputLine);
in.close();
return response.toString();
}catch (Exception e){
e.printStackTrace();
return null;
}
}
protected JSONObject buildJSON(String jsonRaw){
JSONObject json = null;
try{
json = new JSONObject(jsonRaw);
}catch (Exception e){
e.printStackTrace();
}
return json;
}
public void isSreaming(){
String jsonRaw = getJson("streams");
Log.d(null,"RETOUR " + jsonRaw);
}
}
谢谢!
我 运行 你的原始代码并得到一个 NetworkOnMainThreadException。
我制作了一个简单的 AsyncTask,它成功了:
private class TwitchAsync extends AsyncTask<Void, Void, String> {
@Override
protected String doInBackground(Void... params) {
String str = twitch.getJson("streams");
return str;
}
@Override
protected void onPostExecute(String result){
Toast.makeText(MainActivity.this, "result: " + result, Toast.LENGTH_LONG).show();
//testing buildJSON:
JSONObject obj = twitch.buildJSON(result);
Log.d("JSON Result: ", obj.toString());
}
}
这是完整的 class 我用来测试的:
public class MainActivity extends AppCompatActivity {
Twitch twitch;
JSONObject jsonObj; //instance variable which can be accessed anywhere in the class code
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
twitch = new Twitch("aksynial");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
System.out.println("REFRESHING");
new TwitchAsync().execute();
return true;
}
return super.onOptionsItemSelected(item);
}
private class TwitchAsync extends AsyncTask<Void, Void, String> {
@Override
protected String doInBackground(Void... params) {
String str = twitch.getJson("streams");
return str;
}
@Override
protected void onPostExecute(String result){
Toast.makeText(MainActivity.this, "result: " + result, Toast.LENGTH_LONG).show();
//testing buildJSON:
//assign to the instance variable jsonObj
jsonObj = twitch.buildJSON(result);
Log.d("JSON Result: ", jsonObj.toString());
}
}
}
在 onPostExecute()
中记录结果:
D/JSON Result:﹕ {"_links":{"channel":"https:\/\/api.twitch.tv\/kraken\/channels\/aksynial","self":"https:\/\/api.twitch.tv\/kraken\/streams\/aksynial"},"stream":null}
我尝试从 HTTP 服务器获取字符串(实际上是 JSON 文件)来存储有关 Twitch 流的数据。
连接得到的字符串:api.twitch.tv/kraken/streams/lainkk
我想在 String 变量中获取这个 String 并从这个 String 构建一个 JSON 对象。
我写了一些方法,但在调用这些方法时总是在日志中出现 SystemErr:
这是我自己的 Twitch API class :
package com.linkpulsion.bibix;
import android.util.Log;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class Twitch {
private String channel;
public final static String TWITCH_API_SERVER = "https://api.twitch.tv/kraken/";
/**
* Constructor of Java Twitch API Json Generator
* @param channel The cannel name to get the infos
*/
public Twitch(String channel){
if(channel != null){
this.channel = channel;
}
}
/**
* Getter for channel name
* @return String the channel name
*/
public String getChannel(){
return this.channel;
}
protected String getJson(String mode){
String apiUri = TWITCH_API_SERVER + mode + "/" + this.channel;
try{
URL website = new URL(apiUri);
URLConnection connection = website.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder response = new StringBuilder();
String inputLine;
while ((inputLine = in.readLine()) != null)
response.append(inputLine);
in.close();
return response.toString();
}catch (Exception e){
e.printStackTrace();
return null;
}
}
protected JSONObject buildJSON(String jsonRaw){
JSONObject json = null;
try{
json = new JSONObject(jsonRaw);
}catch (Exception e){
e.printStackTrace();
}
return json;
}
public void isSreaming(){
String jsonRaw = getJson("streams");
Log.d(null,"RETOUR " + jsonRaw);
}
}
谢谢!
我 运行 你的原始代码并得到一个 NetworkOnMainThreadException。
我制作了一个简单的 AsyncTask,它成功了:
private class TwitchAsync extends AsyncTask<Void, Void, String> {
@Override
protected String doInBackground(Void... params) {
String str = twitch.getJson("streams");
return str;
}
@Override
protected void onPostExecute(String result){
Toast.makeText(MainActivity.this, "result: " + result, Toast.LENGTH_LONG).show();
//testing buildJSON:
JSONObject obj = twitch.buildJSON(result);
Log.d("JSON Result: ", obj.toString());
}
}
这是完整的 class 我用来测试的:
public class MainActivity extends AppCompatActivity {
Twitch twitch;
JSONObject jsonObj; //instance variable which can be accessed anywhere in the class code
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
twitch = new Twitch("aksynial");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
System.out.println("REFRESHING");
new TwitchAsync().execute();
return true;
}
return super.onOptionsItemSelected(item);
}
private class TwitchAsync extends AsyncTask<Void, Void, String> {
@Override
protected String doInBackground(Void... params) {
String str = twitch.getJson("streams");
return str;
}
@Override
protected void onPostExecute(String result){
Toast.makeText(MainActivity.this, "result: " + result, Toast.LENGTH_LONG).show();
//testing buildJSON:
//assign to the instance variable jsonObj
jsonObj = twitch.buildJSON(result);
Log.d("JSON Result: ", jsonObj.toString());
}
}
}
在 onPostExecute()
中记录结果:
D/JSON Result:﹕ {"_links":{"channel":"https:\/\/api.twitch.tv\/kraken\/channels\/aksynial","self":"https:\/\/api.twitch.tv\/kraken\/streams\/aksynial"},"stream":null}