问题描述
我的字符串表示XML:
String soapCall="<soap:Envelope xmlns:soap="http://www.w3.org/2001/12/soap-envelope" soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding"> <soap:Body xmlns:m="http://www.example.org/stock"> <m:addDownloadParams> <m:idApp>"; soapCall+=idApp; soapCall+="<m:versionApp>"; soapCall+=versonApp; soapCall+="</m:versionApp> <m:os>Android</m:os> </m:addDownloadParams> </soap:Body> </soap:Envelope>";
我有这个SOAP Web服务:
http://stats.mywebsite.com/ws/adddownload
现在,我需要将该字符串传递到Android上的SOAP WebService,但我不知道方法,我知道我需要使用httpcliente:
HttpClient httpClient = new DefaultHttpClient(); HttpContext localContext = new BasicHttpContext();
但我不知道如何用该字符串调用肥皂水.
有人有代码示例吗?我在Google上找不到它.我不想使用库,我需要自己做
谢谢
编辑:这是现在的代码,但是它不起作用,我收到错误500内部服务器错误:
public static byte[] addDownloadIntoServer(){ byte[] result = null; String SERVER_URL="http://stats.mywebsite.com/ws/server.php"; String SOAP_ACTION="addDownload"; String body="<?xml version=\"1.0\" encoding=\"UTF-8\"?><SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ns1=\"http://stats.mobincube.com/\"><SOAP-ENV:Body><ns1:addDownloadParams>"; body+="<idApp>" +SectionManager.instance.app_id+"</idApp>"; body+="<versionApp>"+SectionManager.instance.app_version+"</versionApp>"; body+="<source>android</source> <os>Android</os> </ns1:addDownloadParams></SOAP-ENV:Body></SOAP-ENV:Envelope>"; HttpParams httpParameters = new BasicHttpParams(); // Set the timeout in milliseconds until a connection is established. int timeoutConnection = 15000; HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); // Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data. int timeoutSocket = 35000; HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters); /* * httpclient.getCredentialsProvider().setCredentials( new * AuthScope("os.icloud.com", 80, null, "Digest"), new * UsernamePasswordCredentials(username, password)); */ HttpPost httppost = new HttpPost(SERVER_URL ); httppost.setHeader("soapaction", SOAP_ACTION); httppost.setHeader("Content-Type", "text/xml; charset=utf-8"); System.out.println("executing request" + httppost.getRequestLine()); //now create a soap request message as follows: final StringBuffer soap = new StringBuffer(); soap.append("\n"); soap.append(""); // this is a sample data..you have create your own required data BEGIN soap.append(" \n"); soap.append(" \n"); soap.append("" + body); soap.append(" \n"); soap.append(" \n"); /* soap.append(body); */ // END of MEssage Body soap.append(""); Log.i("SOAP Request", ""+soap.toString()); // END of full SOAP request message try { HttpEntity entity = new StringEntity(soap.toString(),HTTP.UTF_8); httppost.setEntity(entity); HttpResponse response = httpclient.execute(httppost);// calling server HttpEntity r_entity = response.getEntity(); //get response Log.i("Reponse Header", "Begin..."); // response headers Log.i("Reponse Header", "StatusLine:"+response.getStatusLine()); Header[] headers = response.getAllHeaders(); for(Header h:headers) Log.i("Reponse Header",h.getName() + ": " + h.getValue()); Log.i("Reponse Header", "END..."); if (r_entity != null) { result = new byte[(int) r_entity.getContentLength()]; if (r_entity.isStreaming()) { DataInputStream is = new DataInputStream( r_entity.getContent()); is.readFully(result); } } }catch (Exception E) { Log.i("Exception While Connecting", ""+E.getMessage()); E.printStackTrace(); } httpclient.getConnectionManager().shutdown(); //shut down the connection return result; }
推荐答案
解决方案:
private byte[] callSOAPServer() { byte[] result = null; HttpParams httpParameters = new BasicHttpParams(); // Set the timeout in milliseconds until a connection is established. int timeoutConnection = 15000; HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); // Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data. int timeoutSocket = 35000; HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters); /* * httpclient.getCredentialsProvider().setCredentials( new * AuthScope("os.icloud.com", 80, null, "Digest"), new * UsernamePasswordCredentials(username, password)); */ HttpPost httppost = new HttpPost(SERVER_URL ); httppost.setHeader("soapaction", SOAP_ACTION); httppost.setHeader("Content-Type", "text/xml; charset=utf-8"); System.out.println("executing request" + httppost.getRequestLine()); //now create a soap request message as follows: final StringBuffer soap = new StringBuffer(); soap.append("\n"); soap.append(""); // this is a sample data..you have create your own required data BEGIN soap.append(" \n"); soap.append(" \n"); soap.append("" + body); soap.append(" \n"); soap.append(" \n"); /* soap.append(body); */ // END of MEssage Body soap.append(""); Log.i("SOAP Request", ""+soap.toString()); // END of full SOAP request message try { HttpEntity entity = new StringEntity(soap.toString(),HTTP.UTF_8); httppost.setEntity(entity); HttpResponse response = httpclient.execute(httppost);// calling server HttpEntity r_entity = response.getEntity(); //get response Log.i("Reponse Header", "Begin..."); // response headers Log.i("Reponse Header", "StatusLine:"+response.getStatusLine()); Header[] headers = response.getAllHeaders(); for(Header h:headers){ Log.i("Reponse Header",h.getName() + ": " + h.getValue()); } Log.i("Reponse Header", "END..."); if (r_entity != null) { result = new byte[(int) r_entity.getContentLength()]; if (r_entity.isStreaming()) { DataInputStream is = new DataInputStream( r_entity.getContent()); is.readFully(result); } } } catch (Exception E) { Log.i("Exception While Connecting", ""+E.getMessage()); E.printStackTrace(); } httpclient.getConnectionManager().shutdown(); //shut down the connection return result; }
2)您必须解析上述函数返回ByTearray的输出.例如:
byte[] initReqrepsonse = callSOAPServer(soapBodymessage ); ByteArrayInputStream bais=new ByteArrayInputStream(initReqrepsonse); // now parse the xml as /** Handling XML */ SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); /** Create handler to handle XML Tags ( extends DefaultHandler ) */ // ResponseParser is XML parser class which will parse the XML output. ResponseParser myXMLHandler = new ResponseParser(); xr.setContentHandler(myXMLHandler); Log.i("XML data", bais.toString()); xr.parse(new InputSource(bais));
这样,您可以访问没有第三方库的任何SOAP Web服务方法. 请让我知道是否需要任何更正.
其他推荐答案
package ProductVerificationCard.in; import org.ksoap2.SoapEnvelope; import org.ksoap2.serialization.SoapObject; import org.ksoap2.serialization.SoapSerializationEnvelope; import org.ksoap2.transport.HttpTransportSE; import android.app.Activity; import android.content.Intent;`` import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; public class AdminLogin extends Activity { /** Called when the activity is first created. */ Button btn_ok; TextView textView; private static final String SOAP_ACTION = "http://tempuri.org/Login"; private static final String OPERATION_NAME = "Login"; private static final String WSDL_TARGET_NAMESPACE = "http://tempuri.org/"; private static final String SOAP_ADDRESS = "http://10.0.2.2/new/WebService.asmx"; String s; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); btn_ok=(Button) findViewById(R.id.btn_login); textView=(TextView) findViewById(R.id.tv_error); btn_ok.setOnClickListener(new OnClickListener() { public void onClick(View v) { SoapObject request = new SoapObject(WSDL_TARGET_NAMESPACE, OPERATION_NAME); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope( SoapEnvelope.VER11); envelope.dotNet = true; envelope.setOutputSoapObject(request); HttpTransportSE httpTransport = new HttpTransportSE(SOAP_ADDRESS); try { httpTransport.call(SOAP_ACTION, envelope); Object response = envelope.getResponse(); //textView.setText(response.toString()); s=response.toString(); if(s=="true") { Intent intent=new Intent(AdminLogin.this,MenuForm.class); startActivity(intent); } else { textView.setText("Enter Valid Username or Password"); } } catch (Exception exception) { textView.setText(exception.toString()); } // TODO Auto-generated method stub } }); } }
其他推荐答案
Formatted answer : import java.io.BufferedReader; import java.io.InputStreamReader; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.methods.PostMethod; /** * * This program demonstrates consuming web service using Apache HTTPClient and * SOAP message. * Reference: * http://www.webservicex.net/stockquote.asmx?op=GetQuote * ClassPath: Keep these * two files in class path: commons-httpclient-3.0.1.jar, commons-codec-1.4.jar * @author * Bhavani P Polimetla * @since April-27-2011 */ public class WSClient { public static void main(String args[]) { HttpClient httpClient = new HttpClient(); httpClient.getParams().setParameter("http.useragent", "Web Service Test Client"); BufferedReader br = null; String data = "<?xml version=\"1.0\" encoding=\"utf-8\"?> " + "<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\"> " + "<soap12:Body> " + "<GetQuote xmlns=\"http://www.webserviceX.NET/\"> " + "<symbol>INFY</symbol> " + "</GetQuote> " + "</soap12:Body> </soap12:Envelope>"; PostMethod methodPost = new PostMethod( "http://www.webservicex.net/stockquote.asmx?op=GetQuote"); methodPost.setRequestBody(data); methodPost.setRequestHeader("Content-Type", "text/xml"); try { int returnCode = httpClient.executeMethod(methodPost); if (returnCode == HttpStatus.SC_NOT_IMPLEMENTED) { System.out .println("The Post method is not implemented by this URI"); methodPost.getResponseBodyAsString(); } else { br = new BufferedReader(new InputStreamReader( methodPost.getResponseBodyAsStream())); String readLine; while (((readLine = br.readLine()) != null)) { System.out.println(readLine); } } } catch (Exception e) { e.printStackTrace(); } finally { methodPost.releaseConnection(); if (br != null) try { br.close(); } catch (Exception fe) { fe.printStackTrace(); } } } }
问题描述
I have this string representing a XML:
String soapCall="<soap:Envelope xmlns:soap="http://www.w3.org/2001/12/soap-envelope" soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding"> <soap:Body xmlns:m="http://www.example.org/stock"> <m:addDownloadParams> <m:idApp>"; soapCall+=idApp; soapCall+="<m:versionApp>"; soapCall+=versonApp; soapCall+="</m:versionApp> <m:os>Android</m:os> </m:addDownloadParams> </soap:Body> </soap:Envelope>";
And i have this soap webservice:
http://stats.mywebsite.com/ws/adddownload
Now, i need to pass that string to that soap webservice on android, but i dont know the way, i know i need to use httpcliente:
HttpClient httpClient = new DefaultHttpClient(); HttpContext localContext = new BasicHttpContext();
but i dont know how to call the soapwebservice with that string.
Anyone haves a code example? i can't find it on google. I dont want to use a library, i need to do it by myself
Thanks
EDIT: this is the code now, but it is not working, i get error 500 internal server error:
public static byte[] addDownloadIntoServer(){ byte[] result = null; String SERVER_URL="http://stats.mywebsite.com/ws/server.php"; String SOAP_ACTION="addDownload"; String body="<?xml version=\"1.0\" encoding=\"UTF-8\"?><SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ns1=\"http://stats.mobincube.com/\"><SOAP-ENV:Body><ns1:addDownloadParams>"; body+="<idApp>" +SectionManager.instance.app_id+"</idApp>"; body+="<versionApp>"+SectionManager.instance.app_version+"</versionApp>"; body+="<source>android</source> <os>Android</os> </ns1:addDownloadParams></SOAP-ENV:Body></SOAP-ENV:Envelope>"; HttpParams httpParameters = new BasicHttpParams(); // Set the timeout in milliseconds until a connection is established. int timeoutConnection = 15000; HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); // Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data. int timeoutSocket = 35000; HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters); /* * httpclient.getCredentialsProvider().setCredentials( new * AuthScope("os.icloud.com", 80, null, "Digest"), new * UsernamePasswordCredentials(username, password)); */ HttpPost httppost = new HttpPost(SERVER_URL ); httppost.setHeader("soapaction", SOAP_ACTION); httppost.setHeader("Content-Type", "text/xml; charset=utf-8"); System.out.println("executing request" + httppost.getRequestLine()); //now create a soap request message as follows: final StringBuffer soap = new StringBuffer(); soap.append("\n"); soap.append(""); // this is a sample data..you have create your own required data BEGIN soap.append(" \n"); soap.append(" \n"); soap.append("" + body); soap.append(" \n"); soap.append(" \n"); /* soap.append(body); */ // END of MEssage Body soap.append(""); Log.i("SOAP Request", ""+soap.toString()); // END of full SOAP request message try { HttpEntity entity = new StringEntity(soap.toString(),HTTP.UTF_8); httppost.setEntity(entity); HttpResponse response = httpclient.execute(httppost);// calling server HttpEntity r_entity = response.getEntity(); //get response Log.i("Reponse Header", "Begin..."); // response headers Log.i("Reponse Header", "StatusLine:"+response.getStatusLine()); Header[] headers = response.getAllHeaders(); for(Header h:headers) Log.i("Reponse Header",h.getName() + ": " + h.getValue()); Log.i("Reponse Header", "END..."); if (r_entity != null) { result = new byte[(int) r_entity.getContentLength()]; if (r_entity.isStreaming()) { DataInputStream is = new DataInputStream( r_entity.getContent()); is.readFully(result); } } }catch (Exception E) { Log.i("Exception While Connecting", ""+E.getMessage()); E.printStackTrace(); } httpclient.getConnectionManager().shutdown(); //shut down the connection return result; }
推荐答案
Solution:
private byte[] callSOAPServer() { byte[] result = null; HttpParams httpParameters = new BasicHttpParams(); // Set the timeout in milliseconds until a connection is established. int timeoutConnection = 15000; HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); // Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data. int timeoutSocket = 35000; HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters); /* * httpclient.getCredentialsProvider().setCredentials( new * AuthScope("os.icloud.com", 80, null, "Digest"), new * UsernamePasswordCredentials(username, password)); */ HttpPost httppost = new HttpPost(SERVER_URL ); httppost.setHeader("soapaction", SOAP_ACTION); httppost.setHeader("Content-Type", "text/xml; charset=utf-8"); System.out.println("executing request" + httppost.getRequestLine()); //now create a soap request message as follows: final StringBuffer soap = new StringBuffer(); soap.append("\n"); soap.append(""); // this is a sample data..you have create your own required data BEGIN soap.append(" \n"); soap.append(" \n"); soap.append("" + body); soap.append(" \n"); soap.append(" \n"); /* soap.append(body); */ // END of MEssage Body soap.append(""); Log.i("SOAP Request", ""+soap.toString()); // END of full SOAP request message try { HttpEntity entity = new StringEntity(soap.toString(),HTTP.UTF_8); httppost.setEntity(entity); HttpResponse response = httpclient.execute(httppost);// calling server HttpEntity r_entity = response.getEntity(); //get response Log.i("Reponse Header", "Begin..."); // response headers Log.i("Reponse Header", "StatusLine:"+response.getStatusLine()); Header[] headers = response.getAllHeaders(); for(Header h:headers){ Log.i("Reponse Header",h.getName() + ": " + h.getValue()); } Log.i("Reponse Header", "END..."); if (r_entity != null) { result = new byte[(int) r_entity.getContentLength()]; if (r_entity.isStreaming()) { DataInputStream is = new DataInputStream( r_entity.getContent()); is.readFully(result); } } } catch (Exception E) { Log.i("Exception While Connecting", ""+E.getMessage()); E.printStackTrace(); } httpclient.getConnectionManager().shutdown(); //shut down the connection return result; }
2) You have to parse the output of above function returned byteArray. For example:
byte[] initReqrepsonse = callSOAPServer(soapBodymessage ); ByteArrayInputStream bais=new ByteArrayInputStream(initReqrepsonse); // now parse the xml as /** Handling XML */ SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); /** Create handler to handle XML Tags ( extends DefaultHandler ) */ // ResponseParser is XML parser class which will parse the XML output. ResponseParser myXMLHandler = new ResponseParser(); xr.setContentHandler(myXMLHandler); Log.i("XML data", bais.toString()); xr.parse(new InputSource(bais));
This way,you can access Any SOAP webservice methods without third-party libraries. Please let me know if any corrections are required.
其他推荐答案
package ProductVerificationCard.in; import org.ksoap2.SoapEnvelope; import org.ksoap2.serialization.SoapObject; import org.ksoap2.serialization.SoapSerializationEnvelope; import org.ksoap2.transport.HttpTransportSE; import android.app.Activity; import android.content.Intent;`` import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; public class AdminLogin extends Activity { /** Called when the activity is first created. */ Button btn_ok; TextView textView; private static final String SOAP_ACTION = "http://tempuri.org/Login"; private static final String OPERATION_NAME = "Login"; private static final String WSDL_TARGET_NAMESPACE = "http://tempuri.org/"; private static final String SOAP_ADDRESS = "http://10.0.2.2/new/WebService.asmx"; String s; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); btn_ok=(Button) findViewById(R.id.btn_login); textView=(TextView) findViewById(R.id.tv_error); btn_ok.setOnClickListener(new OnClickListener() { public void onClick(View v) { SoapObject request = new SoapObject(WSDL_TARGET_NAMESPACE, OPERATION_NAME); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope( SoapEnvelope.VER11); envelope.dotNet = true; envelope.setOutputSoapObject(request); HttpTransportSE httpTransport = new HttpTransportSE(SOAP_ADDRESS); try { httpTransport.call(SOAP_ACTION, envelope); Object response = envelope.getResponse(); //textView.setText(response.toString()); s=response.toString(); if(s=="true") { Intent intent=new Intent(AdminLogin.this,MenuForm.class); startActivity(intent); } else { textView.setText("Enter Valid Username or Password"); } } catch (Exception exception) { textView.setText(exception.toString()); } // TODO Auto-generated method stub } }); } }
其他推荐答案
Formatted answer : import java.io.BufferedReader; import java.io.InputStreamReader; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.methods.PostMethod; /** * * This program demonstrates consuming web service using Apache HTTPClient and * SOAP message. * Reference: * http://www.webservicex.net/stockquote.asmx?op=GetQuote * ClassPath: Keep these * two files in class path: commons-httpclient-3.0.1.jar, commons-codec-1.4.jar * @author * Bhavani P Polimetla * @since April-27-2011 */ public class WSClient { public static void main(String args[]) { HttpClient httpClient = new HttpClient(); httpClient.getParams().setParameter("http.useragent", "Web Service Test Client"); BufferedReader br = null; String data = "<?xml version=\"1.0\" encoding=\"utf-8\"?> " + "<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\"> " + "<soap12:Body> " + "<GetQuote xmlns=\"http://www.webserviceX.NET/\"> " + "<symbol>INFY</symbol> " + "</GetQuote> " + "</soap12:Body> </soap12:Envelope>"; PostMethod methodPost = new PostMethod( "http://www.webservicex.net/stockquote.asmx?op=GetQuote"); methodPost.setRequestBody(data); methodPost.setRequestHeader("Content-Type", "text/xml"); try { int returnCode = httpClient.executeMethod(methodPost); if (returnCode == HttpStatus.SC_NOT_IMPLEMENTED) { System.out .println("The Post method is not implemented by this URI"); methodPost.getResponseBodyAsString(); } else { br = new BufferedReader(new InputStreamReader( methodPost.getResponseBodyAsStream())); String readLine; while (((readLine = br.readLine()) != null)) { System.out.println(readLine); } } } catch (Exception e) { e.printStackTrace(); } finally { methodPost.releaseConnection(); if (br != null) try { br.close(); } catch (Exception fe) { fe.printStackTrace(); } } } }