consume SOAP local web service in android - java

I am trying to consume data from local web service in an android emulator using ksoap2 library, I test the same app with a online webservice http://www.webservicex.net/New/Home/ServiceDetail/17 and It works,
the webService has been made it on Csharp, it has a method to return a column from a DB, call neptuno(spanish adventure works),when execute dont show the data and after a moment show the error message programmed, I change the localhost for my local IP
[WebService(Namespace = "http://testapi.idat/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class Service : System.Web.Services.WebService
{
SqlConnection cn = new SqlConnection("data source=.;initial catalog = neptuno; integrated security=true");
public Service () {
//InitializeComponent();
}
[WebMethod]
public string HelloWorld() {
return "Hello World";
}
[WebMethod]
public DataSet mostrar(){
DataSet ds = new DataSet();
cn.Open();
String sql = "select idProducto from productos";
SqlDataAdapter da = new SqlDataAdapter(sql,cn);
da.Fill(ds);
return ds;
}
}
the service works and return the column IDProduct, the problem is call with the method, I already add the permission on manifest, and the layout is just a textview for error message and edittext multiline for show the data
package com.example.webservice;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.EditText;
import android.widget.TextView;
import android.os.AsyncTask;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
public class MainActivity extends Activity {
EditText resultMultiline;
TextView message;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
resultMultiline = (EditText)findViewById(R.id.editText1);
message = (TextView) findViewById(R.id.textView);
CallWebservice webservice = new CallWebservice();
webservice.execute();
}
public class CallWebservice extends AsyncTask<Integer,Integer,Boolean>{
String resultText = "";
protected Boolean doInBackground(Integer... params){
boolean result = true;
final String SOAP_ACTION = "http://testapi.idat/mostrar";
final String NAMESPACE = "http://testapi.idat/";
final String METHOD_NAME = "mostrar";
final String URL = "http://192.168.1.45:51582/Webservice/Service.asmx?WSDL";
HttpTransportSE transport = new HttpTransportSE(URL);
SoapObject request = new SoapObject(NAMESPACE,METHOD_NAME);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
try {
transport.call(SOAP_ACTION,envelope);
SoapPrimitive respSoap = (SoapPrimitive)envelope.getResponse();
resultText = respSoap.toString();
}catch (Exception e){
result = false;
Log.d("Debug", e.getMessage().toString());
}
return result;
}
protected void onPostExecute(Boolean result){
if (result){
resultMultiline.setText(resultText);
Log.d("Debug","Web service works");
}else{
message.setText("ERROR");
}
}
}
}

Use the Following function it is working in my case this is normal Login soap call you need to add internet permission in your menifest
/*
* Vishal Mokal 05-MAR-2015
* soapCALL() function returns String Array.
* Make A sope call and returns response.
* if responce is success full then user will get responce array
* first element status = 1 if syccessfull 0 = if any exception of faliur
* second element = response srtring if successful or error message.
* */
public String[] soapCALL(RequestDetails requestDetails, String wsdlUserName, String wsdlPassword , String headerName) {
String url = requestDetails.getUrl().toString();
String nameSpace = requestDetails.getNameSpace().toString();
String methodName = requestDetails.getMethodName().toString();
String soapAction = requestDetails.getSoapAction().toString();
String[] responses = new String[2];
Element[] header = new Element[1];
// header[0] = new Element().createElement(nameSpace, "AuthenticationHeader");
header[0] = new Element().createElement(nameSpace, headerName);
try {
Element UserName = new Element().createElement(nameSpace, "UserName");
UserName.addChild(Node.TEXT, wsdlUserName);
header[0].addChild(Node.ELEMENT, UserName);
Element Password = new Element().createElement(nameSpace, "Password");
Password.addChild(Node.TEXT, wsdlPassword);
header[0].addChild(Node.ELEMENT, Password);
SoapObject request = requestDetails.getSoapObject();
SoapSerializationEnvelope soapSerilizationEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
soapSerilizationEnvelope.dotNet = true;
soapSerilizationEnvelope.headerOut = header;
soapSerilizationEnvelope.setOutputSoapObject(request);
Object env = soapSerilizationEnvelope.bodyOut;
HttpTransportSE httptransport = new HttpTransportSE(url);
httptransport.call(soapAction, soapSerilizationEnvelope);
SoapPrimitive response = (SoapPrimitive) soapSerilizationEnvelope.getResponse();
responses[0] = "1";
responses[1] = response.toString();
Log.d("Respons", response.toString());
return responses;
}
catch (SocketTimeoutException e)
{
responses[0] = "0";
responses[1] = "Sorry!Unable To Connect Server Please Check Your Internet Connection Or Try After Some Time.";
return responses;
}
catch (SocketException e)
{
responses[0] = "0";
responses[1] = "Sorry!Unable To Connect Server Please Try After Some Time.";
return responses;
}
catch (Exception e) {
responses[0] = "0";
responses[1] = "Sorry!Unable To Connect Server Please Try After Some Time.";
return responses;
}
}
Following is the structure for the Requestdetail class
public class RequestDetails {
private String nameSpace;
private String url;
private String methodName;
private String SoapAction;
private SoapObject soapObject;
public RequestDetails(String nameSpace, String url, String methodName, String soapAction) {
this.nameSpace = nameSpace;
this.url = url;
this.methodName = methodName;
SoapAction = soapAction;
}
public String getNameSpace() {
return nameSpace;
}
public String getUrl() {
return url;
}
public String getMethodName() {
return methodName;
}
public String getSoapAction() {
return SoapAction;
}
public SoapObject getSoapObject() {
return soapObject;
}
public void setSoapObject(SoapObject soapObject) {
this.soapObject = soapObject;
}
}

Related

Android Twitter App Can't Make Objects from Json Response

I'm trying to simply make objects out of a Twitter stream I download from a user. I am using the information provided from https://github.com/Rockncoder/TwitterTutorial. Can someone help determine if this code actually works? Some of the classes are kind of sketchy, as in the Twitter.java class is just an ArrayList and it only has what's listed below in it.
Is my process correct? Any help is appreciated.
public class MainActivity extends ListActivity {
private ListActivity activity;
final static String ScreenName = "riddlemetombers";
final static String LOG_TAG = "rmt";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
activity = this;
downloadTweets();
}
// download twitter timeline after first checking to see if there is a network connection
public void downloadTweets() {
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
new DownloadTwitterTask().execute(ScreenName);
} else {
Log.v(LOG_TAG, "No network connection available.");
}
}
// Uses an AsyncTask to download a Twitter user's timeline
private class DownloadTwitterTask extends AsyncTask<String, Void, String> {
final String CONSUMER_KEY = (String) getResources().getString(R.string.api_key);
final String CONSUMER_SECRET = (String)getResources().getString(R.string.api_secret);
final static String TwitterTokenURL = "https://api.twitter.com/oauth2/token";
final static String TwitterStreamURL = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=";
#Override
protected String doInBackground(String... screenNames) {
String result = null;
if (screenNames.length > 0) {
result = getTwitterStream(screenNames[0]);
}
return result;
}
// onPostExecute convert the JSON results into a Twitter object (which is an Array list of tweets
#Override
protected void onPostExecute(String result) {
Twitter twits = jsonToTwitter(result);
// lets write the results to the console as well
for (Tweet tweet : twits) {
Log.i(LOG_TAG, tweet.getText());
}
// send the tweets to the adapter for rendering
ArrayAdapter<Tweet> adapter = new ArrayAdapter<Tweet>(activity, R.layout.items, twits);
setListAdapter(adapter);
}
// converts a string of JSON data into a Twitter object
private Twitter jsonToTwitter(String result) {
Twitter twits = null;
if (result != null && result.length() > 0) {
try {
Gson gson = new Gson();
twits = gson.fromJson(result, Twitter.class);
if(twits==null){Log.d(LOG_TAG, "Twits null");}
else if(twits!=null) {Log.d(LOG_TAG, "Twits NOT null");}
} catch (IllegalStateException ex) {
// just eat the exception
}
}
return twits;
}
// convert a JSON authentication object into an Authenticated object
private Authenticated jsonToAuthenticated(String rawAuthorization) {
Authenticated auth = null;
if (rawAuthorization != null && rawAuthorization.length() > 0) {
try {
Gson gson = new Gson();
auth = gson.fromJson(rawAuthorization, Authenticated.class);
} catch (IllegalStateException ex) {
// just eat the exception
}
}
return auth;
}
private String getResponseBody(HttpRequestBase request) {
StringBuilder sb = new StringBuilder();
try {
DefaultHttpClient httpClient = new DefaultHttpClient(new BasicHttpParams());
HttpResponse response = httpClient.execute(request);
int statusCode = response.getStatusLine().getStatusCode();
String reason = response.getStatusLine().getReasonPhrase();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
String line = null;
while ((line = bReader.readLine()) != null) {
sb.append(line);
}
} else {
sb.append(reason);
}
} catch (UnsupportedEncodingException ex) {
} catch (ClientProtocolException ex1) {
} catch (IOException ex2) {
}
return sb.toString();
}
private String getTwitterStream(String screenName) {
String results = null;
// Step 1: Encode consumer key and secret
try {
// URL encode the consumer key and secret
String urlApiKey = URLEncoder.encode(CONSUMER_KEY, "UTF-8");
String urlApiSecret = URLEncoder.encode(CONSUMER_SECRET, "UTF-8");
// Concatenate the encoded consumer key, a colon character, and the
// encoded consumer secret
String combined = urlApiKey + ":" + urlApiSecret;
// Base64 encode the string
String base64Encoded = Base64.encodeToString(combined.getBytes(), Base64.NO_WRAP);
// Step 2: Obtain a bearer token
HttpPost httpPost = new HttpPost(TwitterTokenURL);
httpPost.setHeader("Authorization", "Basic " + base64Encoded);
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
httpPost.setEntity(new StringEntity("grant_type=client_credentials"));
String rawAuthorization = getResponseBody(httpPost);
Authenticated auth = jsonToAuthenticated(rawAuthorization);
// Applications should verify that the value associated with the
// token_type key of the returned object is bearer
if (auth != null && auth.token_type.equals("bearer")) {
// Step 3: Authenticate API requests with bearer token
HttpGet httpGet = new HttpGet(TwitterStreamURL + screenName);
// construct a normal HTTPS request and include an Authorization
// header with the value of Bearer <>
httpGet.setHeader("Authorization", "Bearer " + auth.access_token);
httpGet.setHeader("Content-Type", "application/json");
// update the results with the body of the response
results = getResponseBody(httpGet);
}
} catch (UnsupportedEncodingException ex) {
} catch (IllegalStateException ex1) {
}
return results;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
TWITTER CLASS
import java.util.ArrayList;
// a collection of tweets
public class Twitter extends ArrayList<Tweet> {
private static final long serialVersionUID = 1L;
}
TWEET CLASS
import com.google.gson.annotations.SerializedName;
public class Tweet {
#SerializedName("created_at")
private String DateCreated;
#SerializedName("id")
private String Id;
#SerializedName("text")
private String Text;
#SerializedName("in_reply_to_status_id")
private String InReplyToStatusId;
#SerializedName("in_reply_to_user_id")
private String InReplyToUserId;
#SerializedName("in_reply_to_screen_name")
private String InReplyToScreenName;
#SerializedName("user")
private TwitterUser User;
public String getDateCreated() {
return DateCreated;
}
public String getId() {
return Id;
}
public String getInReplyToScreenName() {
return InReplyToScreenName;
}
public String getInReplyToStatusId() {
return InReplyToStatusId;
}
public String getInReplyToUserId() {
return InReplyToUserId;
}
public String getText() {
return Text;
}
public void setDateCreated(String dateCreated) {
DateCreated = dateCreated;
}
public void setId(String id) {
Id = id;
}
public void setInReplyToScreenName(String inReplyToScreenName) {
InReplyToScreenName = inReplyToScreenName;
}
public void setInReplyToStatusId(String inReplyToStatusId) {
InReplyToStatusId = inReplyToStatusId;
}
public void setInReplyToUserId(String inReplyToUserId) {
InReplyToUserId = inReplyToUserId;
}
public void setText(String text) {
Text = text;
}
public void setUser(TwitterUser user) {
User = user;
}
public TwitterUser getUser() {
return User;
}
#Override
public String toString(){
return getText();
}
}
I've done several Log.d(LOG_TAG, Stuff) to see if I'm getting stuff, and it indicates I'm getting some kind of content back. Maybe the problem is in making objects of the data.
Not sure why you want to use the code from https://github.com/Rockncoder/TwitterTutorial.
Why don't use use http://twitter4j.org. They have give sample example to use it.
Moreover it support Twitter 1.1 as well. Just include twitter-core.jar and you are ready write your code.
Hope it helps.

Java : a WebService asking embeded in a AsyncTask

. Hi, as a young android developer i was looking at a way to get a JSON response from a server.
I started looking at AsyncTask but i not feeling comfortable to code an AsyncTask for each time i needed to ask a WebService.
Then i started to code a class (extends AsyncTask) that query an URL (POST or GET) and provide a callback containing the response from the server.
I wanted to have some feedback, is it really useful, and not an useless overlay of an AsyncTask cause i missed understand something at the beginning.
The more i code it, the more i doubt.
Thanks in advance for your feedback.
Here's the code i use to query a server with my class :
HashMap<String, String> parameters = new HashMap<String, String>();
parameters.put("address", "sidney");
parameters.put("sensor", "false");
WebServiceAsyncTask asyncWS = new WebServiceAsyncTask(MainActivity.this);
asyncWS.setParameters(parameters);
asyncWS.execute(
"http://maps.googleapis.com/maps/api/geocode/json",
WebServiceAsyncTask.GET,
new WebServiceAsyncTaskCallback() {
#Override
void callbackMethod(String result) {
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT).show();
}
}
);
Here's the code of my WebServiceAsyncTask :
import android.app.ProgressDialog;
import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* Anthony Raymond
*/
public class WebServiceAsyncTask extends AsyncTask<Object, String, String> {
public static final String GET = "GET";
public static final String POST = "POST";
private static final String PROGRESS_TEXT_PREPARING = "Preparing request";
private static final String PROGRESS_PERCENT_PREPARING = "25";
private static final String PROGRESS_TEXT_CONNECTION_SERVER = "Connecting to the server";
private static final String PROGRESS_PERCENT_CONNECTION_SERVER = "50";
private static final String PROGRESS_TEXT_PARSING = "Parsing received data";
private static final String PROGRESS_PERCENT_PARSING = "75";
private static final String PROGRESS_TEXT_END = "Process ended";
private static final String PROGRESS_PERCENT_END = "100";
private Context context;
private HashMap<String, String> mData = new HashMap<String, String>();
private ProgressDialog progressDialog;
private WebServiceAsyncTaskCallback callbackClass;
/**
* If a Context is passed, a ProgressDialog will be displayed
* NEED TO PASS Context LIKE THIS :
* MyActivity.this
* DO NOT USE getApplicationContext()
* #param applicationContext
*/
public WebServiceAsyncTask(Context applicationContext)
{
this.context = applicationContext;
}
/**
* Create a WebServiceAsyncTask.
* Usage : add request parameter by passing an HashMap<String, String> with the setParameter Method, then call
* .execute(String url, WebServiceAsyncTask constant (GET or SET), WebServiceAsyncTaskCallback callback)
* exemple :
* HashMap<String, String> parameters = new HashMap<String, String>();
* parameters.put("address", "Sidney");
* parameters.put("sensor", "false");
* WebServiceAsyncTask asyncWS = new WebServiceAsyncTask(MainActivity.this);
* asyncWS.setParameters(parameters);
* asyncWS.execute(
* "http://maps.googleapis.com/maps/api/geocode/json",
* WebServiceAsyncTask.GET,
* new WebServiceAsyncTaskCallback() {
* #Override
* void callbackMethod(String result) {
* Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT).show();
* }
* }
* );
*/
public WebServiceAsyncTask()
{
this.context = null;
}
private void prepareProgressDialog()
{
if (this.context != null)
{
this.progressDialog = new ProgressDialog(this.context);
this.progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
this.progressDialog.setCancelable(true);
this.progressDialog.setTitle("Please Wait...");
this.progressDialog.setMessage(PROGRESS_TEXT_PREPARING);
this.progressDialog.setProgress(Integer.parseInt(PROGRESS_PERCENT_PREPARING));
}
}
private String getPostResponse(String url)
{
byte[] result;
String str = "";
HttpClient client = new DefaultHttpClient();
HttpPost http = new HttpPost(url);
// set up post data
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
for (String key : this.mData.keySet()) {
nameValuePair.add(new BasicNameValuePair(key, this.mData.get(key)));
}
UrlEncodedFormEntity urlEncodedFormEntity;
try
{
urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePair);
http.setEntity(urlEncodedFormEntity);
this.publishProgress(PROGRESS_TEXT_CONNECTION_SERVER, PROGRESS_PERCENT_CONNECTION_SERVER);
HttpResponse response = client.execute(http);
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpURLConnection.HTTP_OK)
{
this.publishProgress(PROGRESS_TEXT_PARSING, PROGRESS_PERCENT_PARSING);
result = EntityUtils.toByteArray(response.getEntity());
str = new String(result, HTTP.UTF_8);
}
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
return str;
}
private String getGetResponse(String url)
{
byte[] result;
String str = "";
HttpClient client = new DefaultHttpClient();
try
{
// set up get data and URL
Uri.Builder uri = Uri.parse(url).buildUpon();
for (String key : this.mData.keySet()) {
uri.appendQueryParameter(key, this.mData.get(key));
}
HttpGet http = new HttpGet(String.valueOf(uri));
this.publishProgress(PROGRESS_TEXT_CONNECTION_SERVER, PROGRESS_PERCENT_CONNECTION_SERVER);
HttpResponse response = client.execute(http);
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpURLConnection.HTTP_OK)
{
this.publishProgress(PROGRESS_TEXT_PARSING, PROGRESS_PERCENT_PARSING);
result = EntityUtils.toByteArray(response.getEntity());
str = new String(result, HTTP.UTF_8);
}
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
return str;
}
public void setParameters(HashMap<String, String> httpRequestParameters)
{
this.mData = httpRequestParameters;
}
#Override
protected String doInBackground(Object... params)
{
// Ensure that we got, URL, http method and Callback
if (params.length != 3)
{
this.cancel(true);
}
else
{
if ((params[2] instanceof WebServiceAsyncTaskCallback))
{
this.callbackClass = ((WebServiceAsyncTaskCallback)params[2]);
}
else
{
this.cancel(true);
}
try {
URL url = new URL((String)params[0]);
} catch (MalformedURLException e) {
this.callbackClass.onError("First param must be a valid URL. (" + params[0] + " given)");
this.cancel(true);
}
if (!((String)params[1]).equals(POST) && !((String)params[1]).equals(GET))
{
this.callbackClass.onError("Second parameters must be " + this.getClass().getName() + " POST or GET constant");
this.cancel(true);
}
}
String str = "";
//IS OUR REQUEST A POST
if (params.length > 1)
{
if (((String)params[1]).toUpperCase().equals(WebServiceAsyncTask.POST))
{
str = getPostResponse(((String)params[0]));
}
else if(((String)params[1]).toUpperCase().equals(WebServiceAsyncTask.GET)) //THEN GET
{
str = getGetResponse(((String)params[0]));
}
}
return str;
}
#Override
protected void onPostExecute(String result)
{
this.mData = null;
if (this.context != null)
{
this.publishProgress(PROGRESS_TEXT_END, PROGRESS_PERCENT_END);
this.progressDialog.dismiss();
}
if (this.callbackClass != null)
{
this.callbackClass.callbackMethod(result);
}
}
#Override
protected void onPreExecute()
{
if (this.context != null)
{
this.prepareProgressDialog();
this.progressDialog.show();
}
}
#Override
protected void onProgressUpdate(String... values) {
if (this.context != null)
{
this.progressDialog.setMessage(values[0]);
this.progressDialog.setProgress(Integer.parseInt(values[1]));
}
}
}
/**
* Allow to easily get the server response
*/
abstract class WebServiceAsyncTaskCallback{
/**
* Return the server response as String
* #param result server response as a String
*/
abstract void callbackMethod(String result);
/**
* This method is design to report simple errors for development phase.
* #param errMessage contains error message
*/
protected void onError(String errMessage){};
;
}
Your use of AsyncTask appears appropriate. As you may be aware.. for network communications you must use AsyncTask or your own thread (extend HandlerThread.)
If your app is frequently calling AsyncTask or is executing simultaneous AsyncTask then creating your own thread will be more efficient (all AsyncTask requests use a single thread in API 13 and up.)
I'm unfamiliar with your app and how it functions.. do your users require the dialogs and status feedback for thses background network transmissions?
Can I just point out that, because you are not doing this in a Service, your remote query stands every chance of being killed, as soon your Activity is hidden. You have, essentially, rewritten IntentService... except that your version will get killed and the version the framework provides, free, will not
IntentService, FTW

