Reputation: 33
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();
}
}
Upvotes: 2
Views: 259
Reputation: 36423
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" />
Upvotes: 2
Reputation: 639
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
Upvotes: 1