在实现第三方接口时,通过二进制数据通讯,可以更高效、更灵活、更稳定。
从客户端发起请求的代码如下所示。
protected
static
byte
[] remoteInvoke(
byte
[]
data
)
throws
SomeException {
byte
[]
ret
=
null
;
PostMethod
filePost
=
null
;
try
{
String
targetURL
=
REMOTE_URL
+
sign
;
logger
.debug(
"REMOTE_URL:"
+
targetURL
);
filePost
=
new
PostMethod(
targetURL
);
//增加http 请求输入流
filePost
.setRequestEntity(
new
ByteArrayRequestEntity(
data
,
"text/plain; charset=utf-8"
));
HttpClient
client
=
new
HttpClient();
client
.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
int
status
=
client
.executeMethod(
filePost
);
if
(
status
== HttpStatus.
SC_OK
) {
// 响应回文数组
ret
=
filePost
.getResponseBody();
}
else
{
logger
.debug(
"请求出错,状态:"
+
status
+
","
+
filePost
.getStatusText());
logger
.debug(
"请求出错,响应:"
+
filePost
.getResponseBodyAsString());
throw
new
SomeException(
"请求远端数据失败,"
+
filePost
.getStatusText());
}
}
catch
(IOException
e
){
throw
new
SomeException(
"
请求远端数据
失败,"
+
e
.getMessage(),
e
);
}
finally
{
if
(
filePost
!=
null
){
filePost
.releaseConnection();
}
}
if
(
logger
.isDebugEnabled()){
//logger.debug(String.format("请求:“%s”", SomeUtils.toString(data)));
//logger.debug(String.format("响应:“%s”", SomeUtils.toString(ret)));
}
return
ret
;
}
服务器获取二进制输入的代码如下所示。
protected static String getRequestBody(HttpServletRequest request )
throws
IOException, UnsupportedEncodingException {
final
int
BUFFER_SIZE
= 8 * 1024;
byte
[]
buffer
=
new
byte
[
BUFFER_SIZE
];
ServletInputStream
sis
=
request
.getInputStream();
int
length
= 0;
ByteArrayOutputStream
baos
=
new
ByteArrayOutputStream();
int
length
= 0;
while
((
length
=
sis
.read(
buffer
))>0){
baos
.write(
buffer
, 0,
length
);
}
String
bodyData
=
new
String(
baos
.toByteArray(),
"UTF-8"
);
return
bodyData
;
}