Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send HTTP request in java? [duplicate]

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

like image 338
Yatendra Avatar asked Aug 31 '09 22:08

Yatendra


People also ask

How do I duplicate HTTP requests?

There is no such thing as a duplicate http request. Http is designed to accept multiple requests in parallel, often with the same parameters - you need to design your program to be able to deal with this situation. To prevent it you could use a clickshield.


2 Answers

You can use java.net.HttpUrlConnection.

Example (from here), with improvements. Included in case of link rot:

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();     }   } } 
like image 163
duffymo Avatar answered Sep 21 '22 02:09

duffymo


From Oracle's java tutorial

import java.net.*; import java.io.*;  public class URLConnectionReader {     public static void main(String[] args) throws Exception {         URL yahoo = new URL("http://www.yahoo.com/");         URLConnection yc = yahoo.openConnection();         BufferedReader in = new BufferedReader(                                 new InputStreamReader(                                 yc.getInputStream()));         String inputLine;          while ((inputLine = in.readLine()) != null)              System.out.println(inputLine);         in.close();     } } 
like image 22
Chi Avatar answered Sep 17 '22 02:09

Chi