WCF used in Android Project (FileNotFoundException) - java

I have a simple web service in c#.
Here is the C# code :
IService1.cs
[ServiceContract(ConfigurationName = "IService")]
public interface IService1
{
[OperationContract]
[WebGet]
string TestAndroid();
}
Service1.svc.cs
public class Service1 : IService1
{
public string TestAndroid()
{
return "Test done !";
}
}
Here is the Android code :
protected Boolean doInBackground(String... urls) {
try {
URL url = new URL("http://10.0.2.2:49363/Service1.svc/TestAndroid");
InputStream in = new BufferedInputStream(httpURLConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line = reader.readLine();
reader.close();
} catch(Exception e){
return false;
}
return null;
}
When I want to read the InputStream, I have an error.
It's
java.io.FileNotFoundException:
http://10.0.2.2:49363/Service1.svc/TestAndroid
I don't know where is the problem, because when I go in browser I have
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">Test done !</string>
Can someone help me ?

I hope your service is working and you had tested it on your computer by invoking url http://10.0.2.2:49363/Service1.svc/TestAndroid
Am I right?
Then simple explanation for your issue would be that your Android doesn't know about ip address 10.0.2.2.
Can you validate that is accessible? Just try to open the same url in browser on your Android device.
Simple solution to see this IP address - your phone should be on the same WiFi as your computer.
Update:
Goal is to see computer with service running WCF host. Question is - can Android device see WCF host?
The opposite direction is irrelevant but it's good to know that
Android emulator cannot be seen from the computer. Here is good explanation

Related

Issue getting the azure translator to work with Android

My android app used the old microsoft Translator very well but I am having
problems getting the app to work with the new Cognitive Services.
First I got a new azure translation account that has the following values
(these are not the real values)
Name: MYTranslateAcct
Resource group: translate
subscription ID: 981h5ce7-7ac7-4f6f-b4a5-ff04dc9e4266
key1 d122230418a8479ab5c06f2f1fca664c
key2 39c1f187o9814f4e983jba9eedd2e2c7
My first step is to try to get a token. Microsoft has docs on doing
this in JAVA but not in an Android environment. I dug around and have
put together some code but it is not working. One problem is that the
docs use terms that I don't have in my account such as "app-id" and
"key". I don't have those things - I just have the list of values
above.
Here is my code . . .
class translateMessage extends AsyncTask<Void, Void, String>
{
String retString;
String inString = null;
translateMessage(String inString) { this.inString = inString; }
#Override
protected String doInBackground(Void... arg0)
{
try
{
String key = "881b5ce7-9ac7-4f6f-b4a5-ff04dc9e3199";
String authenticationUrl = "https://api.cognitive.microsoft.com/sts/v1.0/issueToken";
HttpsURLConnection authConn = (HttpsURLConnection) new URL(authenticationUrl).openConnection();
authConn.setRequestMethod("POST");
authConn.setDoOutput(true);
authConn.setRequestProperty("Ocp-Apim-Subscription-Key", key);
IOUtils.write("", authConn.getOutputStream(), "UTF-8"); //following line of code gets the exception . . .
String token = IOUtils.toString(authConn.getInputStream(), "UTF-8"); //this blows
}
catch (Exception e)
{
String myString = e.getMessage();
String aString = "look at e";
}
return retString;
}
#Override
protected void onPostExecute(String result)
{
String debugStr = result;
translation.setText(result);
}
}
Following is the exception . . .
java.io.FileNotFoundException:https://api.cognitive.microsoft.com/sts/v1.0/issueToken
What am I doing wrong?
Is anyone aware of any working Android java code using the new services?
I posted this on Azure support and someone called me within an hour. I was passing the wrong key. When you get a translate cognitive account you get Key1 and Key2. Either of them will work. So the code is a useful example of working code that will get a token.

KSoap2 on Android freezing the device instead of making a webservice call

I'm trying to connect to .NET 4.0 webservice I created for receiving SOAP-calls from Android-devices, now hosted on local IIS for testing purposes.
I found out that ksoap2 would be an excellent class library for doing what i want to do. Downloaded the .jar package from https://code.google.com/p/ksoap2-android/ and started pounding the keyboard in ecstacy... with my fingers.
The amount of information being sent is from few kilobytes to few megabytes.
What is working
HttpTransportSE.call(String, SoapSerializationEnvelope)-method works perfectly while still in Eclipse's Android emulator, sending the call to webservice hosted in local IIS. Even tested that the webservice receives empty calls from trying to open the service address from a web browser in the same local area network.
What doesn't work
When I copy the .apk-file to an Android device, install it, start it and trying to make the call, the whole program freezes without making the call.
As you can see from a code block presented some lines after that possible errors are being taken into account: In emulated environment a successful call returns a SoapPrimitive-object or flows into the correct catch block generating an error message for the user according to the current situation.
Then on live Android device, program loses it's responsivity forever and has to be terminated from application menu.
What have i tried
I removed the call from the asynchronous method, and tried calling it straight from an anonymous inner function assigned for a button click-event.
Tried not trying to get a response, just making the call.
Tried getting a logcat-program for the device to see what's happening behind the UI, found two, they needed root access, which i don't have in the device. This is why i don't have any logcats to show you, and showing the emulator logcat would probably(?) be useless because it works fine there.
Not trying to connect to localhost.
Tried installing the program on older Lenovo-tablet running Android 4.2.2 and on brand new Samsung Galaxy Tab, both would have the same problem while otherwise working well.
The code
Here's the asynchronous method for making the call in device/emulator, where variables str_URL and soapRequest are a correct service address (checked) and a well formed SoapObject respectively:
#Override
protected WebServiceResult doInBackground(Void... v) {
WebServiceResult _ret;
SoapSerializationEnvelope soapEnvelope= new SoapSerializationEnvelope(SoapEnvelope.VER11);
soapEnvelope.dotNet=true;
soapEnvelope.setAddAdornments(false);
soapEnvelope.setOutputSoapObject(soapRequest);
HttpTransportSE conn = new HttpTransportSE(str_URL);
conn.setXmlVersionTag("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
conn.debug = true;
try {
conn.call(str_ACTION, soapEnvelope);
SoapObject o = (SoapObject)soapEnvelope.getResponse();
_ret = new WebServiceResult(o, WebServiceResultEnum.ok);
} catch (NetworkOnMainThreadException e) {
_ret = new WebServiceResult(null, WebServiceResultEnum.keskeytys);
} catch (HttpResponseException e) {
_ret = new WebServiceResult(null, WebServiceResultEnum.httpVirhe);
} catch (XmlPullParserException e) {
_ret = new WebServiceResult(null, WebServiceResultEnum.vaara_muoto);
} catch (SocketTimeoutException e) {
_ret = new WebServiceResult(null, WebServiceResultEnum.aikakatkaisu);
} catch (Exception e) {
_ret = new WebServiceResult(null, WebServiceResultEnum.keskeytys);
}
return _ret;
}
Thank you in advance!
Is it possible you are doing something like this:
YourAsyncTask task = new YourAsyncTask();
WebServiceResult result = task.doInBackground();
Because that would be wrong, completely wrong. If you call doInBackground() directly it will run in the same Thread and not in a new one. You need to start the AsyncTask with execute() like this:
YourAsyncTask task = new YourAsyncTask();
task.execute();
You need to implement the AsyncTask like this:
public class ExampleTask extends AsyncTask<Void, Void, WebServiceResult> {
public interface FinishedListener {
public void onFinished(WebServiceResult result);
}
private final FinishedListener finishedListener;
public ExampleTask(FinishedListener listener) {
this.finishedListener = listener;
}
#Override
protected WebServiceResult doInBackground(Void... params) {
WebServiceResult result = ...;
return result;
}
#Override
protected void onPostExecute(WebServiceResult result) {
super.onPostExecute(result);
if(this.finishedListener != null) {
this.finishedListener.onFinished(result);
}
}
}
And if you implemented it that way you can use it like this:
ExampleTask task = new ExampleTask(new ExampleTask.FinishedListener() {
#Override
public void onFinished(WebServiceResult result) {
// This will be called if the task has finished
}
});
task.execute();
It seems that I had declared the minimum SDK as 14 and target SDK as 17 in AndroidManifest.xml. I didn't use any fancy things in newer sdk's so i lowered the target SDK to the same level as minimum SDK, 14. I also had an Avast! Antivirus service running on the tablet which i removed.
This solved my problem. It could be that probably the Avast! antivirus-program wanted to block all communications from applications not downloaded from Play-store. I don't know if changing the target SDK had much effect really.
Well, I had the same question as you. When it goes to the method transport.call, it pauses, and for a while, it throws a timeout problem. At first, I thought maybe the network was poor, but the server logcat shows it is not the problem. The request was fine and the response was good. My business process is like below:
First, I get a list from the server through ksoap inner a child thread, then cycle the list, send a ksoap request based on every item of the list. It means it will send another list.size() request. When debugging in a real device the above problems occured. I solved it by starting a new child thread after getting the list and making all the list.size requests in the new child thread. So, ksoap use in android may cause thread block which leads to ioexception. So when you put it in a new thread, it escapes from the parent catch exception and works fine.

How to connect to URL WITHOUT opening browser or using browserfield in Blackberry

I am trying to send information to my company's server. Basically when I enter a URL pointing to it and connect to it in a browser, it takes parameters contained in the URL and puts them in a database. Again when done in a browser, it works. However, I would like to be able to send this information every time an event of importance (like scanning a qr code in our app) happens, and I want it to be done in the background (without the user knowing.)
We have tried ConnectionFactory, HTTPRequests etc etc, nothing has worked for us so far.
I am sure there is a simple way to go about this.
Can anyone provide us with the few elusive lines of code to help us do what we want to do??
Thanks alot!
Edit:
Okay here is some code we tried using (one of many code snippets) but it did not work:
public class ConnectionThread extends Thread{
String URL;
public ConnectionThread(String URL) {
this.URL = URL;
}
public void run() {
ServerCalls sc = new ServerCalls(); // This is for generating the URL
ConnectionFactory connFact = new ConnectionFactory();
ConnectionDescriptor connDesc;
connDesc = connFact.getConnection(sc.fillParameters(URL));
if (connDesc != null)
{
HttpConnection httpConn;
httpConn = (HttpConnection)connDesc.getConnection();
}
}
}
and we call
new ConnectionThread(barcode).start()
when we need it to send the info to the server.
For opening the url you can use
javax.microedition.io.HttpConnection Package.
And here is the code how to go about that....
HttpConnection connection=(HttpConnection) Connector.open(your url+";deviceside=true");
if(connection.getResponseCode()==HttpConnection.HTTP_OK) {
write your code, Which you want to get from url or any thing you want
}else{
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Dialog.inform("connection error");
}
});
}
This may help you :)

Download multiple files using a Service in android

My application has a lot of optional data that can be downloaded so I decided to use a Service to handle all the downloads in the background, So I started learning it and here is where i got:
public class DownloadService extends IntentService{
public DownloadService() {
super("DownloadService");
}
#Override
protected void onHandleIntent(Intent intent) {
String URL=intent.getStringExtra("DownloadService_URL");
String FileName=intent.getStringExtra("DownloadService_FILENAME");
String Path=intent.getStringExtra("DownloadService_PATH");
try{
URL url = new URL(URL);
URLConnection conexion = url.openConnection();
conexion.connect();
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(Path+FileName);
byte data[] = new byte[1024];
int count = 0;
while ((count = input.read(data)) != -1) {
output.write(data);
}
output.flush();
output.close();
input.close();
}
catch(Exception e){ }
}
}
The code from the main activity:
Intent ServiceIntent = new Intent(this,DownloadService.class);
ServiceIntent.putExtra("DownloadService_URL", "the url...");
ServiceIntent.putExtra("DownloadService_FILENAME", "Test1.rar");
ServiceIntent.putExtra("DownloadService_PATH", "/sdcard/test/");
startService(ServiceIntent);
Is the code used to download the files correct? Am I using the Service correctly?
I want to download a lot of files.. So should I startService for each different URL?
I would like to inform the user of the percentage done.. But the Service doesnt have a UI. Should I do that in the notification bar?
Thanks.
Is the code used to download the files correct?
I don't like the use of concatenation to create fully-qualified file paths (use the appropriate File constructor). Catching exceptions and not doing anything with them is a really bad idea. On Android 2.3 and higher, you should consider using DownloadManager.
Otherwise, it's probably OK for basic stuff.
I want to download a lot of files.. So should I startService for each different URL?
That should work fine. Note that they will be downloaded one at a time, as IntentService has only one background thread.
I would like to inform the user of the percentage done.. But the Service doesnt have a UI. Should I do that in the notification bar?
That would be one solution. A variation on that would be to have the service send an ordered broadcast, to be picked up by your activity if it is still on-screen or by a BroadcastReceiver that would do the Notification. Here is a blog post with more on that, and here is a tiny sample application demonstrating the concept.

