Подтвердить что ты не робот

Android, отправляющий XML через HTTP POST (SOAP)

Я хотел бы вызвать веб-сервис через Android. Мне нужно, чтобы POST некоторые XML URL через HTTP. Я обнаружил, что это отключено для отправки 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>
4b9b3361

Ответ 1

  • Во-первых, вы можете создать шаблон String для этого 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());

Ответ 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(), google it:).

Ответ 3

Итак, если вы используете:

httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

Он по-прежнему остается, но если вы используете:

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

Это мыло.

Ответ 4

Вот мой код для отправки 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();
        }

Ответ 5

Мне пришлось отправить XML-сообщение через HTTP-сообщение на Android.

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

здесь, фрагменты кода кода, которые я использую для размещения xml в SOAP-сервисах и взамен получения входного потока из Интернета.

 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

Пример отправки XML в WS через http POST.

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

Ответ 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();