Volley – POST / GET参数

我看到了Google IO 2013会议关于Volley的问题,我正在考虑切换到抽象。 Volley是否支持添加POST / GET参数来请求? 如果是,我该怎么办?

在您的Request类(扩展Request)中,重写getParams()方法。 你会做同样的标题,只是重写getHeaders()。

如果您在Volleytesting中的TestRequest.java中查看PostWithBody类,则会find一个示例。 它是这样的

 public class LoginRequest extends Request<String> { // ... other methods go here private Map<String, String> mParams; public LoginRequest(String param1, String param2, Listener<String> listener, ErrorListener errorListener) { super(Method.POST, "http://test.url", errorListener); mListener = listener; mParams = new HashMap<String, String>(); mParams.put("paramOne", param1); mParams.put("paramTwo", param2); } @Override public Map<String, String> getParams() { return mParams; } } 

埃文·查尔顿(Evan Charlton)做了一个快速示例项目,向我们展示了如何使用排球。 https://github.com/evancharlton/folly/

对于GET参数有两个select:

首先 :正如在下面的评论中所build议的那样,您可以使用String并使用它们的值replace参数占位符,如下所示:

 String uri = String.format("http://somesite.com/some_endpoint.php?param1=%1$s&param2=%2$s", num1, num2); StringRequest myReq = new StringRequest(Method.GET, uri, createMyReqSuccessListener(), createMyReqErrorListener()); queue.add(myReq); 

其中num1和num2是包含您的值的stringvariables。

第二 :如果你使用更新的外部HttpClient (例如4.2.x),你可以使用URIBuilder来build立你的Uri。 好处是,如果你的uristring已经有了参数,那么将它传递给URIBuilder ,然后使用ub.setQuery(URLEncodedUtils.format(getGetParams(), "UTF-8")); 添加您的附加参数。 这样你就不会麻烦检查是否“?” 已经被添加到uri中,或者错过了一些消除潜在错误的来源。

对于POST参数可能有时会比接受的答案更容易做到这一点:

 StringRequest myReq = new StringRequest(Method.POST, "http://somesite.com/some_endpoint.php", createMyReqSuccessListener(), createMyReqErrorListener()) { protected Map<String, String> getParams() throws com.android.volley.AuthFailureError { Map<String, String> params = new HashMap<String, String>(); params.put("param1", num1); params.put("param2", num2); return params; }; }; queue.add(myReq); 

例如只是重写getParams()方法。

您可以在Andorid Volley示例项目中find一个工作示例(以及许多其他基本Volley示例)。

CustomRequest是解决Volley的JSONObjectRequest不能像StringRequest一样发布参数的一种方法

这里是允许添加参数的帮助器类:

  import java.io.UnsupportedEncodingException; import java.util.Map; import org.json.JSONException; import org.json.JSONObject; import com.android.volley.NetworkResponse; import com.android.volley.ParseError; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.Response.ErrorListener; import com.android.volley.Response.Listener; import com.android.volley.toolbox.HttpHeaderParser; 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); } } 

感谢Greenchiu

