1.http接口开发,发送xml(报文),接受服务器发来的报文
首先去apache官网:http://hc.apache.org/下载相关jia包
看我的jar包:commons-codec-1.6.jar
commons-logging-1.1.3.jar
fluent-hc-4.3.4.jar
httpclient-cache-4.3.4.jar
httpcore-4.3.2.jar
httpmime-4.3.4.jar
commons-httpclient-3.1.jar
客户端:
public static void main(String[] args) {
String xml = "<?xml version="
+ "\"1.0\""
+ " encoding="
+ "\"UTF-8\""
+ "?><SDRequest><TransactionName>CreateDataFileComplete</TransactionName><IdentityInfo><Code>"
+ 1 + "</Code><Description></Description><Timestamp>"
+ "20100315140542" + "</Timestamp></IdentityInfo></SDRequest>";// 新接的一个项目接口,非要用xml请求,找不到别的post方式,最终选用这种方式,将参数拼成xml字符串
//发送之前可以根据业务要求进行数据库或其它操作
// File input = new File("test.xml");//如果是xml文件,可以这样写
PostMethod post = new PostMethod(" 请求地址
// 设置请求的内容直接从文件中读取sssssssssssO
// post.setRequestBody( new FileInputStream(input));
// if (input.length() < Integer.MAX_VALUE)
// post.setRequestContentLength(input.length());
// else
// post.setRequestContentLength(EntityEnclosingMethod.CONTENT_LENGTH_CHUNKED);
post.setRequestBody(xml);// 这里添加xml字符串
// 指定请求内容的类型
post.setRequestHeader("Content-type", "text/xml; charset=iso-8859-1");
HttpClient httpclient = new HttpClient();// 创建 HttpClient 的实例
int result;
try {
result = httpclient.executeMethod(post);
System.out.println("Response status code: " + result);// 返回200为成功
System.out.println("Response body: ");
System.out.println(post.getResponseBodyAsString());// 接受返回的内容之后,可以根据业务需求进行数据库或其它操作
post.releaseConnection();// 释放连接
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
服务端
首先web.xml中
<servlet>
<servlet-name>GenXmlServlet</servlet-name>
<servlet-class>com.GenXmlServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>GenXmlServlet</servlet-name>
<url-pattern>/GenXmlServlet</url-pattern>
</servlet-mapping>
业务处理类:
public class GenXmlServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//String xml = req.getParameter("xml");
resp.setContentType("text/xml");
resp.setCharacterEncoding("GBK");
PrintWriter out = resp.getWriter();
// out.println(xml);
// System.out.println(xml);
System.out.println("----------------------");
InputStreamReader reader = new InputStreamReader(req.getInputStream(),
"GBK");
char[] buff = new char[1024];
int length = 0;
while ((length = reader.read(buff)) != -1) {
String x = new String(buff, 0, length);
System.out.println(x);//输出客户端请求的xml信息,得到之后可以根据业务需求进行数据库或其它操作,把需要返回给客户端的消息用out.print("返回的消息")返回。
out.print(x);
}
}
}
后面可能会发送json到服务器,用到了,我再更新出来。
爱生活,爱分享,爱康宝。有问题请大家提出。欢迎分享。