Android,通过 HTTP POST (SOAP) 发送 XML

Posted

技术标签:

【中文标题】Android,通过 HTTP POST (SOAP) 发送 XML【英文标题】:Android, sending XML via HTTP POST (SOAP) 【发布时间】:2011-02-03 08:02:23 【问题描述】:

我想通过 android 调用网络服务。我需要通过 HTTP 将一些 XML 发布到 URL。 我发现这是为了发送 POST 而剪掉的,但我不知道如何包含/添加 XML 数据本身。

public void postData() 
         // Create a new HttpClient and Post Header  
         HttpClient httpclient = new DefaultHttpClient();  
         HttpPost httppost = new HttpPost("http://10.10.4.35:53011/");

         try   
             // Add your data  
             List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);  
             nameValuePairs.add(new BasicNameValuePair("Content-Type", "application/soap+xml"));               
             httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
                 // Where/how to add the XML data?


             // Execute HTTP Post Request  
             HttpResponse response = httpclient.execute(httppost);  

          catch (ClientProtocolException e)   
             // TODO Auto-generated catch block  
          catch (IOException e)   
             // TODO Auto-generated catch block  
           
     

这是我需要模仿的完整 POST 消息:

POST /a8103e90-f1e3-11dd-bfdb-8b1fcff1a110 HTTP/1.1
Host: 10.10.4.35:53011
Content-Type: application/soap+xml
Content-Length: 602

<?xml version='1.0' encoding='UTF-8' ?>
<s12:Envelope xmlns:s12="http://www.w3.org/2003/05/soap-envelope" xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing">
  <s12:Header>
    <wsa:MessageID>urn:uuid:fc061d40-3d63-11df-bfba-62764ccc0e48</wsa:MessageID>
    <wsa:Action>http://schemas.xmlsoap.org/ws/2004/09/transfer/Get</wsa:Action>
    <wsa:To>urn:uuid:a8103e90-f1e3-11dd-bfdb-8b1fcff1a110</wsa:To>
    <wsa:ReplyTo>
      <wsa:Address>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</wsa:Address>
    </wsa:ReplyTo>
  </s12:Header>
  <s12:Body />
</s12:Envelope>

【问题讨论】:

嗨。你是怎么做到的?我应该放 SOAPRequestXML = "POST /a8103e.... " 还是 ""? @Intosia 是新手,也面临同样的问题。您能否详细解释一下以下解决方案,以便我理解。谢谢 【参考方案1】:
    首先,您可以为此 SOAP 请求创建一个字符串模板,并在此模板中替换用户在运行时提供的值以创建一个有效的请求。 将此字符串包装在 StringEntity 中并将其内容类型设置为 text/xml 在 SOAP 请求中设置此实体。

类似:

HttpPost httppost = new HttpPost(SERVICE_EPR);          
StringEntity se = new StringEntity(SOAPRequestXML,HTTP.UTF_8);

se.setContentType("text/xml");  
httppost.setHeader("Content-Type","application/soap+xml;charset=UTF-8");
httppost.setEntity(se);  

HttpClient httpclient = new DefaultHttpClient();
BasicHttpResponse httpResponse = 
    (BasicHttpResponse) httpclient.execute(httppost);

response.put("HTTPStatus",httpResponse.getStatusLine().toString());

【讨论】:

你也应该考虑阅读这个:***.com/questions/297586/… 感谢工作,更干净,虽然我不得不添加一个 'HttpClient httpclient = new DefaultHttpClient();' 当然,我只是粘贴了与我提出的观点相关的部分……很高兴知道它有帮助。干杯! 嗨。我应该放 SOAPRequestXML = "POST /a8103e.... " 还是 ""? @Samuh 你能否澄清一下最后一行代码response.put(...); 的作用以及对象response 的类型是什么?【参考方案2】:

这里是发送soap msg的替代方法。

public String setSoapMsg(String targetURL, String urlParameters)

        URL url;
        HttpURLConnection connection = null;  
        try 
          //Create connection
          url = new URL(targetURL);

         // for not trusted site (https)
         // _FakeX509TrustManager.allowAllSSL();
         // System.setProperty("javax.net.debug","all");

          connection = (HttpURLConnection)url.openConnection();
          connection.setRequestMethod("POST");


          connection.setRequestProperty("SOAPAction", "**** SOAP ACTION VALUE HERE ****");

          connection.setUseCaches (false);
          connection.setDoInput(true);
          connection.setDoOutput(true);


          //Send request
          DataOutputStream wr = new DataOutputStream (
                       connection.getOutputStream ());
          wr.writeBytes (urlParameters);
          wr.flush ();
          wr.close ();

          //Get Response    
          InputStream is ;
          Log.i("response", "code="+connection.getResponseCode());
          if(connection.getResponseCode()<=400)
              is=connection.getInputStream();
          else
              /* error from server */
              is = connection.getErrorStream();
         
         // is= connection.getInputStream();
          BufferedReader rd = new BufferedReader(new InputStreamReader(is));
          String line;
          StringBuffer response = new StringBuffer(); 
          while((line = rd.readLine()) != null) 
            response.append(line);
            response.append('\r');
          
          rd.close();
          Log.i("response", ""+response.toString());
          return response.toString();

         catch (Exception e) 

         Log.e("error https", "", e);
          return null;

         finally 

          if(connection != null) 
            connection.disconnect(); 
          
        
      

