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

0

Because it is giving nullPointerException. I use the same OutPutStream 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 noticed that you have a problem with url.openConnection ().

    
asked by anonymous 01.09.2015 / 16:16

1 answer

2

You can try,

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();
    
01.09.2015 / 18:14