1/8/2008

Make HTTP POST Or GET Request From Java

Filed under: — Aviran Mordo @ 5:36 am

In this day of age where many applications need to communicate with web servers you need to make a simple HTTP call to the server. Usually There are two types of calls you’ll need to make an HTTP GET or HTTP POST. So instead of blabbing words, here is a code sample of how you do it.

Code example (sorry for the lack of formatting):


package HTTPUtil;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLConnection;

public class HTTPRequestPoster
{
/**
* Sends an HTTP GET request to a url
*
* @param endpoint - The URL of the server. (Example: " http://www.yahoo.com/search")
* @param requestParameters - all the request parameters (Example: "param1=val1&param2=val2"). Note: This method will add the question mark (?) to the request - DO NOT add it yourself
* @return - The response from the end point
*/
public static String sendGetRequest(String endpoint, String requestParameters)
{
String result = null;
if (endpoint.startsWith("http://"))
{
// Send a GET request to the servlet
try
{
// Construct data
StringBuffer data = new StringBuffer();

// Send data
String urlStr = endpoint;
if (requestParameters != null && requestParameters.length () > 0)
{
urlStr += "?" + requestParameters;
}
URL url = new URL(urlStr);
URLConnection conn = url.openConnection ();

// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuffer sb = new StringBuffer();
String line;
while ((line = rd.readLine()) != null)
{
sb.append(line);
}
rd.close();
result = sb.toString();
} catch (Exception e)
{
e.printStackTrace();
}
}
return result;
}

/**
* Reads data from the data reader and posts it to a server via POST request.
* data - The data you want to send
* endpoint - The server's address
* output - writes the server's response to output
* @throws Exception
*/
public static void postData(Reader data, URL endpoint, Writer output) throws Exception
{
HttpURLConnection urlc = null;
try
{
urlc = (HttpURLConnection) endpoint.openConnection();
try
{
urlc.setRequestMethod("POST");
} catch (ProtocolException e)
{
throw new Exception("Shouldn't happen: HttpURLConnection doesn't support POST??", e);
}
urlc.setDoOutput(true);
urlc.setDoInput(true);
urlc.setUseCaches(false);
urlc.setAllowUserInteraction(false);
urlc.setRequestProperty("Content-type", "text/xml; charset=" + "UTF-8");

OutputStream out = urlc.getOutputStream();

try
{
Writer writer = new OutputStreamWriter(out, "UTF-8");
pipe(data, writer);
writer.close();
} catch (IOException e)
{
throw new Exception("IOException while posting data", e);
} finally
{
if (out != null)
out.close();
}

InputStream in = urlc.getInputStream();
try
{
Reader reader = new InputStreamReader(in);
pipe(reader, output);
reader.close();
} catch (IOException e)
{
throw new Exception("IOException while reading response", e);
} finally
{
if (in != null)
in.close();
}

} catch (IOException e)
{
throw new Exception("Connection error (is server running at " + endpoint + " ?): " + e);
} finally
{
if (urlc != null)
urlc.disconnect();
}
}

/**
* Pipes everything from the reader to the writer via a buffer
*/
private static void pipe(Reader reader, Writer writer) throws IOException
{
char[] buf = new char[1024];
int read = 0;
while ((read = reader.read(buf)) >= 0)
{
writer.write(buf, 0, read);
}
writer.flush();
}

}

 

