I am constructing String in my android app and then pass it to URLEncoder.
String searchStr;
// then I get some searchStr from shared preferences
// i check it is correct
searchStr = searchStr + "/page/"+pageNumber+"";
Then I pass that searchStr to URL encoder:
try {
String url_params = URLEncoder.encode(params[0]);
String result = downloadURL("some url/" + url_params);
Log.d("key", url_params); // -> php/page/10
}catch (IOException){
Log.d("key", e.getMessage() );
}
So here i get IOException which shows me this message:
http://some url/php%2Fpage%2F10
If I copy paste it to browser it shows me Not found error with this message:
The requested url someurl/php/page/10 was not found on this server
Also if I change those strange sign %2F into / in browser I am able to get the page. So how can I construct proper string with / instead of %2F sign?
You don't encode the entire URL, only parts of it that come from "unreliable sources".
String query = URLEncoder.encode("apples oranges", "utf-8");
String url = "http://stackoverflow.com/search?q=" + query;
Related
For each request to server in my android app I need to encode parameters, so my string for URL is looks like
"http://example.com/script.php?param1="+URLEncoder.encode(param1.getText().toString(), "UTF-8")+"param2="+URLEncoder.encode(param2.getText().toString(), "UTF-8")+...."
It works but maybe it is possible to use URLEncoder.encode only one time - like this
URLEncoder.encode("http://example.com/script.php?param1="+param1.getText().toString()+"param2="+param2.getText().toString()+....", "UTF-8")
Would it be ok or there are some cases when it can crash?
URL encoding the whole URL will not work, because it would result in something like
"http%3A%2F%2Fexample.com%2Fscript.php%3Fparam1%3Dasdf%26param2%3Djkl"
i.e. all the special characters in the whole URL would be encoded. You also can not url encode the whole query string, because the = and & characters would be encoded.
You have to encode each parameter value to stop special characters in the parameter interfering with the URL parsing. A helper function may reduce the pain.
String url = "http://example.com/script.php?" + encodeArgs("a", "a + b", "b", "=xxx=");
and something to get you started
public String encodeArgs(String... args) {
final String encoding = "UTF-8";
try {
if (args.length % 2 != 0) {
throw new IllegalArgumentException("number of arguments not even");
}
StringBuffer sb = new StringBuffer();
for (int i = 0; i < args.length; i += 2) {
sb.append(URLEncoder.encode(args[i], encoding));
sb.append("=");
sb.append(URLEncoder.encode(args[i + 1], encoding));
sb.append("&");
}
// delete last &, if any
if (sb.length() > 0) {
sb.deleteCharAt(sb.length() - 1);
}
return sb.toString();
} catch (UnsupportedEncodingException e) {
throw new IllegalArgumentException("unsupported encoding " + encoding, e);
}
}
You should not encode complete URL. Encode only param section or in other words, only parts of it that come from "unreliable sources".
So your 1st attempt "http://example.com/script.php?param1="+URLEncoder.encode(param1.getText().toString(), "UTF-8")+"param2="+URLEncoder.encode(param2.getText().toString(), "UTF-8")+...." is correct, and you should continue with it.
URL encoding in Android and Android: howto parse URL String with spaces to URI object? can be useful for more clarity.
I am working on an app that gets a URL link from the user via edit text widget. How can I check if a given URL has a protocol? And if it doesn't, how can I add the correct protocol for the specific URL?
For example if the user entered: google.com
how can I make it become: https://google.com
The main problem is knowing the correct URL protocol for a given address (is it http/https/ftp? and so on).
You can use String.startsWith() to check if the url String starts with http:// or not
public String valid_url(final String url)
{
if (!url.startsWith("http://") && !url.startsWith("https://"))
{
return "http://" + url;
}
return url;
}
first check if url has protocol using .contains() method
and get protocol using .indexof() and .substring() method
string url = editText.getText().toString();
string protocol;
if(url.contains("://")){
//url has a protocol
int index = url.indexof("://");
//get protocol
protocol = url.substring(0,index-1);
}else{
//url does not have a protocal
// add your protocol to begining of the url
}
You can use android web kit URLUTIL class
package android.webkit;
URLUtil.guessUrl("your web address/String")
example scenarios:
www.testurl.com
testurl.com
testurl
result:
http://www.testurl.com/
Just compare the your output string with .contains() property
String value = editText.getText().toString();
if(!value.contains("https://")) {
// add https:// to ur string
}else {
// No need to add
}
This solution worked for me:
if(!url.startsWith("www.")&& !url.startsWith("http://") && !url.startsWith("https://")){
url = "www."+url;
}
if(!url.startsWith("http://") && !url.startsWith("https://")){
url = "http://"+url;
}
Hope this will help you.
As already adviced use the URL class of the SDK.
Here an example:
var urlWithScheme = new URL("https://www.google.com");
var urlWithoutScheme = new URL("www.google.com");
if (urlWithScheme.getProtocol() != null && urlWithScheme.getProtocol().length() > 0) {
System.out.println("Given URL includes scheme: " + urlWithScheme.getProtocol());
}
if (urlWithoutScheme.getProtocol() != null && urlWithoutScheme.getProtocol().length() > 0) {
System.out.println("Given URL includes scheme: " + urlWithoutScheme.getProtocol());
} else {
System.out.println("Url has no Protocol and you can't guess it by the domain name, because under this name all possible services can exist!");
}
If the given URL has not protocoll you can't guess it. Because under a domain name there can exist any protocol specific service in parrallel.
I would narrow it down to only support http and https. For this you could write a test like connect to https url, if success use it, because https is prefered. If you get redirect or not connection try http ;)
In my Android project I'm using Robospice with spring-android. Which works fine for all REST communication. But for the below request query parameter "=" is getting converted to "&". Because of this the request is getting failed.
Query String: tags=["keywords:default=hello"]
By checking the logs the request is converted as below for making call by the library.
http://XXX/rest/media/search?token=123&tags=%5B%22keywords:default&hello%22%5D
here "=" sign is converted to "&" in "keywords:default=hello"
Request Class
here tags = String.format("[\"keywords:default=%s\"]", mTag);
#Override
public MVMediaSearch loadDataFromNetwork() throws Exception
{
String search="";
if(!tags.equals(Constants.EMPTY_DATA))
search="&tags="+tags;
return getRestTemplate().getForObject( Constants.BASE_URL+"/media/search?token="+token+search, MVMediaSearch.class );
}
If I fire the URL in a browser, I'm getting error. And if I change the '&' sign to its corresponding url encoded value in browser, it works fine.
I also have the same issue.
For alternative, I use getForObject(java.net.URI, java.lang.Class).
URI uri = new URI(Constants.BASE_URL+"/media/search?token="+token+search);
getRestTemplate().getForObject(uri, MVMediaSearch.class );
http://docs.spring.io/spring/docs/3.0.x/javadoc-api/org/springframework/web/client/RestTemplate.html#getForObject(java.net.URI, java.lang.Class)
You can do something like this:
URI uri = new URI(
"http",
Constants.BASE_URL,
"/media/search?token=",
token,
search,
null);
String request = uri.toASCIIString();
take a look at THIS and see if you understand (you have to adapt to your code - this is not completely done for you)
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!
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("&")
)