我正在尝试从android Volley框架使用自定义版本的Request类。我设法工作GET自定义请求但它失败了POST。我是ovverriding getBody()方法并返回byte []。但是,Volley抱怨连接已经开放。
代码:
@Override
public byte[] getBody() throws AuthFailureError {
JSONObject json = new JSONObject();
try {
json.put("date_in_millis", this.newsDateInMillis);
json.put("title", URLEncoder.encode(this.newsTitle.replace("\n", "").replace("\r", ""), "UTF-8"));
return new StringEntity("data=" + json.toString(), "UTF-8").toString().getBytes();
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}
例外:
05-24 21:51:08.076: E/Volley(5535): [177] NetworkDispatcher.run: Unhandled exception
java.lang.IllegalStateException: Already connected
05-24 21:51:08.076: E/Volley(5535): java.lang.IllegalStateException: Already connected
05-24 21:51:08.076: E/Volley(5535): at java.net.URLConnection.checkNotConnected(URLConnection.java:464)
05-24 21:51:08.076: E/Volley(5535): at java.net.URLConnection.setDoOutput(URLConnection.java:878)
05-24 21:51:08.076: E/Volley(5535): at com.android.volley.toolbox.HurlStack.addBodyIfExists(HurlStack.java:225)
05-24 21:51:08.076: E/Volley(5535): at com.android.volley.toolbox.HurlStack.setConnectionParametersForRequest(HurlStack.java:210)
05-24 21:51:08.076: E/Volley(5535): at com.android.volley.toolbox.HurlStack.performRequest(HurlStack.java:106)
05-24 21:51:08.076: E/Volley(5535): at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:93)
05-24 21:51:08.076: E/Volley(5535): at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:105)
有人用这种方式使用Volley Request吗?
由于
答案 0 :(得分:1)
我认为最简单的方法是从Volley \ toolbox继承JsonRequest(或JsonObjectRequest),因为那样你需要做的就是将requestBody字符串传递给超类构造函数
public JsonRequest(int method, String url, String requestBody, Listener<T> listener,
ErrorListener errorListener) {
super(method, url, errorListener);
mListener = listener;
mRequestBody = requestBody;
}
您仍然可以根据需要覆盖例如parseNetworkResponse和parseNetworkError。如果你真的需要继承Request,你应该检查JsonRequest如何实现getBody()和getBodyContentType()。