工作中为第三方厂商提供HTTP接口,第三方传送请求报文给我们,我们自己进行相应的业务处理之后返回给第三方相应报文。
自己编写完服务端之后,还需要写个客户端进行模拟测试,以下用POST方式向HTTP接口发送数据。
编写客户端需要用到以下两个包,专门用于java客户端的开发:
传递相应的参数,通过POST方式调用HTTP接口:
<span style="font-family:Microsoft YaHei;"><span style="white-space:pre"> </span><span style="font-size:14px;">public static void main(String[] args) throws Exception {
</span></span><pre><span style="font-family:Microsoft YaHei;"><span style="font-size:14px;"> TestHttpPost test = new TestHttpPost();
</span></span><span style="font-family:Microsoft YaHei;"><span style="font-size:14px;"> String xmlFilePath1 = "C:\\Users\\test.xml";
</span></span><span style="font-family:Microsoft YaHei;"><span style="font-size:14px;"> String url = "http://localhost:8001/servlet";
</span></span><span style="font-family:Microsoft YaHei;"><span style="font-size:14px;"> test.postHttpRequest(xmlFilePath1,url);
</span></span><span style="font-family:Microsoft YaHei;"><span style="font-size:14px;"> }</span></span>
<span style="font-family:Microsoft YaHei;"> /**
<span style="font-size:14px;"> * 发送POST请求
* @param xmlFilePath 请求文件路径
* @param url 接口访问地址
* @throws Exception
*/
public void postHttpRequest(String xmlFilePath,String url) throws Exception{
SAXReader saxReader = new SAXReader();
Document document = saxReader.read(new FileInputStream(new File(xmlFilePath)));
String requestXml = document.asXML();
HttpPost httpPost = null;
try {
// 定义HttpPost请求
httpPost = new HttpPost(url);
// 定义请求实体
HttpEntity requestEntity = new StringEntity(requestXml, "UTF-8");
httpPost.setEntity(requestEntity);
// 定义HttpClient
HttpClient httpClient = new DefaultHttpClient();
HttpParams httpParams = httpClient.getParams();
// 设置Http协议的版本
httpParams.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
// 设置请求连接超时时间
httpParams.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 1000);
// 设置请求响应超时时间
httpParams.setParameter(CoreConnectionPNames.SO_TIMEOUT, 50000);
// 以post方式发送Http请求
HttpResponse httpResponse = httpClient.execute(httpPost);
// 获取响应实体
HttpEntity responsetEntity = httpResponse.getEntity();
InputStream inputStream = responsetEntity.getContent();
StringBuilder reponseXml = new StringBuilder();
byte[] b = new byte[2048];
int length = 0;
while ((length = inputStream.read(b)) != -1) {
reponseXml.append(new String(b, 0, length));
}
//将返回的报文打印出来
System.out.println(URLDecoder.decode(reponseXml.toString(), "UTF-8") );
} catch (Exception e) {
if(SocketTimeoutException.class.isInstance(e)){
throw new RuntimeException("Http请求响应超时",e);
}
else if(ConnectException.class.isInstance(e)){
throw new RuntimeException("Http请求异常", e);
}else{
throw new RuntimeException("其他异常", e);
}
} finally{
//释放请求的连接
if(httpPost!=null){
httpPost.abort();
}
}
}</span></span>