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

时间:2015-04-06 05:48:11

标签: android json android-volley

我尝试做的是从HttpURLConnection获取一些数据,而不是使用Volley库中的JsonObjectRequest()

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

JsonObjectRequest jsonReq = new JsonObjectRequest(Method.GET,"myURL", null, new Response.Listener<JSONObject>();

我在null更改为JSONObject后尝试将myURL更改为null。但这没有成功。

3 个答案:

答案 0 :(得分:20)

JsonObjectRequest()中的网址不是可选的,JSONObject参数用于将请求的参数发布到网址。

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

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

  

JsonObjectRequest

     

public JsonObjectRequest(int方法,                            字符串网址,                            JSONObject jsonRequest,                            Response.Listener监听器,                            Response.ErrorListener errorListener)创建一个新请求。

     

参数:

     

方法 - 使用的HTTP方法

     

url - 从

获取JSON的网址      

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

        }

    }

答案 1 :(得分:1)

    import android.app.ProgressDialog;
    import android.content.Context;
    import android.os.AsyncTask;

    import java.io.BufferedInputStream;
    import java.io.BufferedReader;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.URL;

    public class MyAsyncTask extends AsyncTask<URL, Void, String> {

        private HttpURLConnection urlConnection;
        private Context mContext;
        private ProgressDialog mDialog;
        private TaskListener mListener;

        public MyAsyncTask(Context context, TaskListener listener) {
            this.mContext = context;
            mDialog = new ProgressDialog(mContext);
            this.mListener = listener;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            mDialog.setTitle(R.string.app_name);
            mDialog.setMessage("Retrieving data...");
            mDialog.show();
        }

        @Override
        protected String doInBackground(URL... params) {
            StringBuilder result = new StringBuilder();

            try {
                URL url = params[0];
//            Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("10.0.0.1", 8080));
            urlConnection = (HttpURLConnection) url.openConnection(/*proxy*/);
                urlConnection.setDoInput(true);
                urlConnection.setConnectTimeout(20 * 1000);
                urlConnection.setReadTimeout(20 * 1000);

                if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {

                    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 s) {
            super.onPostExecute(s);
            mDialog.dismiss();
            mListener.onTaskComplete(s);
        }
    }

答案 2 :(得分:0)

使用此功能

private String getJSON(String url) {
    HttpURLConnection c = null;
    try {
        URL u = new URL(url);
        c = (HttpURLConnection) u.openConnection();
        c.setRequestMethod("GET");
        c.setRequestProperty("Content-Type", "application/json; utf-8");
        c.setRequestProperty("Accept", "application/json");
        c.connect();
        int status = c.getResponseCode();

        switch (status) {
            case 200:
            case 201:
                BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream(), "utf-8"));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                }
                br.close();
                return sb.toString();
        }

    } catch (MalformedURLException ex) {
        Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
    } finally {
        if (c != null) {
            try {
                c.disconnect();
            } catch (Exception ex) {
                Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    return null;
}