带有标题和JSON正文的Volley中的POST请求

时间:2019-08-06 09:43:15

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

我正在尝试使用Volley发出POST请求,以下是我要发出的请求,标头和JSON正文

我已经尝试过使用Unirest api(Unirest.io),但它要求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();

1 个答案:

答案 0 :(得分:0)

尝试使用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字符串添加为正文