如何使用HttpURLConnection而不是Volley来获取JSON对象?

Ass*_*dow 2 android json android-volley

我想要做的是从一个数据中获取一些数据HttpURLConnection而不是使用JsonObjectRequest()Volley库.

下面是我用来从服务器获取JSON对象的代码.

JsonObjectRequest jsonReq = new JsonObjectRequest(Method.GET,"myURL", null, new Response.Listener<JSONObject>();
Run Code Online (Sandbox Code Playgroud)

我试过更改null为a JSONObjectmyURL更改为null.但这没有成功.

Dan*_*ent 20

url in JsonObjectRequest()不是可选的,JSONObject参数用于将请求的参数发布到url.

从文档:http: //afzaln.com/volley/com/android/volley/toolbox/JsonObjectRequest.html

http://developer.android.com/training/volley/index.html

JsonObjectRequest

public JsonObjectRequest(int方法,String url,JSONObject jsonRequest,Response.Listener侦听器,Response.ErrorListener errorListener)创建新请求.

参数:

method - 要使用的HTTP方法

url - 从中​​获取JSON的URL

jsonRequest - 要发布的JSONObject.允许Null,表示不会随请求一起发布参数.

listener - 侦听器以接收JSON响应

errorListener - 错误侦听器,或null以忽略错误.

使用HttpURLConnection:

http://developer.android.com/reference/java/net/HttpURLConnection.html

代码将是这样的:

 public class getData extends AsyncTask<String, String, String> {

        HttpURLConnection urlConnection;

        @Override
        protected String doInBackground(String... args) {

            StringBuilder result = new StringBuilder();

            try {
                URL url = new URL("https://api.github.com/users/dmnugent80/repos");
                urlConnection = (HttpURLConnection) url.openConnection();
                InputStream in = new BufferedInputStream(urlConnection.getInputStream());

                BufferedReader reader = new BufferedReader(new InputStreamReader(in));

                String line;
                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }

            }catch( Exception e) {
                e.printStackTrace();
            }
            finally {
                urlConnection.disconnect();
            }


            return result.toString();
        }

        @Override
        protected void onPostExecute(String result) {

            //Do something with the JSON string

        }

    }
Run Code Online (Sandbox Code Playgroud)