此帮助程序类pipe理GETPOST请求的参数:

 import java.io.UnsupportedEncodingException; import java.util.Iterator; import java.util.Map; import org.json.JSONException; import org.json.JSONObject; import com.android.volley.NetworkResponse; import com.android.volley.ParseError; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.Response.ErrorListener; import com.android.volley.Response.Listener; import com.android.volley.toolbox.HttpHeaderParser; public class CustomRequest extends Request<JSONObject> { private int mMethod; private String mUrl; private Map<String, String> mParams; private Listener<JSONObject> mListener; public CustomRequest(int method, String url, Map<String, String> params, Listener<JSONObject> reponseListener, ErrorListener errorListener) { super(method, url, errorListener); this.mMethod = method; this.mUrl = url; this.mParams = params; this.mListener = reponseListener; } @Override public String getUrl() { if(mMethod == Request.Method.GET) { if(mParams != null) { StringBuilder stringBuilder = new StringBuilder(mUrl); Iterator<Map.Entry<String, String>> iterator = mParams.entrySet().iterator(); int i = 1; while (iterator.hasNext()) { Map.Entry<String, String> entry = iterator.next(); if (i == 1) { stringBuilder.append("?" + entry.getKey() + "=" + entry.getValue()); } else { stringBuilder.append("&" + entry.getKey() + "=" + entry.getValue()); } iterator.remove(); // avoids a ConcurrentModificationException i++; } mUrl = stringBuilder.toString(); } } return mUrl; } @Override protected Map<String, String> getParams() throws com.android.volley.AuthFailureError { return mParams; }; @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 mListener.onResponse(response); } } 

处理GET参数我重复了Andrea Motto的解决scheme。 问题是Volley多次调用GetUrl ,他的解决scheme使用迭代器破坏了原始的Map对象。 随后的Volley内部调用有一个空的params对象。

我也加了参数的编码。

这是一个内联使用(无子类)。

 public void GET(String url, Map<String, String> params, Response.Listener<String> response_listener, Response.ErrorListener error_listener, String API_KEY, String stringRequestTag) { final Map<String, String> mParams = params; final String mAPI_KEY = API_KEY; final String mUrl = url; StringRequest stringRequest = new StringRequest( Request.Method.GET, mUrl, response_listener, error_listener ) { @Override protected Map<String, String> getParams() { return mParams; } @Override public String getUrl() { StringBuilder stringBuilder = new StringBuilder(mUrl); int i = 1; for (Map.Entry<String,String> entry: mParams.entrySet()) { String key; String value; try { key = URLEncoder.encode(entry.getKey(), "UTF-8"); value = URLEncoder.encode(entry.getValue(), "UTF-8"); if(i == 1) { stringBuilder.append("?" + key + "=" + value); } else { stringBuilder.append("&" + key + "=" + value); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } i++; } String url = stringBuilder.toString(); return url; } @Override public Map<String, String> getHeaders() { Map<String, String> headers = new HashMap<>(); if (!(mAPI_KEY.equals(""))) { headers.put("X-API-KEY", mAPI_KEY); } return headers; } }; if (stringRequestTag != null) { stringRequest.setTag(stringRequestTag); } mRequestQueue.add(stringRequest); } 

这个函数使用头来传递一个APIKEY,并设置一个TAG给这个有用的请求,在它完成前取消它。

希望这可以帮助。

这可能会帮助你…

 private void loggedInToMainPage(final String emailName, final String passwordName) { String tag_string_req = "req_login"; StringRequest stringRequest = new StringRequest(Request.Method.POST, "http://localhost/index", new Response.Listener<String>() { @Override public void onResponse(String response) { Log.d(TAG, "Login Response: " + response.toString()); try { JSONObject jsonObject = new JSONObject(response); Boolean error = jsonObject.getBoolean("error"); if (!error) { String uid = jsonObject.getString("uid"); JSONObject user = jsonObject.getJSONObject("user"); String email = user.getString("email"); String password = user.getString("password"); session.setLogin(true); Intent intent = new Intent(getApplicationContext(), MainActivity.class); startActivity(intent); finish(); Toast.makeText(getApplicationContext(), "its ok", Toast.LENGTH_SHORT).show(); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError volleyError) { System.out.println("volley Error ................."); } }) { @Override protected Map<String, String> getParams() throws AuthFailureError { Map<String, String> params = new HashMap<String, String>(); params.put("tag", "login"); params.put("email", emailName); params.put("password", passwordName); return params; } }; MyApplication.getInstance().addToRequestQueue(stringRequest,tag_string_req); } 

对于未来的读者

我喜欢和Volley一起工作。 为了节省开发时间,我试着写一个小方便的库Gloxey Netwok Manager来设置我的项目Volley。 它包括JSONparsing器和其他不同的方法来帮助检查networking可用性。

使用ConnectionManager.class可以使用Volley StringVolley JSON请求的不同方法。 您可以使用或不使用标题来请求GET,PUT,POST,DELETE 。 你可以在这里阅读完整的文档。

把这行放在你的gradle文件中。

  dependencies { compile 'io.gloxey.gnm:network-manager:1.0.1' } 

排球StringRequest

方法GET(无标题)

  ConnectionManager.volleyStringRequest(context, isDialog, progressDialogView, requestURL, volleyResponseInterface); 

如何使用?

  Configuration Description Context Context isDialog If true dialog will appear, otherwise not. progressView For custom progress view supply your progress view id and make isDialog true. otherwise pass null. requestURL Pass your API URL. volleyResponseInterface Callback for response. 

  ConnectionManager.volleyStringRequest(this, false, null, "url", new VolleyResponse() { @Override public void onResponse(String _response) { /** * Handle Response */ } @Override public void onErrorResponse(VolleyError error) { /** * handle Volley Error */ } @Override public void isNetwork(boolean connected) { /** * True if internet is connected otherwise false */ } }); 

排球StringRequest

方法POST / PUT / DELETE(无标题)

  ConnectionManager.volleyStringRequest(context, isDialog, progressDialogView, requestURL, requestMethod, params, volleyResponseInterface); 

 Use Method : Request.Method.POST Request.Method.PUT Request.Method.DELETE Your params : HashMap<String, String> params = new HashMap<>(); params.put("param 1", "value"); params.put("param 2", "value"); ConnectionManager.volleyStringRequest(this, true, null, "url", Request.Method.POST, params, new VolleyResponse() { @Override public void onResponse(String _response) { /** * Handle Response */ } @Override public void onErrorResponse(VolleyError error) { /** * handle Volley Error */ } @Override public void isNetwork(boolean connected) { /** * True if internet is connected otherwise false */ } }); 

奖金

Gloxey JSONparsing器

随意使用gloxey jsonparsing器来parsing你的api响应。

  YourModel yourModel = GloxeyJsonParser.getInstance().parse(stringResponse, YourModel.class); 

 ConnectionManager.volleyStringRequest(this, false, null, "url", new VolleyResponse() { @Override public void onResponse(String _response) { /** * Handle Response */ try { YourModel yourModel = GloxeyJsonParser.getInstance().parse(_response, YourModel.class); } catch (Exception e) { e.printStackTrace(); } } @Override public void onErrorResponse(VolleyError error) { /** * handle Volley Error */ if (error instanceof TimeoutError || error instanceof NoConnectionError) { showSnackBar(parentLayout, getString(R.string.internet_not_found), getString(R.string.retry), new View.OnClickListener() { @Override public void onClick(View view) { //handle retry button } }); } else if (error instanceof AuthFailureError) { } else if (error instanceof ServerError) { } else if (error instanceof NetworkError) { } else if (error instanceof ParseError) { } } @Override public void isNetwork(boolean connected) { /** * True if internet is connected otherwise false */ if (!connected) { showSnackBar(parentLayout, getString(R.string.internet_not_found), getString(R.string.retry), new View.OnClickListener() { @Override public void onClick(View view) { //Handle retry button } }); } }); public void showSnackBar(View view, String message) { Snackbar.make(view, message, Snackbar.LENGTH_LONG).show(); } public void showSnackBar(View view, String message, String actionText, View.OnClickListener onClickListener) { Snackbar.make(view, message, Snackbar.LENGTH_LONG).setAction(actionText, onClickListener).show(); }