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();
}
}
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'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;
}
I have this call (from the browser)
http://serverName:8081/cmp-mg-?sub_x?=7
and it returns 200 response
and I want to call do that request from my web service:
this is my web service:
public Response sendMT2(#BeanParam MT mt) throws IOException {
try {
HttpHost host = new HttpHost("serverName", 8081);
HttpClient client = HttpClientBuilder.create().build();
HttpRequest request = new BasicHttpRequest("GET",
"/serverp/sam?" + mt.getURLParameter());
System.out.println("/cmp-mg-xconn-http-webapp/sam?"
+ mt.getURLParameter());
HttpResponse response = client.execute(host, request);
String responseString = new BasicResponseHandler()
.handleResponse(response);
return Response.ok(responseString).build();
} catch (ClientProtocolException e) {
throw e;
// return Response.status(500).build();
} catch (IOException e) {
throw e;
// return Response.status(500).build();
}
}
but I am getting error
org.apache.http.client.HttpResponseException: Not Found
what is the wrong?
I found the error myself.
before sub-r_mob .. i had ? instead of &
My app is currently crashing whenever it cannot connect to the server. How do I handle this, and instead let the user know that the server is down and to try again.
private void sendPostRequest(String givenEmail, String givenPassword) {
class SendPostRequestTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String emailInput = params[0];
String passwordInput = params[1];
String jsonUserInput = "{email: " + emailInput + ", password: "
+ passwordInput + "}";
try {
HttpClient httpClient = new DefaultHttpClient();
// Use only the web page URL as the parameter of the
// HttpPost argument, since it's a post method.
HttpPost httpPost = new HttpPost(SERVER_URL);
// We add the content that we want to pass with the POST
// request to as name-value pairs
json = new JSONObject(jsonUserInput);
jsonString = new StringEntity(json.toString());
httpPost.setEntity(jsonString);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
HttpParams httpParameters = httpPost.getParams();
// Set the timeout in milliseconds until a connection is established.
int timeoutConnection = 1000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 1000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
// HttpResponse is an interface just like HttpPost.
// Therefore we can't initialize them
HttpResponse httpResponse = httpClient.execute(httpPost);
// According to the JAVA API, InputStream constructor does
// nothing.
// So we can't initialize InputStream although it is not an
// interface
InputStream inputStream = httpResponse.getEntity()
.getContent();
InputStreamReader inputStreamReader = new InputStreamReader(
inputStream);
BufferedReader bufferedReader = new BufferedReader(
inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while ((bufferedStrChunk = bufferedReader.readLine()) != null) {
stringBuilder.append(bufferedStrChunk);
}
return stringBuilder.toString();
} catch (ClientProtocolException cpe) {
Log.i(LOGIN, "ClientProtocolException");
cpe.printStackTrace();
} catch (ConnectTimeoutException e) {
e.printStackTrace();
} catch (IOException ioe) {
Log.i(LOGIN, "IOException");
ioe.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.i(LOGIN, result);
try {
serverResponse = new JSONObject(result);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if ((serverResponse.has("status"))
&& (serverResponse.get("status").toString()
.equals("200"))) {
Toast.makeText(getApplicationContext(), "SUCCESS!",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"Incorrect Email/Password!!!",
Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
SendPostRequestTask sendPostRequestTask = new SendPostRequestTask();
sendPostRequestTask.execute(givenEmail, givenPassword);
}
LogCat Error Log
11-11 16:26:14.970: I/R.id.login_button(17379): IOException
11-11 16:26:14.970: W/System.err(17379): org.apache.http.conn.HttpHostConnectException: Connection to http://* refused
11-11 16:26:14.980: W/System.err(17379): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:183)
I can see that you are already catching the Exceptions and have a String as parameter type to onPostExecute. From inside the exceptions, you can pass a string like "error" to the onPostExecute, whenever an error occurs. Inside the onPostExecute you can check:
if the string is equal to "error":
then create a Alert dialog box from within `onPostExecute` and show it.
else:
continue as desired
Ideally a boolean would do the trick but since you already have a string, you can also use that. Otherwise you can have a struct with a string and a boolean and then pass it to onPostExecute. Hope it gives you the idea.
Or you can create new Object
public class AsyncTaskResult<T> {
private T result;
private Exception error;
public T getResult() {
return result;
}
public Exception getError() {
return error;
}
public AsyncTaskResult(T result) {
super();
this.result = result;
}
public AsyncTaskResult(Exception error) {
super();
this.error = error;
}
public void setError(Exception error) {
this.error = error;
}
}
and pass it to onPostExecute
return new AsyncTaskResult<String>(result)
or
return new AsyncTaskResult<String>(exception)
in onPostExecute you may check exception exists or not
asynctaskresult.getError() != null
You can use droidQuery to simplify everything and include HTTP error handling:
$.ajax(new AjaxOptions().url("http://www.example.com")
.type("POST")
.dataType("json")
.header("Accept", "application/json")
.header("Content-type", "application/json")
.timeout(1000)
.success(new Function() {
#Override
public void invoke($ d, Object... args) {
Toast.makeText(this, "SUCCESS!", Toast.LENGTH_SHORT).show();
JSONObject serverResponse = (JSONObject) args[0];
//handle response
}
})
.error(new Function() {
#Override
public void invoke($ d, Object... args) {
AjaxError error = (AjaxError) args[0];
//toast shows the error code and reason, such as "Error 404: Page not found"
Toast.makeText(this, "Error " + error.status + ": " + error.reason, Toast.LENGTH_SHORT).show();
}
}));
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