這裏面簡單介紹下,HttpURLConnection連接服務器,並返回數據
客戶端代碼java代碼:
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class PostXml {
public static void main(String args[]) {
try {
String xml = "<?xml version='1.0' encoding='UTF-8'?><group><name>周成林</name><age>22</age><Image>我們</Image></group>";
// 創建url資源
URL url = new URL("http://119.29.85.118//finance.php");
// 建立http連接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 設置允許輸出
conn.setDoOutput(true);
conn.setDoInput(true);
// 設置不用緩存
conn.setUseCaches(false);
// 設置傳遞方式
conn.setRequestMethod("POST");
// 設置維持長連接
conn.setRequestProperty("Connection", "Keep-Alive");
// 設置文件字符集:
conn.setRequestProperty("Charset", "UTF-8");
//轉換爲字節數組
byte[] data = xml.getBytes();
// 設置文件長度
conn.setRequestProperty("Content-Length", String.valueOf(data.length));
// 設置文件類型:
conn.setRequestProperty("contentType", "text/xml");
// 開始連接請求
conn.connect();
OutputStream out = conn.getOutputStream();
// 寫入請求的字符串
out.write(data);
out.flush();
out.close();
System.out.println(conn.getResponseCode());
// 請求返回的狀態
if (conn.getResponseCode() == 200) {
System.out.println("連接成功");
// 請求返回的數據
InputStream in = conn.getInputStream();
String a = null;
try {
byte[] data1 = new byte[in.available()];
in.read(data1);
// 轉成字符串
a = new String(data1);
System.out.println(a);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} else {
System.out.println("no++");
}
} catch (Exception e) {
}
}
}
服務端php代碼:
<?php
@header("Content-type: text/html; charset=utf-8");
$file_in = file_get_contents("php://input");
$request=simplexml_load_string($file_in);
foreach($request->children() as $childItem) {
//輸出xml節點名稱和值
echo $childItem->getName() . "->".$childItem."<br />";
//其他操作省略
}
?>
返回結果:
name->周成林
age->22
Image->我們