使用HttpURLConnection发送XML请求数据

 //从XML文件时取出要请求的数据
        InputStream input = MainActivity.class.getResourceAsStream("documentTest4.xml");
        byte[] data;
		try {
			data = new byte[input.available()];
	        input.read(data);
	        //把XML的数据转成字符串
	        String str=new String(data);
	        System.out.println(str);
	        byte[] bb=str.getBytes();
	        //请求地址
			URL url = new URL("http://192.168.1.102:8080/WuYouLife/WuYouLifeAPI?wsdl");
			HttpURLConnection conn = (HttpURLConnection)url.openConnection();
			conn.setRequestMethod("POST");
			conn.setConnectTimeout(5 * 1000);//设置超时的时间
			conn.setDoInput(true);
			conn.setDoOutput(true);//如果通过post提交数据,必须设置允许对外输出数据
			conn.setRequestProperty("Content-Type", "text/xml; charset=UTF-8");
			conn.setRequestProperty("Content-Length", String.valueOf(bb.length));
			conn.connect();
			 DataOutputStream out = new DataOutputStream(conn
		                .getOutputStream());
		        out.writeBytes(str); //写入请求的字符串
		        out.flush();
		        out.close();
		//请求返回的状态 
		if(conn.getResponseCode() ==200) {
			System.out.println("yes++");
			//请求返回的数据
			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 (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

你可能感兴趣的:(xml,exception,String,url,input,byte)