简体   繁体   中英

how to make and handle an Http Request that give a json file as response in Android?

I have a project that consists of using snowtams for aviation(displaying and decoding snowtams) and i want to make a request to a server using my api key but when i put the full link on browser the response is not a body response but a json file which is downloaded every time i make the request.How can i handle this file in code in java using Android.Could you give me a sample example of this? and thanks in advance.

an example that i tried:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_snowtam_codes);


    URL url = null;
    try {
        url = new URL("https://ajax.googleapis.com/ajax/services/feed/find?" +
                "v=1.0&q=Official%20Google%20Blog&userip=INSERT-USER-IP");
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    URLConnection connection = null;
    try {
        connection = url.openConnection();
    } catch (IOException e) {
        e.printStackTrace();
    }
    connection.addRequestProperty("Referer", "https://applications.icao.int/dataservices/api/notams- 
     realtime-list?api_key=my_api_key&format=json&criticality=1&locations=ENBO");

    StringBuilder builder = new StringBuilder();
    BufferedReader reader = null;
    try {
        reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    } catch (IOException e) {
        e.printStackTrace();
    }
    while(true) {
        String line="";
        try {
            if (!((line = reader.readLine()) != null)) break;
        } catch (IOException e) {
            e.printStackTrace();
        }
        builder.append(line);
    }

    try {
        JSONObject json = new JSONObject(builder.toString());
        System.out.println("the json object received is::"+json);
    } catch (JSONException e) {
        e.printStackTrace();
    }
  }

Have a look at Volley

You can create a custom request class to handle the file download like this:

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.toolbox.HttpHeaderParser;

import java.util.HashMap;
import java.util.Map;

public class InputStreamVolleyRequest extends Request<byte[]> {
    private final Response.Listener<byte[]> mListener;
    private Map<String, String> mParams;

    //create a static map for directly accessing headers
    public Map<String, String> responseHeaders;
    public Map<String, String> mRequestHeaders;

    public InputStreamVolleyRequest(int method, String mUrl, Response.Listener<byte[]> listener,
                                    Response.ErrorListener errorListener, HashMap<String, String> params, HashMap<String, String> requestHeaders) {
        super(method, mUrl, errorListener);
        setShouldCache(false);
        mRequestHeaders = requestHeaders;
        mListener = listener;
        mParams = params;
    }

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        mRequestHeaders.putAll(super.getHeaders());
        return mRequestHeaders;
    }

    @Override
    protected Map<String, String> getParams() {
        return mParams;
    }

    @Override
    protected void deliverResponse(byte[] response) {
        mListener.onResponse(response);
    }

    @Override
    protected Response<byte[]> parseNetworkResponse(NetworkResponse response) {
        responseHeaders = response.headers;
        return Response.success(response.data, HttpHeaderParser.parseCacheHeaders(response));
    }
}

Then use it like so:

String mUrl = "https://ajax.googleapis.com/ajax/services/feed/find?" +
        "v=1.0&q=Official%20Google%20Blog&userip=INSERT-USER-IP";
HashMap<String, String> requestHeaders = new HashMap<>();
requestHeaders.put("Referer", "https://applications.icao.int/dataservices/api/notams-realtime-list?api_key=my_api_key&format=json&criticality=1&locations=ENBO")
InputStreamVolleyRequest request = new InputStreamVolleyRequest(Request.Method.GET, mUrl,
        new Response.Listener<byte[]>() {
            @Override
            public void onResponse(byte[] response) {
                try {
                    if (response != null) {
                        JSONObject responseJsonObject = new JSONObject(new String(response));
                        // TODO do something with the JSONObject
                    }
                } catch (Exception e) {
                    Log.d("KEY_ERROR", "UNABLE TO DOWNLOAD FILE");
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {

    @Override
    public void onErrorResponse(VolleyError error) {
        // TODO handle the error
        error.printStackTrace();
    }
}, null, requestHeaders);

RequestQueue mRequestQueue = Volley.newRequestQueue(getApplicationContext(), new HurlStack());
mRequestQueue.add(request);

Update:

Ensure you have the below permissions added to your manifest:

<uses-permission android:name="android.permission.INTERNET" />

It's preferred to use AsyncHttpClient.

Example:

public void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
    (new AsyncHttpClient()).get(url, params, new JsonHttpResponseHandler() {

        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
            //handle async response callback
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            //handle async response callback
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
            //handle async response callback
        }
    });
}

Tutorial: https://guides.codepath.com/android/Using-Android-Async-Http-Client

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM