java.io.filenotfound android exception on web service call - android

I am getting exception java.io.filenotfound android exception on web service call in android.But when I run the same url in my browser it works fine.I am communication with the project running on local host in visual studio. My url is like this:
http://10.0.2.2:7378/HighriseeSite/appservices.svc/savewc?WcID=3646&WODetailID=480982&PSID=2084&wcdate=07/14/2015 &wcompleted=1&remarks=&rabill=0&connectivityID=0&length=0&breadth=0&height=0&execby=0
When I use the same url in my browser by replacing 10.0.2.2 with the localhost it works fine webservice gets called.But when the same url is called from the android studio project I get the exception:
java.io.filenotfound
and in the visual studio where project is running and from where the webservice is being called I get the exception as:
Object reference not set to an instance of an object.
But the same url works fine in the browser.I am not able to detect what is wrong with this.Any kind of help will be appreciated.
My code for accessing webservice is like this:
for( WCompletionData Itm:lstWC)
{
if(Float.parseFloat (Itm.getCompQty())>0.0)
{
ur = "http://" + ServerDetails.hostServer + "/appservices.svc/savewc?WcID=" + Itm.getWO_No().trim() + "&WODetailID=" + Itm.getWODetail_Id().trim() + "&PSID=" + Itm.getPS_Id().trim() + "&wcdate=" + currentDateTimeString.trim().trim() + " &wcompleted=" + Itm.getCompQty().trim() + "&remarks=&rabill=" + Itm.getRABill_Id().trim() + "&connectivityID=0&length=0&breadth=0&height=0&execby=0";
//String ur = "http://"+ServerDetails.hostServer+"/appservices.svc/TaskQuanityList?MaterialID="+MatrID+"&ProjectNo="+ProID+"&TaskNo="+TaskID;
Log.d("URLgggrn", ur);
// Replace it with your own WCF service path
URL json = new URL(ur);
URLConnection jc = json.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(jc.getInputStream()));
line = reader.readLine().toString();
Log.d("Line", line);
WCNo = WCNo + line + ",";
}
I am using same code on another activity and it works fine on that activity.

To get rid of File Not Found Exception while requesting to a URL
from android we should avoid white space from URL. If you need to pass
parameter data which contain space you have to use below code
String param1 = "happy coding";
String url = "http://example.com/query?q=" + URLEncoder.encode(param1 , "UTF-8");

Related

How to post data for WebView android

