Reputation: 21
I'm getting started working with Android Studio, and I'd like to make a simple application to grab raw HTML from a URL. I've set up Volley to do this using the basic example at http://developer.android.com/training/volley/simple.html, which works fine for public URLs.
The URL I want to access requires specific headers and cookies, which I have the static values of on hand. How can I assign these values to my request?
public void grabHTML(View view) {
RequestQueue queue = Volley.newRequestQueue(this);
String url = getString(R.string.urlpath);
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
mTextView.setText(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
mTextView.setText(error.getMessage());
}
});
queue.add(stringRequest);
}
EDIT:
I was able to apply the solution from How are cookies passed in the HTTP protocol? to manually set my request headers.
Upvotes: 1
Views: 1719
Reputation: 21
Use the solution How are cookies passed in the HTTP protocol? here to manually set headers to your request. My code ended up looking like this:
package com.pesonal.webrequestexample;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;
import java.util.HashMap;
import java.util.Map;
public class StringRequestWithCookies extends StringRequest {
private Map<String, String> cookies;
public StringRequestWithCookies(String url, Map<String, String> cookies, Response.Listener<String> listener, Response.ErrorListener errorListener) {
super(Request.Method.GET, url, listener, errorListener);
this.cookies = cookies;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("header1","value");
headers.put("header2","value");
return headers;
}
}
and in the relevant activity...
public void grabHTML(View view) {
String url = getString(R.string.urlpath);
RequestQueue queue = Volley.newRequestQueue(this);
StringRequestWithCookies stringRequest = new StringRequestWithCookies(
url,getCookies(),
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
mTextView.setText(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
mTextView.setText(error.getMessage());
}
});
queue.add(stringRequest);
}
Upvotes: 1