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

前端之家收集整理的这篇文章主要介绍了在android上使用HTTPURLConnection从URL获取JSON对象前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我目前正在尝试访问我的 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

添加AsyncTask;

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) { ... }
}

使用AsyncTask;

public class MainActivity ... {
    private TextView dynamictest;

    onCreate() {
        ...
        TestAsyncTask testAsyncTask = new TestAsyncTask(MainActivity.this,"my url here");
        testAsyncTask.execute();
    }
}
原文链接:https://www.f2er.com/android/308756.html

猜你在找的Android相关文章