我试图使用Volley安卓库发出GET请求,但当我这样做时,我检查服务器并收到请求,但参数不是。我用POST和GET尝试了这个,但没有一个有效。这是我的代码
StringRequest stringRequest = new StringRequest(Request.Method.GET, all ,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Toast.makeText(MainActivity.this,response,Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this,error.toString(),Toast.LENGTH_LONG).show();
}
}){
@Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("t","inVLlhZ0I29tPpoLGpBO9KzVI0zM-3ED3KiTcAuCUJ65TBbUZBnmCg");
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
我也尝试使用类并创建自定义请求并覆盖类中的getParams方法,但结果相同。
这是我使用的自定义请求类:
public class CustomRequest extends Request<JSONObject> {
private Listener<JSONObject> listener;
private Map<String, String> params;
public CustomRequest(String url, Map<String, String> params,
Listener<JSONObject> reponseListener, ErrorListener errorListener) {
super(Method.GET, url, errorListener);
this.listener = reponseListener;
this.params = params;
}
public CustomRequest(int method, String url, Map<String, String> params,
Listener<JSONObject> reponseListener, ErrorListener errorListener) {
super(method, url, errorListener);
this.listener = reponseListener;
this.params = params;
}
protected Map<String, String> getParams()
throws com.android.volley.AuthFailureError {
return params;
};
@Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONObject(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
@Override
protected void deliverResponse(JSONObject response) {
// TODO Auto-generated method stub
listener.onResponse(response);
}
}
答案 0 :(得分:0)
感谢我收到的答案,我找到了一个解决方案,即将我需要的参数附加到网址上:
String url = String.format(myUrl +“? nameOfParameter =%1 $ s”, parameterContent );
因此,如果需要使用此参数(“t”,“1234”)进行GET请求,其网址等于www.mypage.com/request/
我会写下面的内容(该页面应该来自一个属性,但我写的是为了解释这个想法);
public void request() {
String url = String.format("www.mypage.com/request/" + "?t=%1$s","1234");
StringRequest stringRequest = new StringRequest(Request.Method.GET, pos ,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// Code here
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// Code here
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}