Android - HttpsURLConnection - BAD REQUEST

时间:2016-08-12 20:08:03

标签: android httpurlconnection plivo

我正在尝试使用Plivo(VoIP服务器)发送POST请求向我的手机发送短信,但我只是收到了BAD REQUEST(请求代码400)。

我收到的错误是"error": "invalid json data sent in raw POST"

我找不到它的错误。

有人可以帮助我吗?

        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();

2 个答案:

答案 0 :(得分:0)

解决

发送Json object时,必须将其传递给String,但无法对其进行编码。

将行postParaEnvio.write(URLEncoder.encode(params.toString(), "UTF-8"));修改为postParaEnvio.write(params.toString());解决了问题。

答案 1 :(得分:0)

我认为这可能会对你有所帮助。 顺便说一句,
我的依赖关系:gradle-&gt;
编译'com.android.support:appcompat-v7:23.4.0'

   class BackGround extends AsyncTask<String, String, String> {

    protected String doInBackground(String... params) {
        String name = params[0];
        String password = params[1];
        String email = params[2];
        String phone=params[3];

        String data="";
        int tmp;

        try {
            URL url = new URL("http://domain.com/yourFile.php");
            String urlParams = "name="+name+"&password="+password+"&email="+email+"&phone="+phone;

            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setDoOutput(true);
            OutputStream os = httpURLConnection.getOutputStream();
            os.write(urlParams.getBytes());
            os.flush();
            os.close();
            InputStream is = httpURLConnection.getInputStream();
            while((tmp=is.read())!=-1){
                data+= (char)tmp;
            }
            is.close();
            httpURLConnection.disconnect();
            return data;

        } catch (MalformedURLException e) {
            e.printStackTrace();
            return "Exception: "+e.getMessage();
        } catch (IOException e) {
            e.printStackTrace();
            return "Exception: "+e.getMessage();
        }
    }

    @Override
    protected void onPostExecute(String s) {
        if(s.equals("")){
            s="Data Saved! Success...";
        }
        Toast.makeText(ctx, s, Toast.LENGTH_LONG).show();
    }
}