[RESOLVIDO] Método Post

Boa tarde,

A pouco tempo criei um software que gera um numero de protocolo junto com um log de procedimentos realizados. Preciso que o java envie as informações geradas no log para uma API de e-mail da nossa empresa, estudei um pouco mais sobre o envio de dados via HTTP, e verifiquei que o correto seria usar o método post, mas não estou conseguindo achar este método, ou eu achei porém não estou conseguindo usa-lo, o mais próximo que consegui deste método é este abaixo, alguém pode me dizer como funciona este método e como faço pra enviar dados para uma API através da URL dentro dele?

OBS: toda vez que eu executo ele me retorna um código 200 da URL, como se estivesse usando o método de requisição HTTP GET.

Obrigado

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import org.omg.CORBA.NameValuePair;
import sun.net.www.http.HttpClient;

public class Conexao {

private static HttpURLConnection con;

public static void main(String[] args) throws MalformedURLException,
        ProtocolException, IOException {

    String url = "spacecom.com.br";
    String urlParameters = "name=Jack&occupation=programmer";
    byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8);

    try {

        URL myurl = new URL(url);
        con = (HttpURLConnection) myurl.openConnection();

        con.setDoOutput(true);
        con.setRequestMethod("POST");
        con.setRequestProperty("User-Agent", "Java client");
        con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {
            wr.write(postData);
        }

        StringBuilder content;

        try (BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream()))) {

            String line;
            content = new StringBuilder();

            while ((line = in.readLine()) != null) {
                content.append(line);
                content.append(System.lineSeparator());
            }
        }

        System.out.println(content.toString());

    } finally {

        con.disconnect();
    }
}

}

Retorno 200 não significa que esteja usando GET, significa que estabeleceu a conexão e o retorno do servidor foi “OK”.

Fora isso, algum erro?
Aliás, se houver, você nunca verá, afinal, você omitiu o trecho catch do bloco, deixando só o try e o finally.

1 curtida

Entendi @darlan_machado, muito obrigado pelo retorno, a dúvida é como faço esse envio de informação, preciso enviar logs gerados para uma API. no caso, irei pegar o campo de texto digitado pelo usuário, e enviar isso pra uma API através de uma URL, se puder me ajudar.

Att,

O primeiro passo é incluir um catch a esse try. Assim você consegue capturar eventuais exceções que venham a ocorrer.
Ao invés disso

Faça isso:

} catch(Exception ex) {
    ex.printStackTrace();
} finally {
    con.disconnect();
}
1 curtida

Feito Darlan, agora sim, houve um problema.

Código Fonte:

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import org.omg.CORBA.NameValuePair;
import sun.net.www.http.HttpClient;

public class Conexao {

private static HttpURLConnection con;

public static void main(String[] args) throws MalformedURLException,
        ProtocolException, IOException {

    String url = "www.google.com.br";
    String urlParameters = "name=Jack&occupation=programmer";
    byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8);

    try {

        URL myurl = new URL(url);
        con = (HttpURLConnection) myurl.openConnection();

        con.setDoOutput(true);
        con.setRequestMethod("POST");
        con.setRequestProperty("User-Agent", "Java client");
        con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {
            wr.write(postData);
        }

        StringBuilder content;

        try (BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream()))) {

            String line;
            content = new StringBuilder();

            while ((line = in.readLine()) != null) {
                content.append(line);
                content.append(System.lineSeparator());
            }
        }

        System.out.println(content.toString());

    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        con.disconnect();
    }
    
}

}

Console:

java.net.MalformedURLException: no protocol: www.google.com.br
at java.net.URL.(URL.java:593)
at java.net.URL.(URL.java:490)
at java.net.URL.(URL.java:439)
at Conexao.main(Conexao.java:31)
Exception in thread “main” java.lang.NullPointerException
at Conexao.main(Conexao.java:62)
C:\Users\Gustavo\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
FALHA NA CONSTRUÇÃO (tempo total: 0 segundos)

Att,

Etnendo que você não quer enviar nada para a google, certo?
Além disso, pelo que me recordo, você precisa informar a URL completa inclui o protocolo, ou seja, ao invés de

