使用android發送XML數據
服務器端:
1.用一個servlet來接收android客戶端的請求。
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.kafei.utils.StreamTool;
@WebServlet("/XmlServlet")
public class XmlServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
//通過request的getInputStream方法可以獲得android客戶端發送的XML數據流
byte[] data = StreamTool.read(request.getInputStream());
String xml = new String(data, "UTF-8");
System.out.println(xml);
}
}
2.讀取流中的數據:
/**
* 讀取流中的數據
*/
public static byte[] read(InputStream inputStream) throws IOException {
ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
byte[] b=new byte[1024];
int len=0;
while((len=inputStream.read(b))!=-1){
outputStream.write(b,0,len);
}
inputStream.close();
return outputStream.toByteArray();
}
android客戶端:
1.首先準備一個提供測試的XML文件(city.xml),放在src目錄下:
<?xml version="1.0" encoding="UTF-8"?>
<citys>
<china id="0">
<city>蘭州</city>
<province>甘肅</province>
</china>
<china id="1">
<city>慶陽</city>
<province>甘肅</province>
</china>
</citys>
2.編寫發送的業務邏輯:
public void testSendXML() throws Exception {
// 向服務器發送實體數據
InputStream inStream = this.getClass().getClassLoader()
.getResourceAsStream("city.xml");//加載本地XML文件
byte[] data = StreamTool.read(inStream);//獲得文件的字節數組
String path = "http://192.168.1.100:8080/web/XmlServlet";//發送路徑
HttpURLConnection conn = (HttpURLConnection) new URL(path)
.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("POST");//以PSOT方式進行提交
conn.setDoOutput(true);//允許輸出數據
conn.setRequestProperty("Content-Type", "text/xml; charset=UTF-8");//設置發送的文件類型
conn.setRequestProperty("Content-Length", String.valueOf(data.length));//設置發送文件的長度
conn.getOutputStream().write(data);//些人輸出流中
//判斷是否發送成功,只有調用了getResponseCode方法才真正的實現發送的動作
if (conn.getResponseCode() == 200) {
System.out.println("發送成功");
} else {
System.out.println("發送失敗");
}
}
至此android客戶端向服務器發送XML數據就已完成。歡迎大家進行交流