簡體   English   中英

從android調用asmx Web服務

[英]call asmx web service from android

我有這個C#工作示例

void Main()
{
      string r = String.Format("<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\"><s:Body><TrackMobileApp xmlns=\" url \" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\"><device>test device</device><imei>000000</imei><ipAddress>192.168.1.1</ipAddress><timeStamp>{0}</timeStamp></TrackMobileApp></s:Body></s:Envelope>", DateTime.Now.ToString("o"));

      HttpWebRequest wr = (HttpWebRequest)HttpWebRequest.Create("asmx url");
      wr.ProtocolVersion = HttpVersion.Version11;
      wr.Headers.Add("SOAPAction", "\"soap action url\"");
      wr.Method = "POST";
      wr.ContentType = "text/xml;charset=utf-8";
      using (StreamWriter sw = new StreamWriter(wr.GetRequestStream()))
      {
            sw.Write(r);
      }

      HttpWebResponse rs = (HttpWebResponse)wr.GetResponse();
      if (rs.StatusCode == HttpStatusCode.OK)
      {
            XmlDocument xd = new XmlDocument();
            using (StreamReader sr = new StreamReader(rs.GetResponseStream()))
            {
                  xd.LoadXml(sr.ReadToEnd());
                  xd.InnerXml.Dump();
            }
      }
}

我已經在android中嘗試過了:

private class DownloadTask extends AsyncTask<String, Void, String> {
 private String downloadContent(String myurl) throws IOException {
        InputStream is = null;
        int length = 500;

        try {
            URL url = new URL(myurl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(10000 /* milliseconds */);
            conn.setConnectTimeout(15000 /* milliseconds */);
            conn.setRequestProperty("SOAPAction", "soap action url");
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "text/xml;");
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.connect();
            int response = conn.getResponseCode();
            Log.d(TAG, "The response is: " + response);
            is = conn.getInputStream();

            // Convert the InputStream into a string
            String contentAsString = convertInputStreamToString(is, length);
            return contentAsString;
        } finally {
            if (is != null) {
                is.close();
            }
        }
    }
...
}

我用它來稱呼它

新的DownloadTask()。execute(“ asmx url”);

如何將正文附加到該HttpURLConnection

還是有其他事情要告訴我。我是Java的初學者

嘗試這個

if(body != null) {
                DataOutputStream writer = new DataOutputStream(conn.getOutputStream());
                byte[] data = body.toString().getBytes("UTF-8");
                writer.write(data);

                writer.flush();
                writer.close();
            }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM