2017-09-14 78 views
0

我的代码正试图将数据发布到服务器,并且需要添加标题,我正在使用Volley库。具有标题和正文的Android Volley POST请求

如果我不包含“getparams”方法,请求可以工作,但我可以发布但没有数据。

如果我包含“getparams”方法,请求将失败,并返回400(错误请求)。

我一直无法找出错误在哪里。

  public void tryPost() { 
    RequestQueue queue = Volley.newRequestQueue(this); 

    String serverUrl = "http://10.0.2.2:3000/tasks"; 



    StringRequest stringRequest = new StringRequest(Request.Method.POST, serverUrl, 
      new Response.Listener<String>() { 
       @Override 
       public void onResponse(String response) { 
        Log.d("TAG", "response = "+ response); 
       } 
      }, new Response.ErrorListener() { 
     @Override 
     public void onErrorResponse(VolleyError error) { 
      Log.d("TAG", "Error = "+ error); 
     } 
    }) 
    { 
     // 
     @Override 
     public Map<String, String> getHeaders() { 
      HashMap<String, String> headers = new HashMap<>(); 
      headers.put("Accept", "application/json"); 
      headers.put("Content-Type", "application/json"); 
      return headers; 
     } 
     //// 
     @Override 
     public Map<String, String> getParams() { 
      Map<String, String> params = new HashMap<>(); 
      params.put("userId","sargent"); 
      params.put("password","1234567"); 
      return params; //return the parameters 
     } 
    }; 
    // Add the request to the RequestQueue. 
    queue.add(stringRequest); 
    } 

回答

0

我不使用凌空多,但我有一个替代方案,将轻松地做你的工作。如果你想使用AsyncHTTPClient尝试一下。

public void tryPost(){ 
    AsynHTTPClient client = new AsyncHTTPClient(); 

    //to add the data which you wanna post 
    RequestParams params = new RequestParams(); 
    params.add("pass your value","from this value"); 
    params.put("list","your_list"); // this is for passing the arraylist 

    client.post(url, params, new AsynchHTTPRespondHandeler(){ 
    // implement method to get the response from onSuccess() 

    }); 
} 

对于AsynchHTTPClient做到这一点在你的gradle产出:

compile 'com.loopj.android:android-async-http:1.4.9' 

您可以了解更多关于RequestParams为了通过不同的DATAS here

我希望你会用这个做你的工作。请为我解决任何问题。

+0

如何添加标题? – Tori

+0

您是否阅读过有关RequestParams的文档,在这里您将了解如何添加这些数据。尝试使用请求参数,这将做你的工作,或者更精确,以便我能够找出你想要的东西,在这里我可以找出你想添加一些我已经为你解释的数据。 –

+0

我阅读了文档,并没有解释如何添加标题。特别是我想要做的是headers.put(“接受”,“应用程序/ JSON”); headers.put(“Content-Type”,“application/json”); – Tori

3

对于认证你应该包括内部getHeaders,而不是getParams信息

删除getParams和添加给你的getHeaders

@Override 
public Map<String, String> getHeaders() throws AuthFailureError { 
     Map<String, String> headers = new HashMap<>();     
     String credentials = "username:password"; 
     String auth = "Basic " 
         + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP); 
     headers.put("Accept", "application/json"); 
     headers.put("Content-Type", "application/json"); 
     headers.put("Authorization", auth); 
     return headers; 
} 

希望它可以帮助

+0

上面的代码添加了工作正常的头文件,但是当与param代码结合使用时,响应是一个错误的请求。 – Tori