Android, envoi de XML via HTTP POST (SOAP)

Je voudrais invoquer un webservice via Android. Je dois POST du XML à une URL via HTTP. J’ai trouvé cela snipped pour l’envoi d’un POST, mais je ne sais pas comment inclure / append les données XML lui-même.

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 nameValuePairs = new ArrayList(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 } } 

Ceci est le message POST complet que je dois imiter:

 POST /a8103e90-f1e3-11dd-bfdb-8b1fcff1a110 HTTP/1.1 Host: 10.10.4.35:53011 Content-Type: application/soap+xml Content-Length: 602    urn:uuid:fc061d40-3d63-11df-bfba-62764ccc0e48 http://schemas.xmlsoap.org/ws/2004/09/transfer/Get urn:uuid:a8103e90-f1e3-11dd-bfdb-8b1fcff1a110  http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous     

  1. Tout d’abord, vous pouvez créer un modèle Ssortingng pour cette requête SOAP et substituer les valeurs fournies par l’utilisateur à l’exécution dans ce modèle pour créer une requête valide.
  2. Enveloppez cette chaîne dans une SsortingngEntity et définissez son type de contenu en tant que text / xml
  3. Définissez cette entité dans la requête SOAP.

Quelque chose comme:

 HttpPost httppost = new HttpPost(SERVICE_EPR); SsortingngEntity se = new SsortingngEntity(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().toSsortingng()); 

ici l’alternative pour envoyer des messages de soap.

 public Ssortingng setSoapMsg(Ssortingng targetURL, Ssortingng 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(); } } } 

J'espère que cela aide. si quelqu'un se demande la méthode allowAllSSL() , google it :).

Donc, si vous utilisez:

 httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

C’est toujours le repos, mais si vous utilisez:

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

C’est du soap ???

Exemple d’envoi de XML à WS via http POST.

 DefaultHttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://foo/service1.asmx/GetUID"); //XML example to send via Web Service. SsortingngBuilder sb = new SsortingngBuilder(); sb.append("IdApp1234567890"); sb.append("UID1abc12421"); sb.append(""); httppost.addHeader("Accept", "text/xml"); httppost.addHeader("Content-Type", "application/x-www-form-urlencoded"); List nameValuePairs = new ArrayList(1); nameValuePairs.add(new BasicNameValuePair("myxml", sb.toSsortingng());//WS Parameter and Value httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); 

Voici mon code pour envoyer du HTML …. Vous pouvez voir que les données sont le nomValuePairs.add (…)

  HttpClient httpclient = new DefaultHttpClient(); // Your URL HttpPost httppost = new HttpPost("http://192.71.100.21:8000"); try { List nameValuePairs = new ArrayList(2); // Your DATA nameValuePairs.add(new BasicNameValuePair("id", "12345")); nameValuePairs.add(new BasicNameValuePair("ssortingngdata","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(); } 

J’ai également dû envoyer du XML via HTTP Post sur Android.

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

Esperons que ça marche!

ici, les extraits de code du code que j’utilise pour poster du code XML dans les services SOAP et obtenir en retour le stream d’entrée du Web.

  private InputStream call(Ssortingng soapAction, Ssortingng 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 } 

Ici, xml: est la requête XML utilisée pour appeler les services.

S’amuser;

Une autre façon de procéder consiste à utiliser Apache Call . Api URL, Action URI et API Body doivent être fournis

 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(SsortingngUtils.isNotEmpty(actionURI)){ call.setSOAPActionURI(actionURI); } soapEnvelope = call.invoke(soapEnvelope); return soapEnvelope.toSsortingng(); 

OkHTTP est simple à utiliser

 Ssortingng soap_ssortingng = "soap ssortingng"; public static final MediaType SOAP_MEDIA_TYPE = MediaType.parse("application/xml"); final OkHttpClient client = new OkHttpClient(); RequestBody body = RequestBody.create(SOAP_MEDIA_TYPE, soap_ssortingng); 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) { Ssortingng mMessage = e.getMessage().toSsortingng(); Log.w("failure Response", mMessage); } @Override public void onResponse(Call call, Response response) throws IOException { Ssortingng mMessage = response.body().ssortingng(); //code = response.code(); getResponse(mMessage, response); } }); 

Lire le tutoriel complet ici – https://www.studytutorial.in/android-sending-xml-or-soap-rest-api-request-using-okhttp-tutorial