[RESOLVIDO]Post - Web Service

Pessoal,

Estou tentando utilizar o método post para consumir um Web Service:

@Override
protected Integracao doInBackground(Void... params) {

    Integracao retInt = null;
    Gson gson = new Gson();
    String urlCnx = urlWs+"integracao";
    StringBuilder execucao = new StringBuilder();
    HttpURLConnection urlConnection = null;
    System.out.println("Preparando conexão WS - POST");
    try {
        URL url = new URL(urlCnx);
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestProperty("Content-Type", "application/json");
        urlConnection.setRequestMethod("POST");
        urlConnection.setDoOutput(true);
        urlConnection.setDoInput(true);
        urlConnection.setChunkedStreamingMode(0);

        OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
                out, "UTF-8"));
        writer.write(json.toString());
        writer.flush();

        int code = urlConnection.getResponseCode();
        if (code !=  201) {
            throw new IOException("Invalid response from server: " + code);
        }

        BufferedReader rd = new BufferedReader(new InputStreamReader(
                urlConnection.getInputStream()));
        String line;
        while ((line = rd.readLine()) != null) {
            Log.i("data", line);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }

    Log.d("Integração ",retInt.toString());
    return retInt;
}

Porém está retornando o erro abaixo:

W/System.err: java.net.ProtocolException: Unexpected status line: 

W/System.err: at com.android.okhttp.internal.http.StatusLine.parse(StatusLine.java:54)
W/System.err: at com.android.okhttp.internal.http.Http1xStream.readResponse(Http1xStream.java:395)
W/System.err: at com.android.okhttp.internal.http.Http1xStream.readResponseHeaders(Http1xStream.java:144)
W/System.err: at com.android.okhttp.internal.http.HttpEngine.readNetworkResponse(HttpEngine.java:887)
W/System.err: at com.android.okhttp.internal.http.HttpEngine.readResponse(HttpEngine.java:759)
W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:498)
W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:434)
W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:565)
W/System.err: at com.br.retcam.webservice.HttpServiceIntegracao.doInBackground(HttpServiceIntegracao.java:71)
W/System.err: at com.br.retcam.webservice.HttpServiceIntegracao.doInBackground(HttpServiceIntegracao.java:35)
W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:333)
W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:266)
W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245)
W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
W/System.err: at java.lang.Thread.run(Thread.java:764)
E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #4
Process: com.br.retcam, PID: 22110
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:354)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:383)
at java.util.concurrent.FutureTask.setException(FutureTask.java:252)
at java.util.concurrent.FutureTask.run(FutureTask.java:271)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:764)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method ‘java.lang.String com.br.retcam.entity.Integracao.toString()’ on a null object reference
at com.br.retcam.webservice.HttpServiceIntegracao.doInBackground(HttpServiceIntegracao.java:90)
at com.br.retcam.webservice.HttpServiceIntegracao.doInBackground(HttpServiceIntegracao.java:35)
at android.os.AsyncTask$2.call(AsyncTask.java:333)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:764)

Alguém tem alguma ideia do que pode ser?

Obrigado

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method ‘java.lang.String com.br.retcam.entity.Integracao.toString()’ on a null object reference

@Override
protected Integracao doInBackground(Void... params) {

    Integracao retInt = null;

Tente mudar para algo como: Integracao retInt = new Integracao();

Provavelmente, essa é a causa do seu problema…

Fora que usar o OkHttp é bem mais fácil

public static final MediaType JSON = MediaType.get("application/json; charset=utf-8");

OkHttpClient client = new OkHttpClient();

String post(String url, String json) throws IOException {
  RequestBody body = RequestBody.create(json, JSON);
  Request request = new Request.Builder()
      .url(url)
      .post(body)
      .build();
  try (Response response = client.newCall(request).execute()) {
    return response.body().string();
  }
}

link com varios tutoriais:

1 curtida

Opa, obrigado pela resposta, mas vi que o problema é no Json que estou tentando enviar.

Existe alguma objeto no java pra converter nesse formato:

"{\"codigoproduto\":15,\"descricao\":\"PAO INT. COM FIBRAS LEVE 400G\",\"devolucao\":9999,\"troca\":9999,\"retcarga\":9999,\"bonificacao\":9999}"

Tenho uma classe que retorna o objeto. Tentei o Gson, mas ele não retorna conforme o exemplo que dei acima

Pessoal,

Consegue resolver a questão do JSON e agora o meu App consegue consumir o Ws normalmente enviado os dados que preciso.

Agora o problema que estou tento é com relação ao retorno. Quando é executado a linha abaixo é apresentado o java.io.FileNotFoundException

 Scanner scanner = new Scanner(url.openStream());

Erro:

W/System.err: java.io.FileNotFoundException: http://10.100.12.170:8081/rest/ECWSRTTR/integracao

W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:255)
W/System.err: at java.net.URL.openStream(URL.java:1073)
W/System.err: at com.br.retcam.webservice.HttpServiceIntegracao.doInBackground(HttpServiceIntegracao.java:55)
W/System.err: at com.br.retcam.webservice.HttpServiceIntegracao.doInBackground(HttpServiceIntegracao.java:16)
W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:333)
W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:266)
W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245)
W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
W/System.err: at java.lang.Thread.run(Thread.java:764)

Pessoal,

Consegui resolver, o problema estava no web service na qual estava consumindo.

Obrigado

1 curtida