JAVA如何用POST傳遞XML及接收?
最近在和其它系統介接時,對方提出用HTTP協定POST的方式傳遞XML
以往,在傳遞時都是採用parameter的方式傳遞資料,但這次是要直接使用request content body
呵~會JAVA這麼多年了,第一次採用,原本還想說可行嗎?去查了一下真的可以,所以特別寫下來
以下的程式碼都是採用Apache HttpClient 的方式進行
呼叫端
1. 採用Stream的方式,進行傳遞
File input = new File(strXMLFilename);
PostMethod post = new PostMethod(“http://server/api”);
post.setRequestEntity(new InputStreamRequestEntity(new FileInputStream(input), input.length()));
post.setRequestHeader(“Content-type”, “text/xml; charset=UTF-8”);
File input = new File(strXMLFilename);
PostMethod post = new PostMethod(“http://server/api”);
post.setRequestEntity(new InputStreamRequestEntity(new FileInputStream(input), input.length()));
post.setRequestHeader(“Content-type”, “text/xml; charset=UTF-8”);
2.也可以直接用String的方式進行傳遞data 字串
HttpClient httpclient = new HttpClient();
PostMethod post = new PostMethod(“http://server/api”);
RequestEntity entity = new StringRequestEntity(data, “text/xml”, “UTF-8”);
post.setRequestEntity(entity);
httpclient.executeMethod(post);
PostMethod post = new PostMethod(“http://server/api”);
RequestEntity entity = new StringRequestEntity(data, “text/xml”, “UTF-8”);
post.setRequestEntity(entity);
httpclient.executeMethod(post);
至於Server接收端要如何接收呢? 此時就不能採用先前在用的request.getParameter了,我們要改用串流方式
StringBuilder stringBuilder = new StringBuilder();
BufferedReader bufferedReader = null;
try {
InputStream inputStream = request.getInputStream();
if (inputStream != null) {
bufferedReader = new BufferedReader(new InputStreamReader(
inputStream));
char[] charBuffer = new char[128];
int bytesRead = -1;
while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
stringBuilder.append(charBuffer, 0, bytesRead);
}
} else {
stringBuilder.append(“”);
}
} catch (IOException ex) {
throw ex;
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException ex) {
throw ex;
}
}
}
String body = stringBuilder.toString();
BufferedReader bufferedReader = null;
try {
InputStream inputStream = request.getInputStream();
if (inputStream != null) {
bufferedReader = new BufferedReader(new InputStreamReader(
inputStream));
char[] charBuffer = new char[128];
int bytesRead = -1;
while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
stringBuilder.append(charBuffer, 0, bytesRead);
}
} else {
stringBuilder.append(“”);
}
} catch (IOException ex) {
throw ex;
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException ex) {
throw ex;
}
}
}
String body = stringBuilder.toString();
這個body 變數就是我們要的xml文件啦!!
資料來源:
近期留言