带Body的HTTPPOST Android

时间:2017-11-30 08:46:58

标签: java android android-volley

我一直在寻找一种简单的方法来在Android中使用body发布HTTP帖子,我的api调用应该是这样的:

  

的https:URL / API /消息令牌=&设为MyToken放大器;信道=皮尤&安培;文本= someText&安培;用户名=用户

我做的是这个,我创建了这个类

Public class ApiCalls {
    private static PostCommentResponseListener mPostCommentResponse;
    private static Context mContext;
    public ApiCalls(){

    }

    public static void postNewComment(Context context, final String message){
        mContext = context;
        String apiUrl = context.getResources().getString(R.string.api_url);

        mPostCommentResponse.requestStarted();
        RequestQueue queue = Volley.newRequestQueue(context);
        StringRequest sr = new StringRequest(Request.Method.POST,apiUrl, 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("token",mContext.getResources().getString(R.string.access_token));
                params.put("channel","pew");
                params.put("text", message);
                params.put("username","User");
                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);
    }
}

但它不起作用,它只显示应用程序已停止。

使用Volley是否合适?或者你建议我用其他方式?我过去常常使用HttpClient,但现在已弃用...

我缺少什么?

记录错误

  

java.lang.NullPointerException:尝试在空对象引用上调用接口方法'void com.package.ApiCalls $ PostCommentResponseListener.requestStarted()'

2 个答案:

答案 0 :(得分:1)

您可以使用volly以下两种方式发送json正文。

<强> 1。使用JsonObjectRequest

Map<String,String> params = new HashMap<String, String>();
                params.put("token",mContext.getResources().getString(R.string.access_token));
                params.put("channel","pew");
                params.put("text", message);
                params.put("username","User");

JsonObjectRequest request_json = new JsonObjectRequest(URL, new JSONObject(params),
       new Response.Listener<JSONObject>() {
           @Override
           public void onResponse(JSONObject response) {
               try {
                   //Process success response
               } catch (JSONException e) {
                   e.printStackTrace();
               }
           }
       }, new Response.ErrorListener() {
           @Override
           public void onErrorResponse(VolleyError error) {
               // handle error
           }
       });

// add the request object to the queue to be executed
queue.add(request_json);

<强> 2。直接在请求正文中使用JSON

JSONObject jsonBody = new JSONObject();
    jsonBody.put("token",mContext.getResources().getString(R.string.access_token));
    jsonBody.put("channel","pew");
    jsonBody.put("text", message);
    jsonBody.put("username","User");
    final String mRequestBody = jsonBody.toString();

StringRequest sr = new StringRequest(Request.Method.POST,apiUrl, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            // Process success response
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
             // handle error
        }
    }){
    @Override
    public String getBodyContentType() {
        return "application/json; charset=utf-8";
    }

    @Override
    public byte[] getBody() throws AuthFailureError {
        try {
            return mRequestBody.getBytes("utf-8");
        } catch (Exception e) {                
            return null;
        }
    }

    @Override
    protected Response<String> parseNetworkResponse(NetworkResponse response) {
        String responseString = "";
        if (response != null) {
            responseString = String.valueOf(response.statusCode);
        }
        return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
    }
};

// add the request object to the queue to be executed
queue.add((sr);

答案 1 :(得分:0)

像这样初始化你的mPostCommentResponse:

 public ApiCalls(){
      mPostCommmentResponse = (PostCommentResponseListener)mContext;
}
它会帮你工作,休息很好。感谢。

<强>编辑:

在你想要调用“ApiCall”类的另一个Activity中,执行类似的代码:

 new ApiCalls().postNewComment(AnotherActivity.this,"Your Messsage here");

并在方法“postNewComment”中这样做:

  mContext = context;
  mPostCommmentResponse = (PostCommentResponseListener)mContext;

是否可以理解?