Error writing to server
用HTTP发送接收XML
客户端
public class XmlTest {
String url;
public XmlTest(String url){
this.url = url;
}
public static void main(String[] args) {
String url = "http://127.0.0.1:8080/ecg/user/report/receive";
String returnStr = "";
HttpURLConnection httpConn = null;
InputStream fis = null;
try {
URL httpurl = new URL(url);
String xmlInfo = getXmlInfo();
httpConn = (HttpURLConnection) httpurl.openConnection();
httpConn.setDoOutput(true);
httpConn.setRequestProperty("User-agent", "MSIE8.0"); //设置代理为IE8
httpConn.setRequestMethod("POST");
httpConn.setConnectTimeout(600000);
httpConn.setReadTimeout(600000);
OutputStream op = httpConn.getOutputStream();
op.write(xmlInfo.getBytes());
op.flush();
op.close();
if(httpConn.getResponseCode() == 200){
fis = httpConn.getInputStream();
returnStr = Stream2String(fis,"utf-8");
}
System.out.println(returnStr);
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
try {
if(fis!=null){
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
httpConn.disconnect();
}
}
private static String Stream2String(InputStream in, String encoding) {
if (in == null) {
return null;
}
StringBuffer out = new StringBuffer();
try {
char[] b = new char[1024];
InputStreamReader inread = new InputStreamReader(in, encoding);
for (int n; (n = inread.read(b)) != -1;) {
String line = new String(b, 0, n);
out.append(line);
}
} catch (Exception e) {
e.printStackTrace();
}
return out.toString();
}
private static String getXmlInfo() {
SAXBuilder builder = new SAXBuilder();
Document document;
try {
document = builder.build(new FileInputStream(new File("C:/Users/panjing/Documents/Tencent Files/807053633/FileRecv/1514438446000.xml")));
Format format = Format.getCompactFormat();
format.setEncoding("UTF-8");// 设置xml文件的字符为UTF-8,解决中文问题
XMLOutputter xmlout = new XMLOutputter();
ByteArrayOutputStream bo = new ByteArrayOutputStream();
xmlout.output(document, bo);
return bo.toString().trim();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (JDOMException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
服务端
@Controller
@RequestMapping("/ecg/user/report")
public class EcgUserReportController extends BaseController {
@RequestMapping("receive")
public Document receiveXml(HttpServletRequest request,HttpServletResponse response) {
SAXReader saxReader = null;
Document doc = null;
try{
saxReader = new SAXReader();
doc = saxReader.read(request.getInputStream());
String xmlStr = doc.asXML();
System.out.println("xmlInfo=" + xmlStr);
ecgUserReportService.saveXmlResult(xmlStr,4127);
} catch (Exception e){
e.printStackTrace();
}
return doc ;
}
}