Java Reference
In-Depth Information
cessful response is 201, “Created.” Also, a
Location
response header is returned that points
to the newly created customer:
import
import
org.apache.http.*
org.apache.http.*
;
import
import
org.apache.http.client.*
org.apache.http.client.*
;
import
import
org.apache.impl.client.*
org.apache.impl.client.*
;
public
public class
class
MyClient
MyClient
{
public
public static
static
void
void
main
(
String
[]
args
)
throws
throws
Exception
{
DefaultHttpClient client
=
new
new
DefaultHttpClient
();
HttpPost post
=
new
new
HttpPost
(
"http://example.com/customers"
);
StringEntity entity
=
new
new
StringEntity
(
"<customer id='333'/>"
);
entity
.
setContentType
(
"application/xml"
);
post
.
setEntity
(
entity
);
HttpClientParams
.
setRedirection
(
post
.
getParams
(),
false
false
);
HttpResponse response
=
client
.
execute
(
post
);
iif
(
response
.
getStatusLine
().
getStatusCode
() !=
201
) {
throw
throw new
new
RuntimeException
(
"Operation failed: "
+
response
.
getStatusLine
().
getStatusCode
());
}
String location
=
response
.
getLastHeader
(
"Location"
)
.
getValue
();
System
.
out
.
println
(
"Object created at: "
+
location
);
System
.
out
.
println
(
"Content-Type: "
+
response
.
getEntity
().
getContentType
().
getValue
());
BufferedReader reader
=
new
new
InputStreamReader
(
response
.
getEntity
().
getContent
()));
new
BufferedReader
(
new
String line
=
reader
.
readLine
();
while
while
(
line
!=
null
null
) {
System
.
out
.
println
(
line
);
line
=
reader
.
readLine
();
}
client
.
getConnectionManager
().
shutdown
();
}
}
We create an
org.apache.http.entity.StringEntity
to encapsulate the XML we want
to send across the wire. We set its
Content-Type
by calling
StringEntity.setContentType()
. We add the entity to the request by calling
Ht-