【问题标题】:POST Request in Volley with Header and JSON body带有标头和 JSON 正文的 Volley 中的 POST 请求
【发布时间】: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();

【问题讨论】:

标签: android json http http-headers android-volley


【解决方案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 字符串添加为正文

【讨论】:

    猜你喜欢
    • 2020-01-02
    • 1970-01-01
    • 2021-08-11
    • 2017-08-31
    • 2016-09-24
    • 2020-12-23
    • 2021-05-24
    • 1970-01-01
    • 2020-01-28
    相关资源
    最近更新 更多