Android 如何使用截击发送带有JSON正文的POST请求?

Android 如何使用截击发送带有JSON正文的POST请求?,android,http-post,android-volley,Android,Http Post,Android Volley,如何使用Volley库将这些参数传递到POST方法中。 API链接: 我试过了,但又遇到了错误 StringEntity params= new StringEntity ("{\"trip\":\"[\"{\"departure_code\":\"," +departure,"arrival_code\":\"+"+arrival+","+"outbound_date\":\"," +outbound,"

如何使用Volley库将这些参数传递到POST方法中。

API链接:


我试过了,但又遇到了错误

StringEntity params= new StringEntity ("{\"trip\":\"[\"{\"departure_code\":\","
                     +departure,"arrival_code\":\"+"+arrival+","+"outbound_date\":\","
                     +outbound,"inbound_date\":\","+inbound+"}\"]\"}");
request.addHeader("content-type", "application/json");
request.addHeader("Accept","application/json");

有关API的详细信息,请访问。

这是使用
StringRequest

    StringRequest stringRequest = new StringRequest(Method.POST, url,  listener, errorListener) {  
    @Override  
    protected Map<String, String> getParams() throws AuthFailureError {  
        Map<String, String> map = new HashMap<String, String>();  
        map.put("api_key", "12345");  
        map.put("ts_code", "12345");  
        return map;  
    }  
}; 
StringRequest-StringRequest=new-StringRequest(Method.POST,url,listener,errorListener){
@凌驾
受保护的映射getParams()引发AuthFailureError{
Map Map=newhashmap();
地图放置(“api_键”、“12345”);
地图放置(“ts_代码”、“12345”);
返回图;
}  
}; 
OkHttpClient-OkHttpClient=new-OkHttpClient();
ContentValues=新的ContentValues();
value.put(parameter1Name,parameter1Value);
value.put(parameter2Name,parameter2Value);
RequestBody RequestBody=null;
如果(值!=null&&values.size()>0){
FormEncodingBuilder formEncoding=新的FormEncodingBuilder();
设置keySet=values.keySet();
用于(字符串键:键集){
试一试{
value.getAsString(键);
add(key,values.getAsString(key));
}捕获(例外情况除外){
Logger.log(Logger.LEVEL_ERROR,CLASS_NAME,“getRequestBodyFromParameters”,“添加Post参数时出错。跳过此参数。“+例如getLocalizedMessage());
}
}
requestBody=formEncoding.build();
}
字符串URL=”http://example.com";
Request.Builder=新建Request.Builder();
url(url);
建造商职位(请求机构);
Request=builder.build();
Response-Response=okHttpClient.newCall(request.execute();

通常的方法是使用带有键值对的
HashMap
作为请求参数

与下面的示例类似,您需要根据您的特定需求进行自定义

选项1:

final String URL = "URL";
// Post params to be sent to the server
HashMap<String, String> params = new HashMap<String, String>();
params.put("token", "token_value");
params.put("login_id", "login_id_value");
params.put("UN", "username");
params.put("PW", "password");

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

// add the request object to the queue to be executed
ApplicationController.getInstance().addToRequestQueue(request_json);
final String URL=“URL”;
//将要发送到服务器的Post参数
HashMap params=新的HashMap();
参数put(“令牌”、“令牌值”);
参数put(“登录标识”、“登录标识值”);
参数put(“UN”、“用户名”);
参数put(“PW”,“密码”);
JsonObjectRequest\u json=新的JsonObjectRequest(URL,新的JSONObject(参数),
新的Response.Listener(){
@凌驾
公共void onResponse(JSONObject响应){
试一试{
//处理操作系统成功响应
}捕获(JSONException e){
e、 printStackTrace();
}
}
},new Response.ErrorListener(){
@凌驾
公共无效onErrorResponse(截击错误){
e(“Error:,Error.getMessage());
}
});
//将请求对象添加到要执行的队列中
ApplicationController.getInstance().addToRequestQueue(请求\u json);
注意:HashMap可以将自定义对象作为值

选项2:

final String URL = "URL";
// Post params to be sent to the server
HashMap<String, String> params = new HashMap<String, String>();
params.put("token", "token_value");
params.put("login_id", "login_id_value");
params.put("UN", "username");
params.put("PW", "password");

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

// add the request object to the queue to be executed
ApplicationController.getInstance().addToRequestQueue(request_json);
在请求体中直接使用JSON

try {
    RequestQueue requestQueue = Volley.newRequestQueue(this);
    String URL = "http://...";
    JSONObject jsonBody = new JSONObject();
    jsonBody.put("firstkey", "firstvalue");
    jsonBody.put("secondkey", "secondobject");
    final String mRequestBody = jsonBody.toString();

    StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            Log.i("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;
            }
        }

        @Override
        protected Response<String> parseNetworkResponse(NetworkResponse response) {
            String responseString = "";
            if (response != null) {

                responseString = String.valueOf(response.statusCode);

            }
            return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
        }
    };

    requestQueue.add(stringRequest);
} catch (JSONException e) {
    e.printStackTrace();
}
试试看{
RequestQueue RequestQueue=Volley.newRequestQueue(this);
字符串URL=”http://...";
JSONObject jsonBody=新的JSONObject();
jsonBody.put(“firstkey”、“firstvalue”);
put(“secondkey”、“secondobject”);
最后一个字符串mRequestBody=jsonBody.toString();
StringRequest StringRequest=new StringRequest(Request.Method.POST,URL,new Response.Listener()){
@凌驾
公共void onResponse(字符串响应){
Log.i(“Log_-VOLLEY”,回应);
}
},new Response.ErrorListener(){
@凌驾
公共无效onErrorResponse(截击错误){
Log.e(“Log_-VOLLEY”,error.toString());
}
}) {
@凌驾
公共字符串getBodyContentType(){
返回“application/json;charset=utf-8”;
}
@凌驾
公共字节[]getBody()抛出AuthFailureError{
试一试{
返回mRequestBody==null?null:mRequestBody.getBytes(“utf-8”);
}捕获(不支持的编码异常uee){
wtf(“尝试使用%s获取%s的字节时不支持编码”,mRequestBody,“utf-8”);
返回null;
}
}
@凌驾
受保护的响应parseNetworkResponse(NetworkResponse响应){
字符串responseString=“”;
if(响应!=null){
responseString=String.valueOf(response.statusCode);
}
返回Response.success(responseString,HttpHeaderParser.parseCacheHeaders(Response));
}
};
添加(stringRequest);
}捕获(JSONException e){
e、 printStackTrace();
}

quick tip:切换到Okhttp或改型,截击速度较慢,从初学者的角度来看很难,而Okhttp对您来说更容易!你需要做的是使用okhttp在post请求中传递json作为主体,让我知道这是否对你有帮助:如果你坚持使用截击本身,你也可以参考这个问题:@superman谢谢。我会试着解决这个问题?这是如何解决问题的?POST请求的主体是json。@Ricky.Lee我不是在问api_键和ts_代码。api_键和ts_代码添加url链接其工作正常。。我在询问一些json数据,比如trip[{}],我只是发布了这些值{“trips”:[{“出发代码”:“SYD”,“到达代码”:“LON”,“出发日期”:“2014-01-24”,“入境日期”:“2014-01-29”}],“成人计数”:1,“地点”:“ar”}@Pawandeep Kaur要求提供截击体柱参数,而不是Okhttp,如果这两个库的格式完全不同,我只需将这些参数发布到post方法{“trips”:[{“department_code”:“SYD”,”