Android Volley发出发布请求

时间:2018-12-14 11:02:11

标签: java android

我需要为一个类创建一个方法,该方法使用图像中的参数向API发送后期请求。之后,我需要获取响应并检查其“成功”

enter image description here

1 个答案:

答案 0 :(得分:0)

这是代码,使用可以根据您的需要更改参数: 在此getHeaders()方法中,您需要传递标头详细信息,而在getParams()方法中,则需要传递身体参数。

StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
    @Override
    public void onResponse(String s) {
        ///handle response from service
    }, new ErrorResponse() {
      @Override
      public void onErrorResponse(VolleyError volleyError) {
        //handle error response
      }
  }) {
      @Override
      protected Map<String, String> getParams() throws AuthFailureError {
          Map<String, String> params = new HashMap<String, String>();
          //add params <key,value>
          return params;
      }

      @Override
      public Map<String, String> getHeaders() throws AuthFailureError {
        Map<String,String> headers = Constants.getHeaders(context);
        // add headers <key,value>
        String credentials = USERNAME+":"+PASSWORD;
        String auth = "Basic "
                + Base64.encodeToString(credentials.getBytes(),
                Base64.NO_WRAP);
        headers.put("Authorization", auth);
        return headers;
      }
  };
 mQueue.add(request);

ref-https://gist.github.com/jchernandez/5bec1913af80e2923da8