Android 2.2 readUTF() Socket Problem

I am trying to create a Java Client-Server Program, where the Server is running on a Windows PC, and the Client is running on an Android 2.2 Phone.
The Connection is okay. Sending Data from the Phone to the PC works also fine.
Just receiving Data on the Phone crashes the program.
I am using DataInputStream and DataOutputStream to read/write through the Socket.
//Thread on the Phone
public void run() {
while (RUN) {
if (socket != null && socket.isConnected()) {
try {
//Crash
String text = dis.readUTF();
myTextView.setText(text);
} catch (IOException ex) {
//ErrorHandling
}
}
}
}
I want to receive a String from the server and then show it in a TextView.
Any Ideas? I am already setting this permission:
<uses-permission android:name="android.permission.INTERNET" />
do i need any other permissions? Thanks.
you can't set text on your UI if you're not in the UI thread.
do this...
add:
Runnable showmessage = new Runnable() {
public void run() {
myTextView.setText(membervariabletext);
}
};
and from your thread, after the readUTF(), call "runOnUiThread(showmessage);"
I would ensure that your Data Input Stream is initiated correctly:
Socket s = new Socket(serverAddress, port);
DataInputStream dis = new DataInputStream(s.getInputStream());
Otherwise, here's a link for example code where someone uses InputStreamReader() and OutputStreamWriter() to make a server and client for Android.
https://thinkandroid.wordpress.com/2010/03/27/incorporating-socket-programming-into-your-applications/

Categories

Resources