29 Responses to “Make HTTP POST Or GET Request From Java”

  1. Frank Says:

    Thanks, this has been useful.

    -Frank

  2. xavier Says:

    Hello!….I whant make 1 page of internet and i don’t know how …Can you help me?Plz contact me !!!

  3. Brian Says:

    How do I properly create the reader object for the postData function?

  4. Brian Says:

    Update: this works
    new StringReader(”type=1&keyword=abc”)

  5. elmih Says:

    thanks, this was really helpful!

  6. Dave Says:

    The “postData()” method does not work. I can’t find a sample on line that does. Every time I get the same thing:
    Server returned HTTP response code: 405 for URL

    If not that error, other samples give this:
    Unexpected end of file from server

    Why can’t people post working samples? IF I’m suppose to set headers to do a post expected by the server I hit, HOW do I find our what headers need to be set?

  7. Brian Says:

    URL formAction = new URL(”http://targetsite.com/search.php”);
    FileWriter fw = new FileWriter (”results.html”);
    postData(new StringReader(”type=1&keyword=abc”), formAction, fw);
    fw.close();

  8. Anonymous Says:

    java method post example

  9. Xenome Says:

    Very strange … when i comment the part of the code concerned with printing the response the querystring is not sent and not received at the servlet i don’t understand why ????

  10. Lenin Says:

    From where do i actually read the response receive from the POST request?
    My code looks something like this:

    FileWriter fw = new FileWriter (”results.html”);
    URL formAction = new URL(”my url”);
    postData(new StringReader(”my arguments”),formAction,fw);
    fw.close();

    There is no file such as results.html created in the current folder.

  11. bananahom Says:

    String file_name = “result.html”;

    URL formAction = new URL(”http://192.168.1.1/target_path”);
    FileWriter fw = new FileWriter(file_name);
    postData(new StringReader(xml_data), formAction, fw);

    i use the above code, it’s work!

  12. sufu Says:

    Hey, can you guys explain how to enter the xml_data? Is there any particular format or something for that? Also, wht is the file name that you mention in the FileWriter supposed to stand for?

  13. Aviran Mordo Says:

    you send xml_data as String just like any other data. The file_name is the file where the response from the server would be written to

  14. asd Says:

    you touch my trallalaaaaaaa

  15. Philip Says:

    Hi
    In my application, I want to create a file and write some xml to it. Then aome other application procees it and delete it. So I may need to create a file and write. Using the above code where it is writing, since no file is there. I tried to run locally, it is not creating any file , so it could not read. some confusion, please give a reply
    Philip

  16. johan Says:

    This is great.. Thanks.

  17. Abhishek Dilliwal Says:

    Nice one!!! thanks :)

  18. djslash Says:

    And if i have to save the content of a web site which has a sign-on screen? I have set the post method and the parameters but there will be just the sign-in screen in the html file. Please help me! :)

  19. Aviran Mordo Says:

    First you need to authenticate with the login page. After you authenticate use the HttpState and set it with the next http call

    httpclientLogin.executeMethod(post);

    httpclient2.setHttpState(httpclientLogin.getState());
    httpclient2.executeMethod(post);

  20. leon Says:

    thanks works g8

  21. Nuno Says:

    Good afternoon,
    Thanks for this code. It was very useful. I need a server that can read the information sent in the variable “data”. That is, if I send a string with the variable data how can i do to read that information from the server side?
    thank you very much

  22. Aviran Mordo Says:

    In your servlet just read the InputStream coming from the HttpServletRequest

  23. billy Says:

    thanks for the code Aviran.I would like to send http requests to a server through gui components (e.g swing controls) then display results in lists.For example I want to enter search queries in a combo box in a client, then send the request to a server. if the request is successful my search results will be displayed in a list.

  24. srini Says:

    hi,

    my requirement is when ever user submit the request it should invoke http post request which should append user name and pwd and form details should send as post body.

    can you please help how to do this.

  25. Aviran Mordo Says:

    @srini
    Just look at Brian’s comment (#7)

  26. Patrick Says:

    Where can I find the HTTPUtil package? I can not seem to find it.

  27. Aviran Mordo Says:

    HTTPUtil is just a sample. Just copy the code and paste it into a file. You can rename the package name to be whatever you want.

  28. Akila Gunaratne Says:

    Thanks! This is very handy. Will be using it on the site.

  29. Anonymous Says:

    http://get.java.com

Leave a Reply

You must have Javascript enabled in order to submit comments.

All fields are optional (except comment).
Some comments may be held for moderation (depends on spam filter) and not show up immediately.
Links will automatically get rel="nofollow" attribute to deter spammers.

Powered by WordPress