0

I want to create an http request based on an URL in Java and change some of its headers or add new headers; then, receive the corresponding http response for that request and gets its header values and its content. How can I do this as simple as possible?

moorara
  • 3,897
  • 10
  • 47
  • 60
  • 5
    Use Apache HTTP Client. Java also has URL class, which you can use to create URLConnection object. – nhahtdh Sep 23 '12 at 10:17
  • Sample code for using Java's URL class to create URLConnection, set header and send request: http://stackoverflow.com/questions/331538/what-is-the-proper-way-of-setting-headers-in-a-urlconnection – nhahtdh Sep 23 '12 at 10:27
  • @nhahtdh got it right. You could have used Google search service as well. – Nishant Sep 23 '12 at 10:27

2 Answers2

3

Indeed use apache httpclient 4.x and use a ResponseHandler.

HttpClient has a lot of good stuff that you probably want that the raw Java API does not provide like multi threaded use, connection pooling, support for various authentication mechanisms, etc.

Below is a simple example that executes a get and returns you the body as a String.

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

...

DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://www.google.com");
httpGet.addHeader("MyHeader", "MyValue");

try {
    String body = httpClient.execute(httpGet, new ResponseHandler<String>() {

        @Override
        public String handleResponse(HttpResponse response) throws IOException {
            Header firstHeader = response.getFirstHeader("MyHeader");
            String headerValue = firstHeader.getValue();
            return EntityUtils.toString(response.getEntity());
        }
    });
} catch (IOException e) {
    e.printStackTrace();
}
Jilles van Gurp
  • 7,927
  • 4
  • 38
  • 46
2

You can use Apache HTTP client or implement it using the standard HttpUrlConnection

    URL url = new URL("http://thehost/thepath/");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod(method); // GET, POST, ...
    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.addRequestProperty(key, value); // this way you can set HTTP header
AlexR
  • 114,158
  • 16
  • 130
  • 208