Подтвердить что ты не робот

Как отправить запрос POST с помощью волейбола со строкой?

Я разрабатываю приложение для Android, которое общается с веб-службой RESTful, которую я написал. Использование методов Volley для GET является удивительным и легким, но я не могу наложить указатель на методы POST.

Я хочу отправить запрос POST с String в тело запроса и получить исходный ответ веб-службы (например, 200 ok, 500 server error).

Все, что я мог найти, это StringRequest, который не позволяет отправлять данные (тело), ​​а также ограничивает меня получением разобранного ответа String. Я также столкнулся с JsonObjectRequest, который принимает данные (тело), ​​но получает отлаженный ответ JSONObject.

Я решил написать свою собственную реализацию, но я не могу найти способ получить сырой ответ от веб-службы. Как я могу это сделать?

4b9b3361

Ответ 1

Вы можете обратиться к следующему коду (конечно, вы можете настроить, чтобы получить более подробную информацию об ответе сети):

try {
    RequestQueue requestQueue = Volley.newRequestQueue(this);
    String URL = "http://...";
    JSONObject jsonBody = new JSONObject();
    jsonBody.put("Title", "Android Volley Demo");
    jsonBody.put("Author", "BNK");
    final String requestBody = jsonBody.toString();

    StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            Log.i("VOLLEY", response);
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e("VOLLEY", error.toString());
        }
    }) {
        @Override
        public String getBodyContentType() {
            return "application/json; charset=utf-8";
        }

        @Override
        public byte[] getBody() throws AuthFailureError {
            try {
                return requestBody == null ? null : requestBody.getBytes("utf-8");
            } catch (UnsupportedEncodingException uee) {
                VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
                return null;
            }
        }

        @Override
        protected Response<String> parseNetworkResponse(NetworkResponse response) {
            String responseString = "";
            if (response != null) {
                responseString = String.valueOf(response.statusCode);
                // can get more details such as response.headers
            }
            return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
        }
    };

    requestQueue.add(stringRequest);
} catch (JSONException e) {
    e.printStackTrace();
}

Ответ 2

Мне понравился этот, но он sending JSON not string по запросу в вопросе, перепродав код здесь, если исходный github получил удалено или изменено, и это оказалось полезным для кого-то.

public static void postNewComment(Context context,final UserAccount userAccount,final String comment,final int blogId,final int postId){
    mPostCommentResponse.requestStarted();
    RequestQueue queue = Volley.newRequestQueue(context);
    StringRequest sr = new StringRequest(Request.Method.POST,"http://api.someservice.com/post/comment", new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            mPostCommentResponse.requestCompleted();
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            mPostCommentResponse.requestEndedWithError(error);
        }
    }){
        @Override
        protected Map<String,String> getParams(){
            Map<String,String> params = new HashMap<String, String>();
            params.put("user",userAccount.getUsername());
            params.put("pass",userAccount.getPassword());
            params.put("comment", Uri.encode(comment));
            params.put("comment_post_ID",String.valueOf(postId));
            params.put("blogId",String.valueOf(blogId));

            return params;
        }

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

public interface PostCommentResponseListener {
    public void requestStarted();
    public void requestCompleted();
    public void requestEndedWithError(VolleyError error);
}

Ответ 3

Name = editTextName.getText().toString().trim();
Email = editTextEmail.getText().toString().trim();
Phone = editTextMobile.getText().toString().trim();


JSONArray jsonArray = new JSONArray();
jsonArray.put(Name);
jsonArray.put(Email);
jsonArray.put(Phone);
final String mRequestBody = jsonArray.toString();

StringRequest stringRequest = new StringRequest(Request.Method.PUT, OTP_Url, new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        Log.v("LOG_VOLLEY", response);

    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        Log.e("LOG_VOLLEY", error.toString());
    }
}) {
    @Override
    public String getBodyContentType() {
        return "application/json; charset=utf-8";
    }

    @Override
    public byte[] getBody() throws AuthFailureError {
        try {
            return mRequestBody == null ? null : mRequestBody.getBytes("utf-8");
        } catch (UnsupportedEncodingException uee) {
            VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", mRequestBody, "utf-8");
            return null;
        }
    }

};
stringRequest.setShouldCache(false);
VollySupport.getmInstance(RegisterActivity.this).addToRequestque(stringRequest);

Ответ 4

Я делаю функцию для вызова vollyrequest. вам просто нужно передать аргументы

public void callvolly(final String username, final String password){
    RequestQueue MyRequestQueue = Volley.newRequestQueue(this);
    String url = "http://your_url.com/abc.php"; // <----enter your post url here
    StringRequest MyStringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            //This code is executed if the server responds, whether or not the response contains data.
            //The String 'response' contains the server response.
        }
    }, new Response.ErrorListener() { //Create an error listener to handle errors appropriately.
        @Override
        public void onErrorResponse(VolleyError error) {
            //This code is executed if there is an error.
        }
    }) {
        protected Map<String, String> getParams() {
            Map<String, String> MyData = new HashMap<String, String>();
            MyData.put("username", username);             
            MyData.put("password", password);                
            return MyData;
        }
    };


    MyRequestQueue.add(MyStringRequest);
}

Ответ 5

public void callvolly(final String username, final String password){
RequestQueue MyRequestQueue = Volley.newRequestQueue(this);
String url = "http://your_url.com/abc.php"; // <----enter your post url here
StringRequest MyStringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        //This code is executed if the server responds, whether or not the response contains data.
        //The String 'response' contains the server response.
    }
}, new Response.ErrorListener() { //Create an error listener to handle errors appropriately.
    @Override
    public void onErrorResponse(VolleyError error) {
        //This code is executed if there is an error.
    }
}) {
    protected Map<String, String> getParams() {
        Map<String, String> MyData = new HashMap<String, String>();
        MyData.put("username", username);             
        MyData.put("password", password);                
        return MyData;
    }
};


MyRequestQueue.add(MyStringRequest);

}