转: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"
);
相关推荐
使用HttpClient4.3版本,使用Springmvc的restful方式访问后台的服务
NULL 博文链接:https://chnwaterloo.iteye.com/blog/690549
##如何访问服务器通过httpClient对RESTfulAPI进行访问,这里需要注意的是参数和中文编码问题;httpClient.getParams().setContentCharset("UTF-8");以及如何填充参数,这里针对get和post方法分成两种填充方式,一种...
通过登陆验证后,访问固定接口进行文件下载,通过操作access和sqlite实现信息存储,通过zip进行压缩打包
A http request engine based on Volley and OkHttp, giving up Apache HttpClient request. supports image loading, restful api requesting, and file downloading. READ MORE Dependency binary on jcenter ...
RESTful Box 客户端 最近,我的客户请求使用基于 Java 的 RESTful 客户端向 Box 文件存储服务发出后端请求。 最初,我认为我会使用 java.net 库来完成此操作。 显然,cookie 管理存在一些我尚未解决的错误。 由于我...
* 包括`Database`, `Cache`, `HttpClient`, `Session`, `Storage`, `Upload` 等支持多驱动,可以适应不同环境的需求,其中数据库支持 `MySQL`, `MySQLI`, `Mongo`, `SQLite`, `Postgre`,缓存支持 `Memcache`, `File...
使用步骤(Google Chrome) ...替换 HttpClient 工具类以适配更多的Restful服务。 把 json 示例文件替换成官方的示例文件。 更改写死的模板。让生成的 word 的内容都从 Swagger api 中来。 版本:Swa
分布式架构的核心思想是采用大量廉价的PC Server,构建一个低成本、高可用、高可扩展、高吞吐的集群系统,以支撑海量的用户访问和数据存储,理论上具备无限的扩展能力。分布式系统的设计,是一门复杂的学问,它涉及...
在开放平台体系下,OAuth协议如何保障ISV对数据的访问是经过授权的合法行为。 3.1 常见的Web攻击手段 128 3.1.1 XSS攻击 128 3.1.2 CRSF攻击 130 3.1.3 SQL注入攻击 133 3.1.4 文件上传漏洞 139 3.1.5...
配置nginx插件访问图片.avi │ 08.测试图片上传.avi │ 09.FastDFS工具类的使用.avi │ 10.图片上传过程分析.avi │ 11.图片上传Service.avi │ 12.图片上传完成.avi │ 13.解决火狐兼容性问题.avi │ 14.spring的...