I need to post data to Webview.
I found from some of the links the below code:
WebView webview = new WebView(this);
setContentView(webview);
String url = "http://www.example.com";
String postData = username=my_username&password=my_password";
webview.postUrl(url",EncodingUtils.getBytes(postData, "BASE64"));
But in my android studio I see EncodingUtils as deprecated
Can anyone help me what is the alternative for EncodingUtils to post data to Android WebView?
Try like below...
Java:
WebView webview = new WebView(this);
setContentView(webview);
String url = "http://www.example.com";
String postData = "username=" + URLEncoder.encode(my_username, "UTF-8") + "&password=" + URLEncoder.encode(my_password, "UTF-8");
webview.postUrl(url,postData.getBytes());
Kotlin:
val webview = WebView(this)
setContentView(webview)
val url = "http://www.example.com"
val postData = "username=${URLEncoder.encode(my_username, "UTF-8")}" +
"&password=${URLEncoder.encode(my_password, "UTF-8")}"
webview.postUrl(url, postData.toByteArray())
This is a simple workaround.
String html = "<!DOCTYPE html>" +
"<html>" +
"<body onload='document.frm1.submit()'>" +
"<form action='http://www.yoursite.com/postreceiver' method='post' name='frm1'>" +
" <input type='hidden' name='foo' value='12345'><br>" +
" <input type='hidden' name='bar' value='23456'><br>" +
"</form>" +
"</body>" +
"</html>";
webview.loadData(html, "text/html", "UTF-8");
I know this is not the best method but this works.
I would like to add a few things to the answer as I had to work on same and found some info could help complete the answer to this question.
First thing is the need for such a scenario. My need was that I am
creating a payment gateway client for native applications in android.
Second thing is that the URL you are opening needs to perform some
operations right. Hence you must enable your webView to enable
such operations or else things might not work. For example if your
URL is executing some java script, than you must enable java script
for your webview. This can be done as shown below :
val set = webview.settings
set.javaScriptEnabled = true
Normally this will enable trivial things such as timers, returning results etc on your webview.
Third thing is a case when your webView needs to call methods of your android app. This can be done by adding some JavaScript Interface as shown below :
webview.addJavascriptInterface(WebAppInterface(), "Android")
Where WebAppInterface() is a simple class which atleast one method annotated with #JavascriptInterface as shown below :
class WebAppInterface() {
#JavascriptInterface
fun showToast(status: String) {
//show toast here or handle status
}
}
The name Android will be the one which will be injected into your URL as a variable and you can call the methods of your android WebAppInterace from that URL as shown below:
Android.showToast("From WebPage")
Last thing is your postURL method which is somewhat like :
webview.postUrl(actionUrl, params.toByteArray(Charsets.UTF_8))
This method has couple of things that it takes as default. First is that request type is taken as default POST as the name suggest.
Header content-type can be default taken as application/x-www-form-urlencoded and
most important params it takes as & separated key value pairs as shown :
val params = "MERCHANT_ADDR=" + addr + "&CHANNEL=android"
We must pass byteArray of this string which is shown in post URL callback.
Now after your API is hit and it in some cases loads a callback url, from that call back URL using the JavaScript Interface, you can return result to your application and close the webview.
I hope it helps people.
try this:
You need to URL-encode the parameter value before sending it.
String postData = "fileContents=" + URLEncoder.encode(fileCon, "UTF-8");
For those who came here by trying to put a html body as a postData and not working,
try to put your string body as something below:
val htmlCode = "https://ramdom.user.me"
val postData = "{\n" +
"\t\"token\": \"963966f649\"\n" + "}"
webview.postUrl(htmlCode, postData.toByteArray())
I hope to save someone`s life. :-)

Selenium File Upload iOS or Android using BrowserStack

Is there any possibility to upload a file on mobile browser (Safari on iOS, Chrome on Android)? Conventional methods doesn't seem to work. Maybe there are similar options to BrowserStack where file upload can actually work?
BrowserStack uses Appium to drive your Selenium tests on Android and iOS.
As given here, since Appium currently does not support uploads, BrowserStack too wouldn't be able to support File Upload on mobile devices.
This is a hacky file upload solution using base64 and JS, but it works, so hey, I hope you find this useful:
public CorePage UploadHack(string fileInputId, string contentType, string fileContent, string fileName, string angularScopeVar)
{
UploadFile(_filePath);
var uploadHack =
"(function(){" +
"function convert(base64){" +
"var raw = atob(base64);" +
"var arr = new Uint8Array(new ArrayBuffer(raw.length));" +
"for (var i = 0; i < raw.length; i++){" +
"arr[i] = raw.charCodeAt(i);" +
"}" +
"return arr; " +
"}" +
$"var file = new Blob([convert('{fileContent}')], {{'type':'{contentType}'}}); " +
$"file.name = '{fileName}'; " +
$"angular.element('#{fileInputId}').scope().{angularScopeVar} = file;" +
"})()";
Driver.ExecuteJavaScript(uploadHack);
return this;
}

Problems with asp HttpResponse on a download from Android

I have the following problem:
I develop a .zip file download with .pdf selected inside a function on c#.
The function creates the .zip file on a temp folder on the server and the HTTP Response return this file.
This function works great when is called from windows, and IOS. But when I call this function on Android it never downloads the file.
On the server I see that the function create the .zip file again and again when it's called from android browser (chrome, dolphin...) and it's never returned.
The strange thing is that I could run it well when I selected 90 .pdf files (although the function is called twice for no reason), but when I select 140 (or more) the issue happens again.
Here is the code:
**string dirName = Utiles.GetNewName();
zipName += ".ZIP\"";
string urlRet = _mSTempPath + #"\" + dirName + ".ZIP";
string urlDelete = _mSTempPath + #"\" + dirName;
System.IO.Stream iStream = null;
// Total bytes to read:
long dataToRead;
//HttpResponse resp = _page.Response;
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.ClearHeaders();
using (ZipFile zip = new ZipFile())
{
foreach (string url in filesURLs)
{
zip.AddFile(url,"");
}
zip.Save(_mSTempPath + #"\" + dirName + ".ZIP");
}
// Open the file.
iStream = new System.IO.FileStream(urlRet, System.IO.FileMode.Open,
System.IO.FileAccess.Read, System.IO.FileShare.Read);
// Total bytes to read:
dataToRead = iStream.Length;
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=\"" + zipName);
HttpContext.Current.Response.ContentType = "application/octet-stream";
HttpContext.Current.Response.AddHeader("content-length", dataToRead.ToString());
HttpContext.Current.Response.BufferOutput = true;
HttpContext.Current.Response.TransmitFile(urlRet);
HttpContext.Current.Response.Flush();**
Please, I will be very grateful if anyone can help.
Thanks again!

pass two parameters with URL link in android

i have problem with two parameters passing with URL link. Can anyone help me?
private void FillDetails(String _userid,int _sporttype) {
al_TeamName=new ArrayList<String>();
try{
spf=SAXParserFactory.newInstance();
sp=spf.newSAXParser();
xr=sp.getXMLReader();
URL sourceUrl = new URL(
"http://10.0.2.2:2291/acd.asmx/Get_Teams?_userid ="+_userid & "_sporttype="+ _sporttype);
MyHandler mh=new MyHandler();
xr.setContentHandler(mh);
xr.parse(new InputSource(sourceUrl.openStream()));
setListAdapter(new MyAdapter());
}
catch(Exception ex)
{
}
}
when i using this code, i am getting null.If i send single parameter then it works fine.
Is this correct procedure for URL passing two parameters?
Thanks in advance..........
UPDATED ANSWER:
Now you have multiple errors in your URL:
URL sourceUrl = new URL("http://10.0.2.2:2291/acd.asmx/Get_Teams?_userid =" +
_userid & "_sporttype="+ _sporttype);
You still have a space before the first = sign
There's no + between the _userid variable and the rest of the string.
The & sign is outside the second string
It should be something like this:
URL sourceUrl = new URL("http://10.0.2.2:2291/acd.asmx/Get_Teams?_userid="
+ _userid + "&_sporttype=" + _sporttype);
ORIGINAL ANSWER:
You currently have a space instead of a = sign after your first parameter:
?_userid "+_userid
should be
?_userid="+_userid
Solved.
URL sourceUrl = new URL("http://0.0.0.0/acd.asmx/GetList?Value1="+Value1+"&ID="+ID);
"http://10.0.2.2:2291/acd.asmx/Get_Teams?_userid ="+_userid & "_sporttype="+ _sporttype);
You have an & after _userid, which probably does who knows what on _userid. Usually a single & does binary manipulation, so you might be transforming what comes out of _userid. Also, I would recommend URLEncoding your REST tags if you aren't doing that already
I would recommend logging the REST parameters while in development as well to double-check that it's being formed correctly
Update: The & was outside the quote and you needed to use a +
"http://10.0.2.2:2291/acd.asmx/Get_Teams?_userid ="+_userid + "&_sporttype="+ _sporttype);
If you came here because you searched for a version working in Kotlin (like me), you can use this function to build your URL:
import java.net.URL
// Your URL you want to append the query on
val url: String = "http://10.0.2.2:2291/acd.asmx/Get_Teams"
// The parameters you want to pass
val params: Map<String, String> = mapOf(
"_userid" to _user_id
, "_sporttype" to _sporttype
)
// The final build url. Standard encoding for URL is already utf-8
val final_url: URL = URL(
"$url?" // Don't forget the question-mark!
+ params.map {
"${it.key}=${it.value}"
}.joinToString("&")
)

Using image URL which has dashes in it

I'm trying to download images from a website and my code is working fine in most cases, but I can't download from this URL http://www.liveandlocal.org.uk/images/ShowPics/Steiny’s%20Blues%20-%20Such%20Sweet%20Thunder.jpg
The difference between this and the other URLs is that this one has a dash. I'm fairly certain this is the problem. Is there a way around this?
My error is java.io.filenotfoundexception
My initial code was:
imgLink = "http://www.liveandlocal.org.uk/images/ShowPics/" + Show + ".jpg";
imgLink = imgLink.replace(" ", "%20");
This gave me links like: http://www.liveandlocal.org.uk/images/ShowPics/The%20Atlantics.jpg
which works, but this didn't work for the link I posted at the top.
So now I've tried:
try {
Show = URLEncoder.encode(Show, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
imgLink = "http://www.liveandlocal.org.uk/images/ShowPics/" + Show + ".jpg";
Which doesnt work for any of my links, such as http://www.liveandlocal.org.uk/images/ShowPics/The+Atlantics.jpg
If you copy and paste the link at the start of this post into your browser it will work, so it is just not working on Android.
imgLink = "http://www.liveandlocal.org.uk/images/ShowPics/Steiny%E2%80%99s%20Blues%20-%20Such%20Sweet%20Thunder.jpg"
working fine for me, tested it, replace the characters thus accordingly and '.
- is fine.
Your url contains letters which are not suited for urls (' in this case).
You can encode your url as the following:
String encodedUrl = URLEncoder.encode(normalUrl, "UTF-8");
URLEncoder

Categories

Resources