Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1102316
  • 博文数量: 1310
  • 博客积分: 3980
  • 博客等级: 中校
  • 技术积分: 8005
  • 用 户 组: 普通用户
  • 注册时间: 2008-05-09 22:05
文章分类

全部博文(1310)

文章存档

2011年(1)

2008年(1309)

我的朋友

分类:

2008-11-09 15:50:02

The previous message only explains how to create service, this message will describe how to create client and invoke server side. Actually, JSR-311 only defined the server API, so, each vendor will have different ideas on client. But one common way is to use Apache Http Common Client lib. Please see following examples.

1. GET a customer

// Sent HTTP GET request to query customer info

System.out.println(
"Sent HTTP GET request to query customer info");

URL url 
= new URL("http://localhost:8080/vendor_search/services/customerservice/customers/123");

InputStream in 
= url.openStream();

System.out.println(getStringFromInputStream(in)); 
//NOTE, return an input stream, you need convert xml to Java Object by yourself
2. Use PUT to update a customer


System.out.println("Sent HTTP PUT request to update customer info");

Client client 
= new Client();

String inputFile 
= client.getClass().getResource("update_customer.txt").getFile();

File input 
= new File(inputFile);

PutMethod put 
= new PutMethod("http://localhost:8080/vendor_search/services/customerservice/customers");

RequestEntity entity 
= new FileRequestEntity(input, "text/xml; charset=ISO-8859-1");

put.setRequestEntity(entity);

HttpClient httpclient 
= new HttpClient();



try {

int result = httpclient.executeMethod(put);

System.out.println(
"Response status code: " + result);

System.out.println(
"Response body: ");

System.out.println(put.getResponseBodyAsString());

finally {

// Release current connection to the connection pool once you are

// done

put.releaseConnection();

}
3. Use POST to add a customer

System.out.println(
"Sent HTTP POST request to add customer");

inputFile 
= client.getClass().getResource("add_customer.txt").getFile();

input 
= new File(inputFile);

PostMethod post 
= new PostMethod("http://localhost:8080/vendor_search/services/customerservice/customers");

post.addRequestHeader(
"Accept" , "text/xml");

entity 
= new FileRequestEntity(input, "text/xml; charset=ISO-8859-1");

post.setRequestEntity(entity);

httpclient 
= new HttpClient();



try {

int result = httpclient.executeMethod(post);

System.out.println(
"Response status code: " + result);

System.out.println(
"Response body: ");

System.out.println(post.getResponseBodyAsString());

finally {

// Release current connection to the connection pool once you are

// done

post.releaseConnection();

}

So, for this way provided by Apach Common Http Client, the user still need think about the convention from XML to POJO. It is not so convenience. We will provide a utility class to simply this process.



Justin Chen 2008-11-05 22:48 发表评论
阅读(362) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~