servlet读取xml格式的post数据时间:2022-06-13 16:02:58 服务器端代码: rundata.getModuleInfo().setLayoutTemplate(null);HttpServletRequest request = rundata.getRequest();HttpServletResponse response = rundata.getResponse();PrintWriter printWriter = null;ServletInputStream sis = null;String xmlData = null;try {printWriter = response.getWriter();// 取HTTP请求流sis = request.getInputStream();// 取HTTP请求流长度int size = request.getContentLength();// 用于缓存每次读取的数据byte[] buffer = new byte[size];// 用于存放结果的数组byte[] xmldataByte = new byte[size];int count = 0;int rbyte = 0;// 循环读取while (count < size) { // 每次实际读取长度存于rbyte中rbyte = sis.read(buffer); for(int i=0;i<rbyte;i++) {xmldataByte[count + i] = buffer[i];}count += rbyte;}xmlData = new String(xmldataByte, "UTF-8"); 客户端代码: HttpClient httpClient = new HttpClient();String xmlData = getInput();int xmlDataLength = xmlData.getBytes("UTF-8").length;PostMethod method = new PostMethod(url);method.setRequestBody(xmlData);method.setRequestHeader("Content-type", "text/xml; charset=UTF-8");if (xmlDataLength < Integer.MAX_VALUE) {method.setRequestContentLength(xmlDataLength);} else {method.setRequestContentLength(EntityEnclosingMethod.CONTENT_LENGTH_CHUNKED);} try { int statusCode = httpClient.executeMethod(method); System.out.println("返回码: " + statusCode); if(statusCode != HttpStatus.SC_OK) { return; } System.out.println("输出:"); System.out.println(method.getResponseBodyAsString());} catch (IOException e) { e.printStackTrace();} finally { method.releaseConnection();} 说明: 文件xml文件必须是utf-8形式,否则会有编码问题