我开始使用Android Studio了,我想制作一个简单的应用程序来从URL中获取原始HTML。我已经使用http://developer.android.com/training/volley/simple.html上的基本示例设置了Volley来执行此操作,该示例适用于公共网址。
我想要访问的网址需要特定的标头和Cookie,我手头有静态值。如何将这些值分配给我的请求?
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);
}
编辑:
我能够应用How are cookies passed in the HTTP protocol?的解决方案手动设置我的请求标头。
答案 0 :(得分:1)
使用此处的解决方案How are cookies passed in the HTTP protocol?手动为您的请求设置标头。我的代码最终看起来像这样:
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;
}
}
并在相关活动中......
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);
}