如何使用url实现数据交互

  DataInputStream input = null;
  java.io.ByteArrayOutputStream out = null;
  try {
   byte[] xmlData = xmlString.toString().getBytes("GB2312");
   // 获得到位置服务的链接
   URL url = new URL(this.serviceUrl);
   URLConnection urlCon = url.openConnection();
   urlCon.setDoOutput(true);
   urlCon.setDoInput(true);
   urlCon.setUseCaches(false);
   // 将xml数据发送到位置服务
   urlCon.setRequestProperty("Content-Type", "text/xml");
   urlCon.setRequestProperty("Content-length", String
     .valueOf(xmlData.length));
   DataOutputStream printout = new DataOutputStream(urlCon
     .getOutputStream());
   printout.write(xmlData);
   printout.flush();
   printout.close();
   System.out.println("开始接收返回的数据。。。。。。。。");
   input = new DataInputStream(urlCon.getInputStream());
   byte[] rResult;
   out = new java.io.ByteArrayOutputStream();
   byte[] bufferByte = new byte[256];
   int l = -1;
   int downloadSize = 0;
   while ((l = input.read(bufferByte)) > -1) {
    downloadSize += l;
    out.write(bufferByte, 0, l);
    out.flush();
   }
   System.out.println("downloadSize:"+downloadSize);
   rResult = out.toByteArray();
   Document doc = new SAXReader().read(new InputStreamReader(new ByteArrayInputStream(rResult),"GBK"));
   TaskAddr = doc.getRootElement().element("HEAD").element("RESPONSE_CODE").getText();
   ErrorMessage = doc.getRootElement().element("HEAD").element("ERROR_MESSAGE").getText();
   System.out.println("ErrorMessage:\t"+ErrorMessage);
  
  }catch (Exception e) {
   e.printStackTrace();
  }finally {
   try {
    out.close();
    input.close();
   }
   catch (Exception ex) {
   }
  }

原文地址:https://www.cnblogs.com/xiyuanbaiyun/p/2215402.html