Make HTTP POST Or GET Request From Java
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¶m2=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();
}}











(3 votes)
RSS Feeds 



January 16th, 2008 at 6:38 am
Thanks, this has been useful.
-Frank
February 22nd, 2008 at 11:02 am
Hello!….I whant make 1 page of internet and i don’t know how …Can you help me?Plz contact me !!!
May 7th, 2008 at 1:56 pm
How do I properly create the reader object for the postData function?
May 7th, 2008 at 4:11 pm
Update: this works
new StringReader(”type=1&keyword=abc”)
June 11th, 2008 at 8:29 am
thanks, this was really helpful!
June 12th, 2008 at 8:08 pm
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?
June 13th, 2008 at 12:29 am
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();
October 30th, 2008 at 2:04 pm
java method post example
November 9th, 2008 at 9:22 am
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 ????
January 3rd, 2009 at 1:49 am
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.
January 20th, 2009 at 3:32 am
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!
January 29th, 2009 at 12:24 pm
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?
January 31st, 2009 at 1:40 am
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
March 30th, 2009 at 3:51 am
you touch my trallalaaaaaaa
May 5th, 2009 at 2:51 am
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
September 11th, 2009 at 4:58 am
This is great.. Thanks.
September 15th, 2009 at 10:57 pm
Nice one!!! thanks
October 4th, 2009 at 6:26 pm
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!
November 2nd, 2009 at 4:13 am
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);
February 9th, 2010 at 6:14 am
thanks works g8
March 28th, 2010 at 3:16 pm
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
March 31st, 2010 at 1:41 am
In your servlet just read the InputStream coming from the HttpServletRequest
April 13th, 2010 at 3:48 am
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.
May 3rd, 2010 at 10:42 am
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.
May 4th, 2010 at 10:24 am
@srini
Just look at Brian’s comment (#7)
June 25th, 2010 at 11:07 am
Where can I find the HTTPUtil package? I can not seem to find it.
June 27th, 2010 at 3:41 am
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.
July 7th, 2010 at 7:45 am
Thanks! This is very handy. Will be using it on the site.
August 10th, 2010 at 12:11 pm
http://get.java.com
September 8th, 2010 at 1:14 am
hi ty very much