Java Reference
In-Depth Information
System . out . println ( line );
line = reader . readLine ();
}
connection . disconnect ();
In this example, we instantiate a URL instance and then open a connection using the
URL.openConnection() method. This method returns a generic URLConnection type, so we
need to typecast it to an HttpURLConnection . Once we have a connection, we set the HTTP
method we are invoking by calling HttpURLConnection.setMethod() . We want XML from
the server, so we call the setRequestProperty() method to set the Accept header. We get
the response code and Content-Type by calling getResponseCode() and getCon-
tentType() , respectively. The getInputStream() method allows us to read the content sent
from the server using the Java streaming API. We finish up by calling disconnect() .
Sending content to the server via a PUT or POST is a little different. Here's an example of
that:
URL url = new
new URL ( "http://example.com/customers" );
HttpURLConnection connection = ( HttpURLConnection ) url . openConnection ();
connection . setDoOutput ( true
true );
connection . setInstanceFollowRedirects ( false
false );
connection . setRequestMethod ( "POST" );
connection . setRequestProperty ( "Content-Type" , "application/xml" );
OutputStream os = connection . getOutputStream ();
os . write ( "<customer id='333'/>" . getBytes ());
os . flush ();
iif ( connection . getResponseCode () != HttpURLConnection . HTTP_CREATED ) {
throw
throw new
new RuntimeException ( "Failed to create customer" );
}
System . out . println ( "Location: " + connection . getHeaderField ( "Location" ));
connection . disconnect ();
In this example, we create a customer by using POST. We're expecting a response of 201,
“Created,” as well as a Location header in the response that points to the URL of our newly
created customer. We need to call HttpURLConnection.setDoOutput(true) . This allows
us to write a body for the request. By default, HttpURLConnection will automatically follow
redirects. We want to look at our Location header, so we call setInstanceFollowRedir-
ects(false) to disable this feature. We then call setRequestMethod() to tell the connec-
tion we're making a POST request. The setRequestProperty() method is called to set the
Content-Type of our request. We then get a java.io.OutputStream to write out the data
and the Location response header by calling getHeaderField() . Finally, we call discon-
nect() to clean up our connection.
Search WWH ::




Custom Search