---
title: "通过HttpURLConnection发送XML字符串流"
author: "javadonkey"
date: "2008-07-15T14:00:41Z"
tags: [".net", "ASP", "ASP.net", "Struts", "XML"]
categories: ["编程语言"]
slug: "httpurlconnection-xml"
draft: false
lastmod: "2008-07-15T14:00:41Z"
id: 214950
url: "https://javadonkey.iteye.com/blog/214950"
---

今天干活时有个需求，要和.net进行一次交互，想在Struts的Action中接收.net通过HTTPt发过来的XML格式的字符流！然后就解析这个XML字符串通过一些处理然后存数据库。

在做完解析过程和存数据库后，想自己测试一下，所以就想到了通过JDK的HttpURLConnection向自己的Action发送一个用于测试的XML格式的字符流，然后就出现了以下的代码


```java

public class TestClientRegist extends TestCase {

public void testRegist(){
    try{

          // 用于测试，读的自己本地的XML文件
           FileInputStream input = new FileInputStream(new File("regist.xml"));

          // Action地址
          URL url = new URL("http://localhost:8080/fstm/rmi/client/regist.do");
          HttpURLConnection conn = (HttpURLConnection)url.openConnection();
          conn.setDoOutput(true);
          conn.setRequestMethod("POST");

           byte[] b = new byte[1024];
          int l = 0;
          OutputStream out = conn.getOutputStream();
          out.write("data=".getBytes());
          while((l = input.read(b, 0, b.length)) != -1){
                 out.write(b, 0, l);
          }
          out.close();
          InputStream in = conn.getInputStream();
          in.close();
         }catch(Exception ex){
                ex.printStackTrace();
       }
   }
}
```

这些代码是没问题的啦。但没用过这东西，刚开始出了好多问题。

1，第一次在下面没有获取“输入流”，发现没执行时没有反应，Action那边也没有调用

加上以后就好了。问了个“高人”才明白，这里需要建立一次连接，当执行完输出流后。还要接收HTTP的响应。还遇到一些别的问题就不在罗嗦了~~~~大家有什么问题可以来多讨论讨论。

有什么高见请赐教。一定认真接受。

下面在给出Action接收的代码


```java

public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {

		try {
			InputStream in = request.getInputStream();
			
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			StringBuffer data = new StringBuffer();
			String line = null;
			while((line = br.readLine()) != null){
				data.append(line);
			}
			logger.debug(data);
			clientMgr.doRegistManager(data.toString());
// 设置返回状态			
response.setStatus(HttpServletResponse.SC_OK);
		} catch (Exception ex) {
			response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
			logger.warn("", ex);
		}
		return null;
	}

```