我使用Volley作为我的http客户端库。 我需要发送有效载荷原始数据作为Volley的请求的一部分吗? 有一些帖子,如:How to send Request payload to REST API in java?
但是如何使用Volley实现这一目标?
答案 0 :(得分:1)
示例:
final TextView mTextView = (TextView) findViewById(R.id.text);
...
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://www.google.com";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
mTextView.setText("Response is: "+ response.substring(0,500));
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
mTextView.setText("That didn't work!");
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
检查the source and more info here
**更新:**如果你需要添加参数,你可以简单地覆盖getParams()
示例:
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("param1", "val1");
params.put("randomFieldFilledWithAwkwardCharacters","{{%stuffToBe Escaped/");
return params;
}
你不需要覆盖getBody
你自己既不编码特殊字符,因为Volley正在为你做这个。
答案 1 :(得分:1)
需要使用StringRequest作为djodjo提到。 还需要覆盖getBody方法 - 取自Android Volley POST string in body
@Override
public byte[] getBody() throws AuthFailureError {
String httpPostBody="your body as string";
// usually you'd have a field with some values you'd want to escape, you need to do it yourself if overriding getBody. here's how you do it
try {
httpPostBody=httpPostBody+"&randomFieldFilledWithAwkwardCharacters="+ URLEncoder.encode("{{%stuffToBe Escaped/","UTF-8");
} catch (UnsupportedEncodingException exception) {
Log.e("ERROR", "exception", exception);
// return null and don't pass any POST string if you encounter encoding error
return null;
}
return httpPostBody.getBytes();
}