Is there something wrong with this code that sends a String to the server?

Asked

Viewed 68 times

0

Because it is giving nullPointerException. I use Outputstream even to send to the server?

public void envia(String minhastring) {

    HttpURLConnection conn = null;
    URL url = null;
    try {
        url = new URL(
                "http://minhaURL");
        conn = (HttpsURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        OutputStreamWriter wr = new OutputStreamWriter(
                conn.getOutputStream());
        wr.write(minhastring);
        wr.flush();

    } catch (IOException e) {
        System.out.println("Erro ao se conectar com o servidor");
        e.printStackTrace();
    } finally {
        conn.disconnect();
    }

}

When I debugged, I realized that you have a problem with the.openConnection url().

  • You could post the stack trace?

  • 1

    Could be the protocol, your URL is http and Voce is casting for Httpsurlconnection

  • David, do you know how I can solve this?

  • I put a possible solution, you need to provide more information about the error...

1 answer

2


You can try it,

URL url = new URL( "http://minhaURL" );
HttpURLConnection conn = ( HttpURLConnection ) url.openConnection();
conn.setRequestProperty( "Content-length",  minhastring.length() ); 
conn.setRequestProperty( "Content-Type","application/x-www- form-urlencoded" ); 
conn.setDoOutput(true);
conn.setRequestMethod("POST");
OutputStreamWriter wr = new OutputStreamWriter( conn.getOutputStream());
wr.write(minhastring);
wr.flush();
  • thanks, it was missing the Requestproperty, now it worked!

  • I’m glad I could help!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.