Boa tarde Galera,
Fui direcionado para criar um software, que pega algumas informações de sites. Parar ser mais específicos, ele deve enviar uma requisição para um determinado site, e receber algumas informações.
Ja dei uma estudada em método Get e Post para requisição http, mas esse software é mais complexo, e não sei se apenas esses métodos irão me ajudar.
Queria uma ajuda pra saber ao menos por onde começar, o que devo estudar.
Outro exemplo do software:
Deve requisitar um serviço para a embratel, perguntado todos os sites que começam com uma determinada sigla. Por exemplo, “www.GOexemplo.com.br”, e receber todos os sites que possui esta sigla no meio da URL.
Caso eu não expliquei muito bem, posso reformular.
Método Post: (Acho que pode ajudar no processo):
package UtilitariosPost;
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 java.util.Scanner;
import javax.swing.JOptionPane;
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;
public class Conexao {
private String recebe = "dsa";
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);
Scanner entrada = new Scanner(System.in);
String text = JOptionPane.showInputDialog("Digite algo: ");
wr.writeBytes("{\"api\":\"" + text + "\"}");
// 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());
JOptionPane.showMessageDialog(null, "Resposta: " + response.toString());
System.out.println("Resposta: " + 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;
}
}
Obrigado.