gpt4 book ai didi

android - 在 Android 上使用 HTTPURLConnection 从 URL 获取 JSON 对象

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:49:51 24 4
gpt4 key购买 nike

我目前正在尝试访问我的 Android 应用程序上的 JSON 对象。但是,我不断收到以下错误:

android.os.NetworkOnMainThreadException

通过稍微研究一下,我目前唯一的信息是我需要异步执行此操作(?)

这是我的代码:

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView dynamictext;
dynamictext = (TextView) findViewById(R.id.dynamictext);
dynamictext.setText(getJSON("my url here"));

}


public String getJSON(String url) {
HttpURLConnection c = null;
try {
URL u = new URL(url);
c = (HttpURLConnection) u.openConnection();
c.connect();
int status = c.getResponseCode();
switch (status) {
case 200:
case 201:
BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
br.close();
return sb.toString();
}

} catch (Exception ex) {
return ex.toString();
} finally {
if (c != null) {
try {
c.disconnect();
} catch (Exception ex) {
//disconnect error
}
}
}
return null;
}
}

提前致谢

最佳答案

我建议阅读此网址 https://stackoverflow.com/a/6343299/2530660



添加异步任务;

public class TestAsyncTask extends AsyncTask<Void, Void, String> {
private Context mContext;
private String mUrl;

public TestAsyncTask(Context context, String url) {
mContext = context;
mUrl = url;
}

@Override
protected void onPreExecute() {
super.onPreExecute();
dynamictext = (TextView) findViewById(R.id.dynamictext);
}

@Override
protected String doInBackground(Void... params) {
String resultString = null;
resultString = getJSON(mUrl);

return resultString;
}

@Override
protected void onPostExecute(String strings) {
super.onPostExecute(strings);
dynamictext.setText(strings);
}

private String getJSON(String url) { ... }
}

使用异步任务;

public class MainActivity ... {
private TextView dynamictest;

onCreate() {
...
TestAsyncTask testAsyncTask = new TestAsyncTask(MainActivity.this, "my url here");
testAsyncTask.execute();
}
}

关于android - 在 Android 上使用 HTTPURLConnection 从 URL 获取 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33115261/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com