希望对您有所帮助。如果有人想知道allowAllSSL() 的方法,谷歌它:)。

【讨论】:

你的方法对我有用,虽然我必须添加 'connection.setRequestProperty("Content-Type", "text/xml");'因为url参数是soap请求中的xml【参考方案3】:

所以如果你使用:

httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

它仍然是休息,但如果你使用:

StringEntity se = new StringEntity(SOAPRequestXML,HTTP.UTF_8);
httppost.setEntity(se);  

这是肥皂???

【讨论】:

【参考方案4】:

通过 http POST 将 XML 发送到 WS 的示例。

DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://foo/service1.asmx/GetUID");     

        //XML example to send via Web Service.
        StringBuilder sb = new StringBuilder();
        sb.append("<myXML><Parametro><name>IdApp</name><value>1234567890</value></Parameter>");
        sb.append("<Parameter><name>UID1</name><value>abc12421</value></Parameter>");
                sb.append("</myXML>");

        httppost.addHeader("Accept", "text/xml");
        httppost.addHeader("Content-Type", "application/x-www-form-urlencoded");

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); 
        nameValuePairs.add(new BasicNameValuePair("myxml", sb.toString());//WS Parameter and    Value           
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = httpclient.execute(httppost);

【讨论】:

【参考方案5】:

这是我发送 html 的代码.... 可以看到数据是nameValuePairs.add(...)

        HttpClient httpclient = new DefaultHttpClient();
        // Your URL
        HttpPost httppost = new HttpPost("http://192.71.100.21:8000");

        try 
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            // Your DATA
            nameValuePairs.add(new BasicNameValuePair("id", "12345"));
            nameValuePairs.add(new BasicNameValuePair("stringdata","AndDev is Cool!"));

            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            HttpResponse response;
            response = httpclient.execute(httppost);
         catch (ClientProtocolException e) 
            // TODO Auto-generated catch block
            e.printStackTrace();
         catch (IOException e) 
            // TODO Auto-generated catch block
            e.printStackTrace();
        

【讨论】:

【参考方案6】:

我也必须在 Android 上通过 HTTP Post 发送一些 XML。

String xml = "xml-block";
StringEntity se = new StringEntity(xml,"UTF-8");
se.setContentType("application/atom+xml");
HttpPost postRequest = new HttpPost("http://some.url");
postRequest.setEntity(se);

希望它有效!

【讨论】:

【参考方案7】:

这里是代码的 sn-ps 代码,我用于在 SOAP 服务中发布 xml 并作为回报从 web 获取 Inputstream。

 private InputStream call(String soapAction, String xml) throws IOException 

    byte[] requestData = xml.getBytes("UTF-8");
    URL url = new URL(URL);

    connection = (HttpURLConnection) url.openConnection();
    connection.setRequestProperty("Accept-Charset", "UTF-8");
    // connection.setRequestProperty("Accept-Encoding","gzip,deflate");
    connection.setRequestProperty("Content-Type", "text/xml; UTF-8");
    connection.setRequestProperty("SOAPAction", soapAction);
    connection.setRequestProperty("User-Agent", "android");
    connection.setRequestProperty("Host",
            "base_urlforwebservices like - xyz.net");
    // connection
    // .setRequestProperty("Content-Length", "" + requestData.length);
    connection.setRequestMethod("POST");
    connection.setDoOutput(true);
    connection.setDoInput(true);

    os = connection.getOutputStream();
    os.write(requestData, 0, requestData.length);
    os.flush();
    os.close();
    is = connection.getInputStream();
    return is; // inputStream

这里的xml:就是构建的xml请求,用来调用服务。

玩得开心;

【讨论】:

抱歉,我找不到 URL 类。它在哪里?它是标准 Android Java 类的一部分吗? 它的 here 是的,它在 android 中,因为 api 级别 1。 你的问题解决了吗?? 嗯,一年,我采取了另一种方法,但关于找不到这门课,我只是瞎了眼!谢谢! :-)【参考方案8】:

另一种方法是使用Apache Call。需要提供Api URL、Action URI和API Body

InputStream input = new ByteArrayInputStream(apiBody.getBytes());
Service service = new Service();
Call call = (Call) service.createCall();
SOAPEnvelope soapEnvelope = new SOAPEnvelope(input);

call.setTargetEndpointAddress(new URL(apiUrl));
call.setUseSOAPAction(true);
if(StringUtils.isNotEmpty(actionURI))
 call.setSOAPActionURI(actionURI);


soapEnvelope = call.invoke(soapEnvelope);
return soapEnvelope.toString();

【讨论】:

以上是关于Android,通过 HTTP POST (SOAP) 发送 XML的主要内容,如果未能解决你的问题,请参考以下文章

Android,通过 HTTP POST (SOAP) 发送 XML

Android下通过HttpClient执行 HTTP POST 请求 的代码

Android通过HTTP POST带參訪问asp.net网页

Android 中的安全 HTTP Post

Restful,SAOP,SOA,RPC的基础理解

android中Post方式发送HTTP请求