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

时间:2010-04-01 11:18:25

标签: xml android http soap post

我想通过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>

9 个答案:

答案 0 :(得分:47)

  1. 首先,您可以为此SOAP请求创建一个String模板,并在此模板中在运行时替换用户提供的值以创建有效请求。
  2. 将此字符串包装在StringEntity中,并将其内容类型设置为text / xml
  3. 在SOAP请求中设置此实体。
  4. 类似的东西:

    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());
    

答案 1 :(得分:7)

这里是发送肥皂信息的替代方案。

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()方法,那就谷歌吧:)。

答案 2 :(得分:5)

所以如果你使用:

httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

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

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

是肥皂???

答案 3 :(得分:2)

这是我发送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();
        }

答案 4 :(得分:2)

通过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 :(得分:1)

我也必须通过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);

希望它有效!

答案 6 :(得分:1)

这里是代码的代码片段,用于在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请求。

玩得开心;

答案 7 :(得分:0)

另一种方法是使用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();

答案 8 :(得分:0)

使用OkHTTP很容易

String soap_string = "soap string";

public static final MediaType SOAP_MEDIA_TYPE = MediaType.parse("application/xml");
final OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create(SOAP_MEDIA_TYPE, soap_string);

final Request request = new Request.Builder()
       .url("Your URL")
       .post(body)
       .addHeader("Content-Type", "application/xml")
       .addHeader("Authorization", "Your Token")
       .addHeader("cache-control", "no-cache")
       .build();

client.newCall(request).enqueue(new Callback() {
    @Override
    public void onFailure(Call call, IOException e) {
          String mMessage = e.getMessage().toString();
          Log.w("failure Response", mMessage);
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {

         String mMessage = response.body().string();

          //code = response.code();
          getResponse(mMessage, response);
    }
});

在此处阅读完整的教程-https://www.studytutorial.in/android-sending-xml-or-soap-rest-api-request-using-okhttp-tutorial