I'm trying to send a POST
request to Plivo (VoIP server) to send an SMS to my cell phone, but I only get BAD REQUEST (Code 400).
The error I received is "error": "invalid json data sent in raw POST"
I can not find the error.
Does anyone know how to solve it?
final AsyncTask < String, Void, Boolean > request = new AsyncTask < String, Void, Boolean > () {
@Override
protected Boolean doInBackground(String...strings) {
Boolean retorno = true;
HttpsURLConnection request = null;
try {
request = (HttpsURLConnection) finalUrl.openConnection();
System.out.println("Define POST");
request.setRequestMethod("POST");
request.setUseCaches(false);
request.setDoOutput(true);
System.out.println("Define propriedades");
request.setRequestProperty("Content-Type", "application/json");
request.setRequestProperty("Accept", "application/json");
request.setRequestProperty("Accept-Charset", "UTF-8");
request.setRequestProperty("charset", "UTF-8");
System.out.println("Define autenticação");
String autenticacao = authID + ":" + authToken;
String basic = "Basic " + new String(Base64.encode(autenticacao.getBytes(), Base64.NO_WRAP));
request.setRequestProperty("Authorization", basic);
System.out.println("Define parâmetros");
JSONObject params = new JSONObject();
params.put("dst", numeroDestino);
params.put("src", numeroOrigem);
params.put("text", body);
System.out.println("Faz conexão e requisição");
request.connect();
OutputStreamWriter postParaEnvio = new OutputStreamWriter(request.getOutputStream());
postParaEnvio.write(URLEncoder.encode(params.toString(), "UTF-8"));
postParaEnvio.flush();
postParaEnvio.close();
int codigoStatus = request.getResponseCode();
for (Map.Entry < String, List < String >> header: request.getHeaderFields().entrySet()) {
System.out.println(header.getKey() + "=" + header.getValue());
}
if (codigoStatus == 202) {
System.out.println("OK");
} else {
System.out.println("Falha");
System.out.println(codigoStatus);
retorno = false;
}
} catch (IOException e) {
System.out.println("Falha Exception");
e.printStackTrace();
retorno = false;
} catch (JSONException e) {
e.printStackTrace();
retorno = false;
} finally {
request.disconnect();
}
return retorno;
}
@Override
protected void onPostExecute(Boolean result) {
indicadorDeAtividade.dismiss();
if (result) {
} else {
mostrarErro(0, R.string.erroEnviarCodigo);
}
}
}.execute();