Java HTTP POST XML和接收
一般POST或GET中的数据的都是key=value键值对形式。其实POST可以更强大,我们可以直接POST一段XML。
发送的客户端代码:
//xml参数为需要发送的xml格式的字符串
public static String connectServer(String xml) {
String returnMsg = “”;
String urlStr=”http://localhost/external.action”;
try {
URL url = new URL(urlStr);
URLConnection con = url.openConnection();
con.setDoOutput(true);
con.setRequestProperty(“Pragma:”, “no-cache”);
con.setRequestProperty(“Cache-Control”, “no-cache”);
con.setRequestProperty(“Content-Type”, “text/xml”);
OutputStreamWriter out = new OutputStreamWriter(con
.getOutputStream(),”utf-8″);
out.write(new String(xml.getBytes()));
out.flush();
out.close();
BufferedReader br = new BufferedReader(new InputStreamReader(con
.getInputStream(),”utf-8″));
String line = “”;
for (line = br.readLine(); line != null; line = br.readLine()) {
System.out.println(line);
returnMsg =returnMsg + line;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return returnMsg;
}
服务器端的代码:
//获取HTTP请求的输入流
InputStream is;
is = request.getInputStream();
//已HTTP请求输入流建立一个BufferedReader对象
BufferedReader br = new BufferedReader(new InputStreamReader(is,”UTF-8″));
//读取HTTP请求内容
String buffer = null;
while ((buffer = br.readLine()) != null) {
//在页面中显示读取到的请求参数
sb.append(buffer);
}
//Sb就是接收到的xml字符串。
欢迎转载,请注明出处:亲亲宝宝