Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (40.7k points)

In Java, How to compose an HTTP request message and send it to an HTTP WebServer?

1 Answer

0 votes
by (20.3k points)

You can try using java.net.HttpUrlConnection.

public static String executePost(String targetURL, String urlParameters) {

  HttpURLConnection connection = null;

  try {

    //Create connection

    URL url = new URL(targetURL);

    connection = (HttpURLConnection) url.openConnection();

    connection.setRequestMethod("POST");

    connection.setRequestProperty("Content-Type", 

        "application/x-www-form-urlencoded");

    connection.setRequestProperty("Content-Length", 

        Integer.toString(urlParameters.getBytes().length));

    connection.setRequestProperty("Content-Language", "en-US");  

   connection.setUseCaches(false);

    connection.setDoOutput(true);

    //Send request

    DataOutputStream wr = new DataOutputStream (

        connection.getOutputStream());

    wr.writeBytes(urlParameters);

    wr.close();

    //Get Response  

    InputStream is = connection.getInputStream();

    BufferedReader rd = new BufferedReader(new InputStreamReader(is));

    StringBuilder response = new StringBuilder(); // or StringBuffer if Java version 5+

    String line;

    while ((line = rd.readLine()) != null) {

      response.append(line);

      response.append('\r');

    }

    rd.close();

    return response.toString();

  } catch (Exception e) {

    e.printStackTrace();

    return null;

  } finally {

    if (connection != null) {

      connection.disconnect();

    }

  }

}

Related questions

0 votes
1 answer
asked Jul 24, 2019 in Java by Nigam (4k points)
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Oct 9, 2019 in Java by Anvi (10.2k points)

Browse Categories

...