logo资料库

发送Post请求,内容格式为xml,并获取响应内容.doc

第1页 / 共7页
第2页 / 共7页
第3页 / 共7页
第4页 / 共7页
第5页 / 共7页
第6页 / 共7页
第7页 / 共7页
资料共7页,全文预览结束
ChannelDistributor.xml 内容如下: yisou abcd1234 10010000 00 1).HttpClient 发送 Post 请求,内容格式为 xml,并获取响应内容 import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.StringRequestEntity; import org.apache.log4j.Logger; public class ServiceValidate extends HttpServlet{ private Logger log = Logger.getLogger(ServiceValidate.class); private static final long serialVersionUID = -6995391540735187530L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req, resp); } /** * 发送 xml 数据请求到服务器端
* @param url xml 请求数据地址 * @param xmlString 发送的 xml 数据流 * @return null 发送失败,否则返回响应内容 */ @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog"); System.setProperty("org.apache.commons.logging.simplel og.showdatetime", "true"); System.setProperty("org.apache.commons.logging.simplel og.log.org.apache.commons.httpclient", "stdout"); String url = "http://localhost:8080/game/testServlet"; String xmlString = getXmlString(); HttpClient client = new HttpClient(); PostMethod myPost = new PostMethod(url); client.getParams().setSoTimeout(300*1000); String responseString = null; try{ myPost.setRequestEntity(new StringRequestEntity(xmlString,"text/xml","utf-8")); client.executeMethod(myPost); int statusCode = if(statusCode == HttpStatus.SC_OK){ BufferedInputStream bis = new BufferedInputStream(myPost.getResponseBodyAsStream()); ByteArrayOutputStream(); -1){ byte[] bytes = new byte[1024]; ByteArrayOutputStream bos = new int count = 0; while((count = bis.read(bytes))!= bos.write(bytes, 0, count); } byte[] strByte = bos.toByteArray(); responseString = new String(strByte,0,strByte.length,"utf-8"); bos.close(); bis.close();
} }catch (Exception e) { log.error(e.getMessage(), e); } myPost.releaseConnection(); client.getHttpConnectionManager().closeIdleConnections System.out.println("responseString:"+responseString); (0); } /** * 读取 xml 内容,将请求的 xml * 保存成字符串 进行 post 发送 * @return */ private String getXmlString() { StringBuilder sb=new StringBuilder(); try { InputStream inputStream =ServiceValidate.class.getResourceAsStream("/ChannelDistributor.xml"); BufferedReader br=new BufferedReader(new InputStreamReader(inputStream)); String line=""; for(line=br.readLine();line!=null;line=br.read Line()) { sb.append(line+"\n"); } } catch (FileNotFoundException e) { log.error(e.getMessage(), e); } catch (IOException e) { log.error(e.getMessage(), e); } return sb.toString(); } @Override protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req, resp); } } 2).获取 HttpClient Post 请求数据并响应内容
import org.apache.log4j.Logger; public class TestServlet extends HttpServlet{ private static final long serialVersionUID = -6175353394519367540L; private Logger log = Logger.getLogger(TestServlet.class); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req, resp); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { int len = request.getContentLength(); System.out.println("数据流长度:" +len); //获取 HTTP 请求的输入流 InputStream is = request.getInputStream(); //已 HTTP 请求输入流建立一个 BufferedReader 对象 BufferedReader br = new BufferedReader(new InputStreamReader(is,"UTF-8")); //读取 HTTP 请求内容 String buffer = null; StringBuffer sb = new StringBuffer(); while ((buffer = br.readLine()) != null) { //在页面中显示读取到的请求参数 sb.append(buffer+"\n"); } System.out.println("接收 post 发送数 据:\n"+sb.toString().trim()); PrintWriter out = response.getWriter(); StringBuffer stringBuffer = new StringBuffer(""); stringBuffer.append(""); stringBuffer.append("800"); stringBuffer.append("jkuiowerncxuidafjkf daouifdaljkn"); stringBuffer.append(""); out.write(stringBuffer.toString()); out.flush();
out.close(); } catch (Exception e) { log.error(e.getMessage(), e); } } } 控制台输出如下: 数据流长度:175 接收 post 发送数据: yisou abcd1234 10010000 00 responseString:800jkuiowerncx uidafjkfdaouifdaljkn 关于跨域传输 XML 数据,由于刚接触到,碰到了许多问题。这里把一些相关方法记录下来, 也给大家提供一些参考(新手适用,高手请过 嘿嘿)。 Client:通过 HTTP POST 方式请求并接收返回数据。(用于请求别人的接口,并接收返回的数 据) Server:接收 HTTP POST 请求过来的数据并返回数据。(用于别人请求自己的接口,接收请求 数据并返回数据) 下面是大致实现代码: Client: public void test() { try { HttpServletResponse response = ServletActionContext.getResponse(); //设置返回数据的编码类型 response.setCharacterEncoding("GBK"); String xml = "-<-?-xml -version=-"1.0-" -encoding=-"gb2312-" -?->"+ "-<-ddd->-" //里面若干 XML 数据,格式自己改下,被过滤了加些东西 "-<-/ddd->-"; String url = "请求地址";
HttpClient client = new HttpClient(); //设置代理服务器地址和端口 //client.getHostConfiguration().setProxy("proxy_host_addr",proxy_port); //使用 GET 方法,如果服务器需要通过 HTTPS 连接,那只需要将下面 URL 中的 http 换成 https //HttpMethod method = new GetMethod("http://java.sun.com"); //使用 POST 方法 PostMethod post = new PostMethod(url); //设置要发送请求的 XML 数据,这里还可以不用直接发送 XML 数据,可以设置参数 //post.setParameter(key, value); post.setRequestEntity(new StringRequestEntity(xml, "text/xml", "GBK")); //执行请求 client.executeMethod(post); //打印返回的信息 byte[] by = post.getResponseBody(); PrintWriter pw = response.getWriter(); pw.print(new String(by)); //释放连接 post.releaseConnection(); } catch (Exception e) { e.printStackTrace(); } } Server: 这里是关键部分代码 //------------接收物流方请求的 XML 数据----------------------- //获取 request 接收到的流长度,因为这里如果是使用 Struts2 框架,当发送方把 Content-type //设置成 application/x-www-form-urlencoded 会导致传送过来的数据流被过滤掉 //如果这里 len 不为-1,而下面的 br 又为空的话,说明被过滤掉了。 int len = request.getContentLength(); System.out.println("数据流长度:" +len); //获取 HTTP 请求的输入流 InputStream is = request.getInputStream(); //已 HTTP 请求输入流建立一个 BufferedReader 对象 BufferedReader br = new BufferedReader(new InputStreamReader(is,"UTF-8")); //BufferedReader br = request.getReader(); //读取 HTTP 请求内容 String buffer = null; StringBuffer sb = new StringBuffer();
while ((buffer = br.readLine()) != null) { //在页面中显示读取到的请求参数 sb.append(buffer); } 关于解决:request.getInputStream 或 request.getReader()被过滤掉的问题,可以用 JSP 先接收 数据,然后再把 content-type 设置成 xml/text 类型再次请求真正的接口就可以接收到数据。 我是这样想到解决方法的,如果有朋友有更好的方法,请留言给个提示,我也去研究下。 这章内容虽然很简单,但是对于新手的我们来说一出问题可能就会被弄得焦头烂额,大家有 兴趣可以记下,呵呵 百度 httpclient 发送 xml dom4j 解析 xml 你的问题就解决了
分享到:
收藏