How to insert path between absoluteURL and parameter? - android

My url looks like this: https://test.com/test#someParameter
And i want to insert "/site" between the url and the parameter without string operations, because using string operations on urls are not best practise.
The final url should look like this: https://test.com/test/site#someParameter
I tried using .apply but it didn't work:
URI(url).apply { path += "/site" }.toString()

I believe that a safe way to do it is using urllib
import urllib
args = {"site": "site", "param": "some_parameter"}
url = "https://test.com/test/{}#{}".format(urllib.urlencode(args))

Related

Retrofit request url prevent urlencode android

I have a retrofit request
#GET("{link}")
suspend fun getFilePart(#Path(value = "link") link: String): Deferred<NetworkResponse<ResponseBody, NetworkError>>
and when i call it i pass a 'link'
val base = if (BuildConfig.DEBUG) BuildConfig.TRANSFER_URL_DEBUG else BuildConfig.TRANSFER_URL
apiManager.appApiService(base).getFilePart(it.link)
Lets say the link is something like "https://storage_dev.example.com/10002/6d197e1e57e37070760c4ae28bf1..." but in the Logcat i see that some characters get urlEncoded.
For example
the following Url
https://storage_dev.example.com/10002/6d197e1e57e37070760c4ae28bf18d813abd35a372b6a1f462e4cef21e505860.1&Somethingelse
turns to
https://storage_dev.example.com/10002/6d197e1e57e37070760c4ae28bf18d813abd35a372b6a1f462e4cef21e505860.1%3FSomethingelse
As i can see the link is a String that has many characters inside that get encoded like "&" has turned to "%3F"
How can i prevent this?
You can add encoded = true to your request param to tell retrofit to not encode it again:
/**
* Specifies whether the parameter {#linkplain #value() name} and value are already URL encoded.
*/
boolean encoded() default false;
Example:
#Path(value = "link", encoded = true)
If your link includes the baseurl part you should use #Url to avoid that problem
#GET
suspend fun getFilePart(#Url link: String): Deferred<NetworkResponse<ResponseBody, NetworkError>>
I think I'm late but however this is how I solved it ..
my issue was the url to containes " so on request url it gets encoded then looks like this domain.com/api/%22SOME_URL_%22
simply just add interceptor to catch the request and decode it.
if(it.request().url().toString().contains("api/MY_SUB_DOMAIN")){
val newUrl = java.net.URLDecoder.decode( it.request().url().toString(),
StandardCharsets.UTF_8.name()) // <--- This is your main solution (decode)
.replace("\"", "") // <---- I had to do this to remove parenthasis "
requestBuilder.url(newUrl) // <--- DONT FORGET TO ASSAIGN THE NEW URL
}

How to make android.net.Uri encode & between query parameters to %26

I have a Android app that needs to launch a web brower with a URL containing a query string. I build my Uri like this:
Uri uri = builder.scheme("https")
.authority("ids.example.com")
.appendPath("account")
.appendPath("login")
.appendQueryParameter("client_id", "seglaren")
.appendQueryParameter("scope", "openid email name")
.build();
and pass it to the browser using:
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
This launches the browser with the following URL:
https://ids.example.com/account/login?client_id=seglaren&scope=openid%20email%20name
The problem here is that the server I am calling does not accept this URL: it requires the separator between the query parameters to be encoded to "%26" instead of just "&". So it would need to be:
https://ids.example.com/account/login?client_id=seglaren%26scope=openid%20email%20name
How do I fix this?
Instead of .appendQueryParameter() you can use .encodedQuery().
encodedQuery() will be treated as if it is already encoded, thus not encoding it again. So you may insert your own string as you wish like in the example below.
String params = "client_id=seglaren%26scope=openid%20email%20name";
Uri uri = new Uri.Builder().scheme("https")
.authority("ids.artdatabanken.se")
.appendPath("account")
.appendPath("login")
.encodedQuery(params)
.build();
You may use string concatenation or a StringBuilder to make the String params dynamic if you don't want to keep it hardcoded.
Result
"https://ids.artdatabanken.se/account/login?client_id=seglaren%26scope=openid%20email%20name"
Note that androids Uri.Builder is doing the correct thing by adding &to the parameter. So the API you're using probably has a bug if it requires %26.

Make url with custom scheme clickable in textview

I have urls with custom schemes that are displayed in a TextView. The problem is that when I try using something like Linkify not the whole text section is clickable. I am following this link to try to get it working but the link is only on google.com
Code copied from link but I am using Kotlin:
val fullString = "This sentence contains a custom://www.google.com custom scheme url"
mTextView.text = fullString
val urlDetect = Pattern.compile("([a-zA-Z0-9]+):\\/\\/([a-zA-Z0-9.]+)") // this is a terrible regex, don't use it. There are better url regexs.
val matcher = urlDetect.matcher(fullString)
var scheme: String? = null
while (matcher.find()) {
val customSchemedUrl = matcher.group(0)
val uri = Uri.parse(customSchemedUrl)
// Now you could create an intent yourself...
// ...or if you want to rely on Linkify keep going
scheme = uri.getScheme()
break
}
if (!TextUtils.isEmpty(scheme)) {
Linkify.addLinks(mTextView, urlDetect, scheme)
}
the output is: (custom://www.google.com) where only google.com is a link.
maybe a clickable span would be of help here?
https://developer.android.com/reference/android/text/style/ClickableSpan.html

How to convert string json to url format in android

I'm trying to make a slider with this tutorial and it works very good. But when I try to get the image url from JSON with volley this url does not work. I want to convert the string to url, but my code is not working.
img1 = obj.getString("image_1");
URL myURL1 = new URL(img1);
Add app/gradle.app as a dependencies
compile 'com.google.code.gson:gson:2.6.2'
Now you need to create a Object.class according to your Json object. And all key names should same as your Object.class
Eg: Json object:
{
"id": 1,
"message": "This is example"
"url": "http://www.jsoneditoronline.org/"
}
Class object:
public class ExampleObject {
public long id;
public String message;
public String url;
}
Then in your Activity.java:
//jsonObj is your JSON object
ExampleObject obj = new Gson().fromJson(jsonObj, ExampleObject.class);
Now all the values are saved into your Object class.
If you want to load the url of the image retrieved in an imageview you can pass the string to an image processing library, for exemple Glide. Here's a good tutorial on how to set it up and use it: https://futurestud.io/tutorials/glide-getting-started.
The Android SDK contains a very useful Uri class. It exposes a Builder that can be used for property URL building (instead of string concatenation, that you are using). It also has a Uri.parse() method, that can create an instance from a String.

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("&")
)

Categories

Resources