且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用HttpURLConnection的,而不是凌空获得JSON对象?

更新时间:2023-01-17 16:43:52

JsonObjectRequest网址()不可选的,JSONObject的参数是用来发布的参数与请求的URL。

The url in JsonObjectRequest() is not optional, and the JSONObject parameter is used to post parameters with the request to the url.

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

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

JsonObjectRequest

JsonObjectRequest

公共JsonObjectRequest(INT方法,                            字符串URL,                            的JSONObject jsonRequest,                            Response.Listener监听器,                            Response.ErrorListener errorListener)创建一个新的请求。

public JsonObjectRequest(int method, String url, JSONObject jsonRequest, Response.Listener listener, Response.ErrorListener errorListener) Creates a new request.

参数:

方法 - HTTP方法使用

method - the HTTP method to use

URL - URL从

url - URL to fetch the JSON from

jsonRequest - 一个JSONObject的发布与请求。空是允许的   并表示没有参数,将张贴与要求。

jsonRequest - A JSONObject to post with the request. Null is allowed and indicates no parameters will be posted along with request.

监听器 - 监听器接收JSON响应

listener - Listener to receive the JSON response

errorListener - 错误监听,或者为null,忽略错误

errorListener - Error listener, or null to ignore errors.

使用的HttpURLConnection

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

在code将是这样的:

The code would be something like this:

 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

        }

    }