XML-RPC Error, org.xmlpull.v1.XmlPullParserException

I'm try make an application chatbot in Android. I use Pandorabots as Chatbot server. To connect between Device Android with the Server. I use pandorabot XML-RPC API, and i use xml-rpc library from android-xmlrpc. so this my code:
public class MainActivity extends Activity {
private EditText editOne;
private TextView textOne;
private Button ButtonOne;
private XMLRPCClient server;
private URI uri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
uri = URI.create("http://www.pandorabots.com/pandora/talk-xml?botid=e80e92407e341007");
server = new XMLRPCClient(uri);
editOne = (EditText) findViewById(R.id.editText1);
textOne = (TextView) findViewById(R.id.textView1);
ButtonOne = (Button) findViewById(R.id.button1);
textSatu.setText(getDataMethod("hi"));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private String getDataMethod(String num) {
String text = "";
try {
Log.w("Running server.call", "prosess");
Object[] data = (Object[]) server.call("input", num);
Log.w("server.call Run", "finish");
Log.w("Run HashMap", "prosess");
for(Object o: data) {
HashMap map = (HashMap) o;
Log.w("HashMap Berjalan", "Error");
text = text + "'that' => " + map.get("that") + "\n\n";
}
} catch (XMLRPCException e) {
Log.w("XMLRPC Test", "Error", e);
text = "XMLRPC error";
}
return text;
}
}
But i got error. It's say :org.xmlpull.v1.XmlPullParserException: expected: START_TAG {null}methodResponse (position:START_TAG #1:45 in java.io.InputStreamReader#41174280)
can anyone help me? please.
here is a solution that does not require XMLRPCClient. The important thing is to capture the customer ID on the first interaction with the bot, and then send the value of custid back with each subsequent transaction. The bot uses the custid to remember the local variables associated with a conversation thread, such as name, age, gender, topic etc.
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URLEncoder;
public class PandorabotsTalkAPI {
public String defaultCustid = "0";
public String custid = defaultCustid;
public String responseFailed = "RESPONSE FAILED";
public String defaultBotId = "f5d922d97e345aa1";
public String defaultHost = "www.pandorabots.com";
public String askPandorabots(String input) {
return askPandorabots(input, defaultHost, defaultBotId);
}
public String askPandorabots(String input, String host, String botid) {
//System.out.println("Entering askPandorabots with input="+input+" host ="+host+" botid="+botid);
String responseContent = pandorabotsRequest(input, host, botid);
if (responseContent == null) return responseFailed;
else return pandorabotsResponse(responseContent, host, botid);
}
public String responseContent(String url) throws Exception {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(url));
InputStream is = client.execute(request).getEntity().getContent();
BufferedReader inb = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder("");
String line;
String NL = System.getProperty("line.separator");
while ((line = inb.readLine()) != null) {
sb.append(line).append(NL);
}
inb.close();
return sb.toString();
}
public String spec(String host, String botid, String custid, String input) {
//System.out.println("--> custid = "+custid);
String spec = "";
try {
if (custid.equals("0")) // get custid on first transaction with Pandorabots
spec = String.format("%s?botid=%s&input=%s",
"http://" + host + "/pandora/talk-xml",
botid,
URLEncoder.encode(input, "UTF-8"));
else spec = // re-use custid on each subsequent interaction
String.format("%s?botid=%s&custid=%s&input=%s",
"http://" + host + "/pandora/talk-xml",
botid,
custid,
URLEncoder.encode(input, "UTF-8"));
} catch (Exception ex) {
ex.printStackTrace();
}
//System.out.println(spec);
return spec;
}
public String pandorabotsRequest(String input, String host, String botid) {
try {
String spec = spec(host, botid, custid, input);
//System.out.println("Spec = "+spec);
String responseContent = responseContent(spec);
return responseContent;
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
public String pandorabotsResponse (String xmlRpcResponse, String host, String botid) {
String botResponse = responseFailed;
try {
int n1 = xmlRpcResponse.indexOf("<that>");
int n2 = xmlRpcResponse.indexOf("</that>");
if (n2 > n1)
botResponse = xmlRpcResponse.substring(n1+"<that>".length(), n2);
n1 = xmlRpcResponse.indexOf("custid=");
if (n1 > 0) {
custid = xmlRpcResponse.substring(n1+"custid=\"".length(), xmlRpcResponse.length());
n2 = custid.indexOf("\"");
if (n2 > 0) custid = custid.substring(0, n2);
else custid = defaultCustid;
}
if (botResponse.endsWith(".")) botResponse = botResponse.substring(0, botResponse.length()-1); // snnoying Pandorabots extra "."
} catch (Exception ex) {
ex.printStackTrace();
}
return botResponse;
}
}

Connect Android App to Java web services And pass Value to Web services

This is the web services that i want to connect and send value from android virtual machine.
#WebService(serviceName = "EmoDeneme")
#Stateless()
public class EmoDeneme {
/**
* This is a sample web service operation
*/
#WebMethod(operationName = "hello")
public String hello(#WebParam(name = "name") String name) {
String BargeName = "";
int BargeNo = 0;
String Starting = "";
String StartingDate = "";
try {
MongoClient mongoClient = new MongoClient("localhost", 27017);
DB db = mongoClient.getDB("Barge");
DBCollection collection = db.getCollection("Emo");
DBObject match = new BasicDBObject("$match", new BasicDBObject("html.table.tbody.Barge.Name", name));
DBObject unwind = new BasicDBObject("$unwind", "$html.table.tbody.Barge");
AggregationOutput output = collection.aggregate(unwind, match);
for (DBObject result : output.results()) {
DBObject htmlObj = (DBObject) result.get("html");
DBObject tableObj = (DBObject) htmlObj.get("table");
DBObject tbodyObj = (DBObject) tableObj.get("tbody");
DBObject bargeObj = (DBObject) tbodyObj.get("Barge");
BargeName = (String) bargeObj.get("Name");
BargeNo = (Integer) bargeObj.get("Bargeno");
Starting = (String) bargeObj.get("Starting");
StartingDate = Starting.substring(0, 10);
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (MongoException e) {
e.printStackTrace();
}
return "Terminal: " + " BargeName :" + BargeName + " BargeNo: " + BargeNo + " ETA
: " + StartingDate;
}
}
This is the Android Code to connect to web service
public class MainActivity extends Activity {
private static final String SOAP_ACTION = "";
private static final String METHOD_NAME = "hello";
private static final String NAMESPACE = "http://mongodb.me.org/";
private static final String URL = "http://10.0.2.2:8080/EmoDeneme/EmoDeneme?WSDL";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Thread networkThread = new Thread() {
#Override
public void run() {
try {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
String firstName = "Aan";
//Pass value for fname variable of the web service
PropertyInfo fnameProp =new PropertyInfo();
fnameProp.setName("name");//Define the variable name in the web service `method`
fnameProp.setValue(firstname);//Define value for fname variable
fnameProp.setType(String.class);//Define the type of the variable
request.addProperty(fnameProp);//Pass properties to the variable
SoapSerializationEnvelope envelope = new `SoapSerializationEnvelope(SoapEnvelope.VER11);`
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE ht = new HttpTransportSE(URL);
ht.call(SOAP_ACTION, envelope);
final SoapPrimitive response = (SoapPrimitive)envelope.getResponse();
final String str = response.toString();
runOnUiThread (new Runnable(){
public void run() {
TextView result;
result = (TextView)findViewById(R.id.textView1);//I have created a text view `& It's id is textView1`
result.setText(str);
}
});
}
catch (Exception e) {
e.printStackTrace();
}
}
};
networkThread.start();
}
}
It does not work, can someone help me please what i do wrong.
Thank you.
SOAP calls can get messy. There is a better way of calling a web service. Check out the following 2 videos:
http://javabrains.koushik.org/2013/06/writing-web-service-client-stub.html
http://javabrains.koushik.org/2013/06/writing-web-service-client-calling.html
In the first video the author generated java code by using the command line and pointing to a wsdl and in the second video he calls functions from the generated java code.
And if you want to do some really interesting things with web services check out:
http://cxf.apache.org/
Hope this helps.
PS. there is a really cool tool if you are into SOAP: http://www.soapui.org/

Why CalledFromWrongThreadException when no UI calls?

I have an AsyncTask which calls a webservice method and sends the returned data back to the main thread. This task does not affect any UI elements yet throws CalledFromWrongThreadException on the line calling onResultSuccess. I have many other AsyncTask which work in basically the exact same way, changing the called web service method and parameters, etc, but this is the only one that fails. Anyone spot what might be the problem? The AsyncTask looks like:
public static class ClockOff extends AsyncTask<String, Void, Void>
{
public OnAsyncResultClockOff onAsyncResultClockOff;
public void setOnResultListener(OnAsyncResultClockOff onAsyncResultClockOff) {
if(onAsyncResultClockOff != null) {
ResultClockOff = onAsyncResultClockOff;
}
}
private static final String SOAP_ACTION = "http://tempuri.org/ClockOff";
private static final String METHOD_NAME = "ClockOff";
private static final String NAMESPACE = "http://tempuri.org/";
private static final String URL = GlobalFunction.URL;
#Override
protected Void doInBackground(String... strArgs)
{
try
{
SoapObject Request = new SoapObject(NAMESPACE, METHOD_NAME);
Request.addProperty("Items", strArgs[0]);
Request.addProperty("ID", strArgs[1]);
SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
soapEnvelope.dotNet = true;
soapEnvelope.setOutputSoapObject(Request);
HttpTransportSE transport= new HttpTransportSE(URL);
transport.call(SOAP_ACTION, soapEnvelope);
SoapObject result = (SoapObject) soapEnvelope.bodyIn;
String ReturnMessage = ((SoapObject) result.getProperty(0)).getPropertyAsString(0);
String ReturnMessageHeader = ((SoapObject) result.getProperty(0)).getPropertyAsString(1);
String ActionType = ((SoapObject) result.getProperty(0)).getPropertyAsString(2);
String SelectedCompleted = ((SoapObject) result.getProperty(0)).getPropertyAsString(3);
String ClockOffItems = ((SoapObject) result.getProperty(0)).getPropertyAsString(4);
//Exception thrown on the below line
onAsyncResultClockOffItem.onResultSuccess(ReturnMessage, ReturnMessageHeader, ActionType, SelectedCompleted, ClockOffItems);
return null;
}
catch (Exception e)
{
onAsyncResultClockOffItem.onResultFail();
return null;
}
}
}
OnAsyncResultClockOff is simply:
public interface OnAsyncResultClockOff {
public abstract void onResultFail();
public abstract void onResultSuccess(String returnMessage,
String returnMessageHeader, String actionType,
String selectedCompleted, String clockOffItems);
}
And it is called via:
ClockOff co= new ClockOffItem();
co.setOnResultListener(onAsyncResultClockOff);
co.execute(items, ID);
Where onAsyncResultClockOff implements the OnResultFail() and OnResultSuccess methods.

Categories

Resources