在编写接口之前我们需要一个连接,所以我们先写一个连接,直接上代码。
<span style="font-size:14px;"> /**
* Http Post请求方式
* @param method 请求方式POST
* @param str 请求报文
* @param url 请求路径
* @return 返回的状态
* @throws IOException
*/
public static String readFromPost(String method, String str, String url)
throws IOException {
//str = URLEncoder.encode(str, "GBK");
// Post请求的url,与get不同的是不需要带参数
URL postUrl = new URL(url);
// 打开连接
HttpURLConnection connection = (HttpURLConnection) postUrl
.openConnection();
// Output to the connection. Default is
// false, set to true because post
// method must write something to the
// connection
// 设置是否向connection输出,因为这个是post请求,参数要放在
// http正文内,因此需要设为true
connection.setDoOutput(true);
// Read from the connection. Default is true.
connection.setDoInput(true);
// Set the post method. Default is GET
connection.setRequestMethod(method);
// Post cannot use caches
// Post 请求不能使用缓存
connection.setUseCaches(false);
// This method takes effects to
// every instances of this class.
// URLConnection.setFollowRedirects是static函数,作用于所有的URLConnection对象。
// connection.setFollowRedirects(true);
// This methods only
// takes effacts to this
// instance.
// URLConnection.setInstanceFollowRedirects是成员函数,仅作用于当前函数
connection.setInstanceFollowRedirects(true);
// Set the content type to urlencoded,
// because we will write
// some URL-encoded content to the
// connection. Settings above must be set before connect!
// 配置本次连接的Content-type,配置为application/x-www-form-urlencoded的
// 意思是正文是urlencoded编码过的form参数,下面我们可以看到我们对正文内容使用URLEncoder.encode
// 进行编码
connection.setRequestProperty("Connection", "Keep-Alive");//维持长连接
connection.setRequestProperty("Charset", "UTF-8");
connection.setRequestProperty("Content-Length", String.valueOf(str.getBytes("UTF-8").length));
connection.setRequestProperty("Content-Type",
"text/xml; charset='UTF-8'");
// 连接,从postUrl.openConnection()至此的配置必须要在connect之c前完成,
// 要注意的是connection.getOutputStream会隐含的进行connect。
connection.connect();
DataOutputStream out = new DataOutputStream(
connection.getOutputStream());
// The URL-encoded contend
// 正文,正文内容其实跟get的URL中'?'后的参数字符串一致
//String content = URLEncoder.encode(str, "GBK");
// DataOutputStream.writeBytes将字符串中的16位的unicode字符以8位的字符形式写道流里面
out.write(str.getBytes("UTF-8"));
out.flush();
out.close(); // flush and close
BufferedReader reader = new BufferedReader(new InputStreamReader(
connection.getInputStream(), "UTF-8"));// 设置编码,否则中文乱码
String line = "";
StringBuffer sb = new StringBuffer();
while ((line = reader.readLine()) != null) {
// line = new String(line.getBytes(), "utf-8");
sb.append(line);
}
connection.disconnect();
// return URLDecoder.decode(sb.toString(), "GBK");
return sb.toString();
}</span>
在其中有链接、发送报文、发送地址。以及取回对方接收状态消息。
有了链接的方法,接下来就需要接收链接以后发送过来的数据了。
<span style="font-size:14px;">public void xxget() throws Exception{
// TODO Auto-generated method stub
HttpServletResponse response = ServletActionContext.getResponse();
HttpServletRequest request = ServletActionContext.getRequest();
//读客户端发送的数据
InputStream ins = request.getInputStream();
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = -1;
while((len=ins.read(buffer))!=-1){
outStream.write(buffer,0,len);
}
outStream.close();
ins.close();
String str = new String(outStream.toByteArray(),"UTF-8");
str = URLDecoder.decode(str, "UTF-8");
System.out.println("---收到webService命令---");</span><pre name="code" class="java"><span style="font-size:14px;"> //解析xml获取数据
parseXml(str)</span>
//根据数据返回接收状态
xxsend("状态码");
//根据解析数据进行相应操作} 状态返回
<span style="font-size:14px;"> /**
* 服务端响应请求
* @param msg
* @throws Exception
*/
private void xxsend(String msg) throws Exception{
HttpServletResponse response = ServletActionContext.getResponse();
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>拼接你的状态码";
//编码
response.setContentType("text/html;charset=utf-8");
String content = URLEncoder.encode(xml, "UTF-8");
response.getWriter().write(content);
}</span>
处理完数据之后需要给对方返回你的处理结果数据。
<span style="font-size:14px;">private void xxpost(待返回的数据)throws Exception{
//组装为请求报文
String xml = "";
String content = URLEncoder.encode(xml, "UTF-8");
//取得对方的连接方法
String url ="";
try {
String result=readFromPost("POST", content, url);
//解析对方反馈结果result,确定是重发还是结束
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
</span>
至此你与对方的链接、数据发送与反馈和对方与你的链接、数据发送与反馈就结束了。
也许写的有不足之处还望大牛们指正,在下感激不尽。。