java—如何在android中生成和处理一个http请求,并将json文件作为响应?

iszxjhcz  于 2021-07-08  发布在  Java
关注(0)|答案(2)|浏览(650)

我有一个项目,其中包括使用snowtams的航空(显示和解码snowtams),我想提出一个请求,以服务器使用我的api键,但当我把浏览器上的完整链接,响应不是一个身体的响应,而是一个json文件,这是我每次下载的请求。我如何处理这个文件在java代码中使用你能给我举个例子吗?先谢谢你。

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();
    }
  }
vawmfj5a

vawmfj5a1#

看一下凌空抽射
您可以创建一个自定义请求类来处理文件下载,如下所示:

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));
    }
}

然后像这样使用:

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);

更新:
确保已将以下权限添加到清单中: <uses-permission android:name="android.permission.INTERNET" />

gzjq41n4

gzjq41n42#

最好使用asynchttpclient。
例子:

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
        }
    });
}

辅导的:https://guides.codepath.com/android/using-android-async-http-client

相关问题