带有标头和 JSON 正文的 Volley 中的 POST 请求
Posted
技术标签:
【中文标题】带有标头和 JSON 正文的 Volley 中的 POST 请求【英文标题】:POST Request in Volley with Header and JSON body 【发布时间】:2019-12-13 20:09:13 【问题描述】:我正在尝试使用 Volley 发出 POST 请求,下面是我想要发出的请求类型、标头和 JSON 正文
我尝试过使用 Unirest api (Unirest.io),但它需要 min sdk 为 24,所以我不得不切换到 Volley
HttpResponse<String> response = Unirest.post("https://api.msg91.com/api/v2/sendsms?country=91")
.header("authkey", "")
.header("content-type", "application/json")
.body(" \"sender\": \"SOCKET\", \"route\": \"4\", \"country\": \"91\", \"sms\": [ \"message\": \"Message1\", \"to\": [ \"98260XXXXX\", \"98261XXXXX\" ] , \"message\": \"Message2\", \"to\": [ \"98260XXXXX\", \"98261XXXXX\" ] ] ")
.asString();
【问题讨论】:
在我看来,Volley 对于 POST 请求不是很“友好”,我建议改用改造 你能帮我改造一下吗? 查看文档:square.github.io/retrofit 我会在这里发布凌空的答案 How to send a POST request using volley with string body?的可能重复 【参考方案1】:用OkHttp试试,下面是一个简单的
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW");
RequestBody body = RequestBody.create(JSON, json /* your json string*/);
Request request = new Request.Builder()
.url("https://api.msg91.com/api/v2/sendsms?country=91")
.post(body)
.addHeader("authkey", "Token")
.addHeader("content-type", "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW")
.build();
Response response = client.newCall(request).execute();
if (response.isSuccessful())
String responseBody=response.body().string()
您可以添加任何标题,将您的 json 字符串添加为正文
【讨论】:
以上是关于带有标头和 JSON 正文的 Volley 中的 POST 请求的主要内容,如果未能解决你的问题,请参考以下文章
如何在 Alamofire 中请求带有正文和标头的 JSON?
HttpClient postasync,带有自定义标头和应用程序/json,用于正文 C#
Volley Android中带有JSON正文的POST请求