httpclient访问restful

转:http://howtodoinjava.com/2013/05/21/jax-rs-restful-client-using-apache-httpclient/

 

JAX-RS RESTful client using apache httpclient

 

public static void demoPostRESTAPI()  throws Exception
{
     DefaultHttpClient httpClient =  new DefaultHttpClient();
     
     User user =  new User();
     user.setId( 100 );
     user.setFirstName( "Lokesh" );
     user.setLastName( "Gupta" );
     
     StringWriter writer =  new StringWriter();
     JAXBContext jaxbContext = JAXBContext.newInstance(User. class );
     Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
     jaxbMarshaller.marshal(user, writer);
     
     try
     {
         //Define a postRequest request
         HttpPost postRequest =  new HttpPost( "http://localhost:8080/RESTfulDemoApplication/user-management/users" );
         
         //Set the API media type in http content-type header
         postRequest.addHeader( "content-type" "application/xml" );
         
         //Set the request post body
         StringEntity userEntity =  new StringEntity(writer.getBuffer().toString());
         postRequest.setEntity(userEntity);
          
         //Send the request; It will immediately return the response in HttpResponse object if any
         HttpResponse response = httpClient.execute(postRequest);
         
         //verify the valid error code first
         int statusCode = response.getStatusLine().getStatusCode();
         if (statusCode !=  201 )
         {
             throw new RuntimeException( "Failed with HTTP error code : " + statusCode);
         }
     }
     finally
     {
         //Important: Close the connect
         httpClient.getConnectionManager().shutdown();
     }
}
 
就是关键的 postRequest.addHeader( "content-type" "application/xml" );

你可能感兴趣的:(httpclient)