I'm trying to connect with a web service.
The sample request for this web service contains this array:
<Details>
<invoiceDetails>
<ItemID>int</ItemID>
<Price>decimal</Price>
<Quantity>decimal</Quantity>
<UOM>int</UOM>
</invoiceDetails>
<invoiceDetails>
<ItemID>int</ItemID>
<Price>decimal</Price>
<Quantity>decimal</Quantity>
<UOM>int</UOM>
</invoiceDetails>
</Details>
I have managed to make a call with SOAP before, but not with arrays,
so how would I add this to my request?
Try this code,
public String getservicecallmethod(String nameSpace, String methodName,
String soapAction, String Url, List<Info> mInfo) {
String mResponse = "";
SoapObject request = new SoapObject(nameSpace, methodName);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
if (mPropertyInfo != null) {
for (Info propertyInfo : mInfo) {
request.addProperty(propertyInfo);
}
}
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE ht = new HttpTransportSE(Url);
ht.debug = true;
try {
ht.call(soapAction, envelope);
} catch (IOException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
try {
mResponse = envelope.getResponse().toString();
} catch (Exception e) {
e.printStackTrace();
}
return mResponse;
}
Related
I want to build a soap request using KSOAP2 for android application. how to create a request for the given below soap request.
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:glob="http://sap.com/xi/SAPGlobal20/Global"
xmlns:yrt="http://0021611689-one-off.sap.com/YRTWIVFXY_"
xmlns:ytk="http://0021611689-one-off.sap.com/YTK2PLNNY_"
xmlns:glob1="http://sap.com/xi/AP/Globalization">`
<soapenv:Header/>
<soapenv:Body>
<glob:CustomerBundleMaintainRequest_sync_V1>
<BasicMessageHeader>
</BasicMessageHeader>
<Customer>
<InternalID>234569</InternalID>
<!--Optional:-->
<CategoryCode>1</CategoryCode>
<CustomerIndicator>true</CustomerIndicator>
<!--Optional:-->
<LifeCycleStatusCode>2</LifeCycleStatusCode>
<!--Optional:-->
</Customer>
</glob:CustomerBundleMaintainRequest_sync_V1>
</soapenv:Body>
</soapenv:Envelope>
I have written the Android code and tried to build the request it shows an error that Soapfault message error. Find below the android code
public class CreateCustomer {
public void createCustomerAccount() throws IOException {
SoapObject soapObject = new SoapObject(NAME_SPACE,METHOD_NAME);
soapObject.addProperty("InternalID","98765");
soapObject.addProperty("CategoryCode","1");
soapObject.addProperty("CustomerIndicator","true");
soapObject.addProperty("LifeCycleStatusCode","2");
}
For Building soap request ..
public String sendSoapRequest(Context c) throws Exception {
String finalString = "Paste your whole request through which you can send request from browser sucessfully";
Log.i("TAG", "*********************** FinalString Before "
+ FinalString);
// send SOAP request
InputStream resInputStream = sendRequest(FinalString);
// create the response SOAP envelope
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
// process SOAP response
parseResponse(resInputStream, envelope);
Object bodyIn = envelope.bodyIn;
SoapObject RequestSOAP = (SoapObject) envelope.bodyIn;
String response = RequestSOAP.getProperty(0).toString();
if (bodyIn instanceof SoapFault) {
throw (SoapFault) bodyIn;
}
return response.toString();
}
calling sendRequest ..
private InputStream sendRequest(String requestContent) throws Exception {
// initialize HTTP post
HttpPost httpPost = null;
try {
httpPost = new HttpPost(PostURL);
httpPost.addHeader("Content-Type", "text/xml;charset=UTF-8");
httpPost.addHeader("SOAPAction", "Your Soap Action");
} catch (Throwable e) {
Log.e("LOG_TAG", "Error initializing HTTP post for SOAP request", e);
// throw e;
}
// load content to be sent
try {
HttpEntity postEntity = new StringEntity(requestContent);
httpPost.setEntity(postEntity);
} catch (UnsupportedEncodingException e) {
Log.e("LOG_TAG",
"Unsupported ensoding of content for SOAP request", e);
throw e;
}
// send request
HttpResponse httpResponse = null;
HttpClient httpClient = new DefaultHttpClient();
try {
httpResponse = httpClient.execute(httpPost);
} catch (Throwable e) {
Log.e("LOG_TAG", "Error sending SOAP request", e);
// throw e;
}
// get SOAP response
try {
// get response code
int responseStatusCode = httpResponse.getStatusLine()
.getStatusCode();
// if the response code is not 200 - OK, or 500 - Internal error,
// then communication error occurred
if (responseStatusCode != 200 && responseStatusCode != 500) {
String errorMsg = "Got SOAP response code "
+ responseStatusCode + " "
+ httpResponse.getStatusLine().getReasonPhrase();
// ...
}
// get the response content
HttpEntity httpEntity = httpResponse.getEntity();
InputStream is = httpEntity.getContent();
return is;
} catch (Throwable e) {
Log.e("LOG_TAG", "Error getting SOAP response", e);
// throw e;
}
return null;
}
call parseResponse
/**
* Parses the input stream from the response into SoapEnvelope object.
*/
private void parseResponse(InputStream is, SoapEnvelope envelope)
throws Exception {
try {
XmlPullParser xp = new KXmlParser();
xp.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
xp.setInput(is, "UTF-8");
envelope.parse(xp);
} catch (Throwable e) {
Log.e("LOG_TAG", "Error reading/parsing SOAP response", e);
}
}
call SendOrderDetails...
private class SendOrderDetails extends AsyncTask<String, CartViewItemsBean, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... arg) {
String fdfd = "";
try {
fdfd = sendSoapRequest(getActivity());
} catch (Exception e) {
e.printStackTrace();
}
return fdfd;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.i("transactionresponse", result);
if (!result.equalsIgnoreCase("")) {
try {
helpher.deleteTotalRecord();
String ffsd = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + result.toString();
XmlToJson xmlToJson = new XmlToJson.Builder(ffsd.trim()).build();
JSONObject jsonObject = xmlToJson.toJson();
} catch (Exception e) {
e.printStackTrace();
}
} else {
}
}
}
And you have to use library XmlToJson
finally you have to call this using
new SendOrderDetails().execute();
I have developed an Android Application which consumes a Webservice. I have tested the application on different devices and its working perfectly but on the tablet of my client, it's throwing an exception. All devices on which application is tested are running Android 6.0.1 Marshmallow.Following is the exception
java.net.ConnectException: failed to connect to web.abc.com(port 80):connect failed: ECONNREFUSED (Connection refused)
Following is my code for consuming Webservice
String namespace = "http://web.abc.com/";
private static final String url = "http://web.abc.com/WebService/ServiceFileName.asmx";
String SOAP_ACTION;
SoapObject request = null, objMessages = null;
SoapSerializationEnvelope envelope;
HttpTransportSE androidHttpTransport;
/**
* Set Envelope
*/
protected void SetEnvelope() {
try {
// Creating SOAP envelope
envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
//You can comment that line if your web service is not .NET one.
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
//envelope.addMapping(namespace, "ProductStausResponse",new ProductStausResponse().getClass());
androidHttpTransport = new HttpTransportSE(url);
androidHttpTransport.debug = true;
} catch (Exception e) {
e.printStackTrace();
Log.v("Soap Exception", e.toString());
System.out.println("Soap Exception---->>>" + e.toString());
}
}
// MethodName variable is define for which webservice function will call
public String getProductStatus(String MethodName, String Parameter)
{
try {
ProductCode = ProductCode.trim();
SOAP_ACTION = namespace + MethodName;
//Adding values to request object
request = new SoapObject(namespace, MethodName);
/// Code for setting properties
SetEnvelope();
try {
//SOAP calling webservice
androidHttpTransport.call(SOAP_ACTION, envelope);
//Got Webservice response
String result = envelope.getResponse().toString();
return result;
} catch (Exception e) {
// TODO: handle exception
//e.printStackTrace();
//return "Exception";
return e.toString();
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
Log.v("Soap Exception", e.toString());
//return "Exception";
return e.toString();
}
}
I'm using SOAP service to get ticket. I'm sending user and pass, and I'm getting xml in String. For this I'm using ksoap2.
#Override
protected String doInBackground(String... params) {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty(USER, params[0]);
request.addProperty(PASS, params[1]);
SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
soapEnvelope.bodyOut = request;
soapEnvelope.setOutputSoapObject(request);
HttpTransportSE HttpTransport = new HttpTransportSE(URL);
try {
HttpTransport.call(SOAP_ACTION, soapEnvelope);
return soapEnvelope.getResponse().toString();
} catch (IOException | XmlPullParserException e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(String XML) {
super.onPostExecute(XML);
if (result != null) {
// Here I need to get data from XML
}
}
My XML String looks like this:
<?xml version="1.0" encoding="UTF-8" ?>
<resp err="0">
<ticket>1234567989</ticket>
</resp>
So I need to get the error number, and the ticket number.
Don't convert your response to String and return it, instead get properties you need with getProperty() method and convert them to String. Here's how i was doing it:
String ticket;
public void getSoap() {
SoapObject request = new SoapObject(NAMESPACE, METHODNAME);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.implicitTypes = false;
envelope.setOutputSoapObject(request);
HttpTransportSE httpTransportSe = new HttpTransportSE(URL);
httpTransportSe.debug = true;
SoapObject response = null;
try {
httpTransportSe.call(SOAPACTION, envelope);
response = (SoapObject) envelope.getResponse();
ticket = response.getProperty("ticket").toString();
} catch (Exception e) {
e.printStackTrace();
}
}
Getting "err" element from attribute might require a bit more research but you can try this where you get ticket:
String err = response.getAttribute("err").toString;
Hope this helps and happy coding !
Use JDom to parse XML:
String xmlString = //get xml string;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
try
{
builder = factory.newDocumentBuilder();
Document document = builder.parse( new InputSource( new StringReader( xmlString ) ) );
} catch (Exception e) {
e.printStackTrace();
}
and next get values via XPath from document http://www.w3schools.com/xpath/xpath_examples.asp
I am creating an HttpPost object in Android to communicate with a server operated by a client. Unfortunately the server isn't providing either of us with very useful error messages; I would like to see the content of the HttpPost object as a string so I can send it to our client and he can compare it with what he's expecting.
How can I convert an HttpPost object into a string that reflects how it would look as it arrived at the server?
Should use it after execute
public static String httpPostToString(HttpPost httppost) {
StringBuilder sb = new StringBuilder();
sb.append("\nRequestLine:");
sb.append(httppost.getRequestLine().toString());
int i = 0;
for(Header header : httppost.getAllHeaders()){
if(i == 0){
sb.append("\nHeader:");
}
i++;
for(HeaderElement element : header.getElements()){
for(NameValuePair nvp :element.getParameters()){
sb.append(nvp.getName());
sb.append("=");
sb.append(nvp.getValue());
sb.append(";");
}
}
}
HttpEntity entity = httppost.getEntity();
String content = "";
if(entity != null){
try {
content = IOUtils.toString(entity.getContent());
} catch (Exception e) {
e.printStackTrace();
}
}
sb.append("\nContent:");
sb.append(content);
return sb.toString();
}
snippet
I usually do post in this way (The server answer is a JSON object) :
try {
postJSON.put("param1", param1);
postJSON.put("param2",param2);
} catch (JSONException e) {
e.printStackTrace();
}
String result = JSONGetHTTP.postData(url);
if (result != null) {
try {
JSONObject jObjec = new JSONObject(result);
}
} catch (JSONException e) {
Log.e(TAG, "Error setting data " + e.toString());
}
}
And postData is:
public static String postData(String url, JSONObject obj) {
// Create a new HttpClient and Post Header
HttpClient httpclient = null;
try {
HttpParams myParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(myParams, 30000);
HttpConnectionParams.setSoTimeout(myParams, 30000);
httpclient = new DefaultHttpClient(myParams);
} catch (Exception e) {
Log.e("POST_DATA", "error in httpConnection");
e.printStackTrace();
}
InputStream is = null;
try {
HttpPost httppost = new HttpPost(url.toString());
//Header here httppost.setHeader();
StringEntity se = new StringEntity(obj.toString());
httppost.setEntity(se);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
// // Do something with response...
is = entity.getContent();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// convert response to string
BufferedReader reader = null;
String result = null;
try {
reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
} finally {
try {
if (reader != null)
reader.close();
if (is != null)
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (result != null) {
try {
#SuppressWarnings("unused")
JSONObject jObjec = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
}
return result;
}
Hope it helps
Well i actually did HTTP-Post using NameValuePair...... I am showing the code which i use to do an HTTP-Post and then converting the Response into a String
See the below Method code:
public String postData(String url, String xmlQuery) {
final String urlStr = url;
final String xmlStr = xmlQuery;
final StringBuilder sb = new StringBuilder();
Thread t1 = new Thread(new Runnable() {
public void run() {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(urlStr);
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("xml", xmlStr));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
Log.d("Vivek", response.toString());
HttpEntity entity = response.getEntity();
InputStream i = entity.getContent();
Log.d("Vivek", i.toString());
InputStreamReader isr = new InputStreamReader(i);
BufferedReader br = new BufferedReader(isr);
String s = null;
while ((s = br.readLine()) != null) {
Log.d("YumZing", s);
sb.append(s);
}
Log.d("Check Now",sb+"");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
t1.start();
try {
t1.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Getting from Post Data Method "+sb.toString());
return sb.toString();
}
I have added the library "ksoap2-android-assembly-2.4-jar-with-dependencies.jar "
but i am getting below error :
Exception in thread "main" java.lang.NullPointerException at org.kxml2.io.KXmlParser.require(KXmlParser.java:1353) at org.ksoap2.SoapEnvelope.parse(SoapEnvelope.java:127) at org.ksoap2.transport.Transport.parseResponse(Transport.java:63) at org.ksoap2.transport.HttpTransportSE.call(HttpTransportSE.java:100)
private void getData()
{
String METHOD_NAME = "schedule.setschedule";
String SOAP_ACTION = "urn:schedule#setschedule";
String NAMESPACE = "urn:schedule";
String URL = "http://96.30.19.40:8080/server.php?wsdl";
try {
SoapObject request=soap(METHOD_NAME,SOAP_ACTION,NAMESPACE,URL);
System.out.println("suceess");
System.out.println(request.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("fail1");
e.printStackTrace();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("fail2");
}
}
public static SoapObject soap(String METHOD_NAME, String SOAP_ACTION, String NAMESPACE, String URL) throws IOException, XmlPullParserException {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME); //set up request
request.addProperty("iTopN", "5"); //variable name, value. I got the variable name, from the wsdl file!
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); //put all required data into a soap envelope
envelope.setOutputSoapObject(request); //prepare request
HttpTransport httpTransport = new HttpTransport(URL);
httpTransport.debug = true; //this is optional, use it if you don't want to use a packet sniffer to check what the sent message was (httpTransport.requestDump)
httpTransport.call(SOAP_ACTION, envelope); //send request
SoapObject result=(SoapObject)envelope.getResponse(); //get response
return result;
}
The correct download url for the project is here
http://code.google.com/p/ksoap2-android/wiki/HowToUse?tm=2
The direct url provided above is an old version. Read the instructions and download the complete bundle.
You may not have the correct ksoap2 package