【问题标题】:How to post entity using volley library in Android?如何在 Android 中使用 volley 库发布实体?
【发布时间】:2015-10-23 19:01:57
【问题描述】:

如何使用 volley 实现以下代码?我需要发布并从服务器接收答案。

HttpURLConnection    urlConnection = (HttpURLConnection) postUrl.openConnection();
urlConnection.setInstanceFollowRedirects(false);
// urlConnection.setHostnameVerifier(hostnameVerifier);

urlConnection.setConnectTimeout(5000);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
urlConnection.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
urlConnection.setRequestProperty("User-Agent", USER_AGENT);
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);


//Send request
OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream());
out.write(data);
out.close();

//Get Response
InputStream is = urlConnection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while ((line = rd.readLine()) != null)
{
    response.append(line);
    response.append('\r');
}
rd.close();

ret = response.toString();

【问题讨论】:

  • 创建Request 并覆盖getParams(),还是getBody()?有很多例子可以说明如何做到这一点,那么你到底在哪一步遇到了问题?到目前为止,您尝试过什么?
  • 阅读这篇很棒的教程Android working with Volley Library,它涵盖了 GET 和 POST 请求。

标签: android android-volley httpurlconnection


【解决方案1】:

您可以在 Request 类中覆盖适当的方法。

对于字符串请求:

Response.Listener<String> listener = new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    //consume response
                }
};

StringRequest request = new StringRequest(Request.Method.POST, url, listener, errorListener) {

        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String, String> header = new HashMap<>();
            header.put("User-Agent", USER_AGENT);
            header.put("Content-Type", "application/x-www-form-urlencoded");
            ...
            return header;
        }

        @Override
        public byte[] getBody() throws AuthFailureError {
            String someContent = "{\"key\"=\"\value\"}";
            return someContent.getBytes();
        }
};

然后将请求添加到您的请求队列中:

RequestQueue queue = Volley.newRequestQueue(context);
queue.add(request);

【讨论】:

  • 非常感谢。我无法将字符串数据发布到服务器。上帝保佑你。
猜你喜欢
  • 2014-12-20
  • 1970-01-01
  • 2015-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-15
  • 2017-10-27
  • 1970-01-01
相关资源
最近更新 更多