您好,欢迎来到年旅网。
搜索
您的当前位置:首页httpclient访问restful

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( "" );
         
         //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" );

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- oldu.cn 版权所有 浙ICP备2024123271号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务