www.google.com.br

Você deve especificar

http://www.google.com.br

Ou

https://www.google.com.br

Vide este exemplo

1 curtida

Boa tarde Darlan, fiz o teste em uma API e outro problema ocorre:

Código Fonte:
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import javax.swing.text.AbstractDocument.Content;
import javax.swing.text.BadLocationException;
import javax.swing.text.Position;
import javax.swing.text.Segment;
import javax.swing.text.StringContent;
import javax.swing.undo.UndoableEdit;
import org.omg.CORBA.NameValuePair;
import sun.net.www.http.HttpClient;

public class Conexao {

private static HttpURLConnection con;

public static void main(String [] gustavos) throws BadLocationException
{        
    StringContent t = new StringContent(100);
    post("Teste", t);
}

public static void post(String apiKey, Content content){
try{

    // 1. URL
    URL url = new URL("https://jsonplaceholder.typicode.com/posts/42");

    // 2. Open connection
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    // 3. Specify POST method
    conn.setRequestMethod("POST");

    // 4. Set the headers
    conn.setRequestProperty("Content-Type", "application/json");
    conn.setRequestProperty("Authorization", "key="+apiKey);

    conn.setDoOutput(true);

        // 5. Add JSON data into POST request body 

        //`5.1 Use Jackson object mapper to convert Contnet object into JSON
        ObjectMapper mapper = new ObjectMapper();

        // 5.2 Get connection output stream
        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());

        // 5.3 Copy Content "JSON" into 
        mapper.writeValue(wr, content);

        // 5.4 Send the request
        wr.flush();

        // 5.5 close
        wr.close();

        // 6. Get the response
        int responseCode = conn.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(
                new InputStreamReader(conn.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        // 7. Print result
        System.out.println(response.toString());

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

Console:

run:
Exception in thread “main” java.lang.UnsupportedOperationException: Not supported yet.
at ObjectMapper.writeValue(ObjectMapper.java:18)
at Conexao.post(Conexao.java:61)
at Conexao.main(Conexao.java:31)
C:\Users\Gustavo\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
FALHA NA CONSTRUÇÃO (tempo total: 1 segundo)

Boa tarde

Consegui estanciar o método Post, porém esta dando um outro erro durante a execução, alguém pode me auxiliar?

Método Post

public static void post(String apiKey, Content content) {

    try {

        // 1. URL
        URL url = new URL("https://android.googleapis.com/gcm/send");

        // 2. Abrir conexão
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        // 3. Especifique o método POST
        conn.setRequestMethod("POST");

        // 4. Defina os cabeçalhos
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("Authorization", "key=" + apiKey);

        conn.setDoOutput(true);

        // 5. Adicionar dados JSON ao corpo da solicitação POST
        //`5.1 Use o mapeador de objetos Jackson para converter o objeto Contnet em JSON
        ObjectMapper mapper = new ObjectMapper();

        // 5.2 Obter fluxo de saída de conexão
        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());

        // 5.3 Copiar conteúdo "JSON" em
        mapper.writeValue(wr, content);

        // 5.4 Enviar o pedido
        wr.flush();

        // 5.5 fechar
        wr.close();

        // 6. Obtem a resposta
        int responseCode = conn.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(
                new InputStreamReader(conn.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        // 7. Mostra o Resultado
        System.out.println(response.toString());

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Classe Content

public static Content createContent() {

    Content c = new Content() {
        @Override
        public Position createPosition(int offset) throws BadLocationException {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public int length() {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public UndoableEdit insertString(int where, String str) throws BadLocationException {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public UndoableEdit remove(int where, int nitems) throws BadLocationException {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public String getString(int where, int len) throws BadLocationException {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void getChars(int where, int len, Segment txt) throws BadLocationException {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }
    }; 

//AQUI MOSTRA O PROBLEMA NO CÓDIGO
c.addRegId(“APA91bFqnQzp0z5IpXWdth1lagGQZw1PTbdBAD13c-UQ0T76BBYVsFrY96MA4SFduBW9RzDguLaad-7l4QWluQcP6zSoX1HSUaAzQYSmI93…”);

//AQUI MOSTRA O PROBLEMA NO CÓDIGO
c.createData(“Test Title”, “Test Message”);
return c;

}

Classe principal
private static HttpURLConnection con;

public static void main(String[] gustavos) throws BadLocationException {
    System.out.println("Sending POST to GCM");

    String apiKey = "AIzaSyB8azikXJKi_NjpWcVNJVO0d........";
    Content content = createContent();

    Conexao.post(apiKey, content);

}

Mas qual o problema/erro?

run:
Sending POST to GCM
Exception in thread “main” java.lang.UnsupportedOperationException: Not supported yet.
at Conexao$ObjectMapper.writeValue(Conexao.java:147)
at Conexao$ObjectMapper.access$000(Conexao.java:141)
at Conexao.post(Conexao.java:65)
at Conexao.main(Conexao.java:34)
C:\Users\Gustavo\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
FALHA NA CONSTRUÇÃO (tempo total: 1 segundo)

Este é o problema, mas ele ja indica bug quando eu uso o método:

c.addRegId(“APA91bFqnQzp0z5IpXWdth1lagGQZw1PTbdBAD13c-UQ0T76BBYVsFrY96MA4SFduBW9RzDguLaad-7l4QWluQcP6zSoX1HSUaAzQYSmI93…”);

c.createData(“Test Title”, “Test Message”);

Boa tarde,

@Darlan_Mota, através do exemplo que você me enviou, consegui fazer essa requisição após estudar um pouco mais este método, obrigado pela ajuda!!

Código fonte pra quem irá precisar:

public class Conexao {

private static HttpURLConnection con;

public static void main(String[] gustavos) throws BadLocationException {
    System.out.println("Envio de POST para o GCM");

    String apiKey = "AIzaSyB8azikXJKi_NjpWcVNJVO0d........";
    Content content = createContent();

    Conexao.post(apiKey, content);

}

public static void post(String apiKey, Content content) {

    try {

        // 1. URL
        URL url = new URL("http://10.0.11.189:20667/api/gustavo");

        // 2. Abrir conexão
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        // 3. Especifique o método POST
        conn.setRequestMethod("POST");

        // 4. Defina os cabeçalhos
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("Authorization", "key=" + apiKey);

        conn.setDoOutput(true);

        // 5. Adicionar dados JSON ao corpo da solicitação POST
        //`5.1 Use o mapeador de objetos Jackson para converter o objeto Contnet em JSON
        //ObjectMapper mapper = new ObjectMapper();
        
        
        // 5.2 Obter fluxo de saída de conexão
        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());

        // 5.3 Copiar conteúdo "JSON" em
        // mapper.writeValue(wr, content);
        // 5.4 Enviar o pedido
        wr.flush();

        // 5.5 fechar
        wr.close();

        // 6. Obtem a resposta
        int responseCode = conn.getResponseCode();
        System.out.println("\nEnviando solicitação 'POST' para URL : " + url);
        System.out.println("Resposta do código : " + responseCode);

        BufferedReader in = new BufferedReader(
                new InputStreamReader(conn.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        // 7. Mostra o Resultado
        System.out.println(response.toString());

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

private static void flush() {
    throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}

public static Content createContent() {

    Content c = new Content() {
        @Override
        public Position createPosition(int offset) throws BadLocationException {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public int length() {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public UndoableEdit insertString(int where, String str) throws BadLocationException {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public UndoableEdit remove(int where, int nitems) throws BadLocationException {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public String getString(int where, int len) throws BadLocationException {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void getChars(int where, int len, Segment txt) throws BadLocationException {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }
    };

    // c.addRegId("APA91bFqnQzp0z5IpXWdth1lagGQZw1PTbdBAD13c-UQ0T76BBYVsFrY96MA4SFduBW9RzDguLaad-7l4QWluQcP6zSoX1HSUaAzQYSmI93....");
    // c.createData("Test Title", "Test Message");
    return c;

}

}

Importações:
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.text.AbstractDocument.Content;
import javax.swing.text.BadLocationException;
import javax.swing.text.Position;
import javax.swing.text.Segment;
import javax.swing.undo.UndoableEdit;