android端向web发送xml数据:
public void sendXml() throws Exception{
String urlStr = "http://192.168.0.2:8080/web/info!receiveXmlAction.action";
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
InputStream is = context.getAssets().open("struts.xml");
// BufferedReader br = new BufferedReader(new InputStreamReader(is));
// StringBuffer sb = new StringBuffer();
// do{
// sb.append(br.readLine());
// }while(br.readLine() != null);
conn.setRequestMethod("POST");
conn.setConnectTimeout(5*1000);
conn.setDoOutput(true);
conn.setRequestProperty("Content-type", "text/xml charset=UTF-8");
// conn.setRequestProperty("Content-Length", String.valueOf(sb.toString().getBytes().length));
OutputStream os = conn.getOutputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len=0;
while((len=is.read(buffer))!=-1){
baos.write(buffer,0,len);
Log.i("UPLOAD", new String(buffer));
}
byte[] data = baos.toByteArray();
os.write(data);
is.close();
os.flush();
os.close();
Log.i("UPLOAD", String.valueOf(conn.getResponseCode()));
}
以上代码能够成功发送并在服务器接收,但是代码从OutputStream 开始改为下面的就不行了
OutputStream os = conn.getOutputStream();
byte[] buffer = new byte[1024];
int len=0;
while((len=is.read(buffer))!=-1){
os.write(buffer,0,len);
Log.i("UPLOAD", new String(buffer));
}
根本还调用不到服务器端的receiveXmlAction方法.不知道是为什么?
也就是说,我直接通过输出流输出是不行的,必须先把数据输出到ByteArrayOutputStream ,再转为二进制数据,再用
OutputStream 输出才可以
有没有类似情况的朋友??指教一下