Problem trying to make HTTP request in Java

0

I have a problem and I would like you to help me solve it. I created a java application to consume a webservice I made in php. After much searching I was able to create a class capable of making http requests. The problem is that I'm encountering an error with the url I'm using to access the webservice. The WebClient class is responsible for making the connection to the webservice and returning a response (which would be a string in JSON format), it receives the data (also a string in JSON format) and tries to make the request with the server where the webservice is Stayed there. However I am encountering a mis-formation error in the url. Could someone help me solve this problem?

WebClient class

public class WebClient {
public String post(String json) {
    try {
        URL url = new URL("localhost/CWS/cadastrar_guia.php");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestProperty("Content-type", "application/json");
        connection.setRequestProperty("Accept", "application/json");


        connection.setDoOutput(true);

        PrintStream output = new PrintStream(connection.getOutputStream());
        output.println(json);

        connection.connect();

        Scanner scanner = new Scanner(connection.getInputStream());
        String resposta = scanner.next();
        return resposta;
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

}

No Main

    String guia = "{\"nome\":\"NomeUsuario\",\"sobrenome\":\"SobrenomeUsuario\",\"cpf\":\"99999999999\",\"email\":\"[email protected]\",\"senha\":\"00000\"}";
    WebClient wc = new WebClient();
    resposta =  wc.post(guia);

    System.out.println(resposta);

Error:

java.net.MalformedURLException: no protocol: localhost//CitourWS//cadastrar_guia.php
at java.net.URL.<init>(Unknown Source)
at java.net.URL.<init>(Unknown Source)
at java.net.URL.<init>(Unknown Source)
at webservice.WebClient.post(WebClient.java:13)
at Main.main(Main.java:76)
    
asked by anonymous 15.06.2017 / 23:58

1 answer

2

The exception is probably due to missing parts of your declared URL.

Switch:

URL url = new URL("localhost/CWS/cadastrar_guia.php");

By:

URL url = new URL("http://localhost/CWS/cadastrar_guia.php");
    
16.06.2017 / 00:12