如何在Android中使用排球库发布实体?

时间:2015-10-23 19:01:57

标签: android android-volley httpurlconnection

如何使用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();

1 个答案:

答案 0 :(得分:0)

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

对于StringRequest:

yourApp.filter('orderObjectBy', function () {
    return function (items, field, reverse) {
        // Build array
        var filtered = [];
        for (var key in items) {
            if (field === 'key')
                filtered.push(key);
            else
                filtered.push(items[key]);
        }
        // Sort array
        filtered.sort(function (a, b) {
            if (field === 'key')
                return (a > b ? 1 : -1);
            else
                return (a[field] > b[field] ? 1 : -1);
        });
        // Reverse array
        if (reverse)
            filtered.reverse();
        return filtered;
    };
});

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

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();
        }
};