When I try to shorten a link with "#,&" character I get an exception. Is there a way to handle these character properly?
This is a sample code that works:
String shortUrl = bitly.getShortUrl("http://z"); //Works
If I add for example '&' or '%25' to the string it will throw an exception:
String shortUrl = bitly.getShortUrl("http://z%26"); // Exception
String shortUrl = bitly.getShortUrl("http://z&"); // Exception
The getShortUrl function from this Java class.
Thanks
That library (the Java class you link to) doesn't escape the URL... that's pretty awful.
Excerpt:
private String getBitlyHttpResponseText(String urlToShorten) throws IOException {
String uri = getBitlyUrl() + urlToShorten + bitlyAuth;
HttpGet httpGet = new HttpGet(uri);
...
Notice how urlToShorten isn't escaped in any way, shape or form. Prone to injection-style attacks, and just generally doesn't work.
Anyway, you'll need to escape urlToShorten.
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 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;
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 would like to store some strings in a simple .txt file and then read them, but when I want to encode them using Base64 it doesn't work anymore: it writes well but the reading doesn't work. ^^
The write method:
private void write() throws IOException {
String fileName = "/mnt/sdcard/test.txt";
File myFile = new File(fileName);
BufferedWriter bW = new BufferedWriter(new FileWriter(myFile, true));
// Write the string to the file
String test = "http://google.fr";
test = Base64.encodeToString(test.getBytes(), Base64.DEFAULT);
bW.write("here it comes");
bW.write(";");
bW.write(test);
bW.write(";");
bW.write("done");
bW.write("\r\n");
// save and close
bW.flush();
bW.close();
}
The read method :
private void read() throws IOException {
String fileName = "/mnt/sdcard/test.txt";
File myFile = new File(fileName);
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader inBuff = new BufferedReader(new InputStreamReader(fIn));
String line = inBuff.readLine();
int i = 0;
ArrayList<List<String>> matrice_full = new ArrayList<List<String>>();
while (line != null) {
matrice_full.add(new ArrayList<String>());
String[] tokens = line.split(";");
String decode = tokens[1];
decode = new String(Base64.decode(decode, Base64.DEFAULT));
matrice_full.get(i).add(tokens[0]);
matrice_full.get(i).add(tokens[1]);
matrice_full.get(i).add(tokens[2]);
line = inBuff.readLine();
i++;
}
inBuff.close();
}
Any ideas why?
You have a couple of errors in your code.
First a couple of notes on your code:
When posting here, attaching a SSCCE helps others to debug your code. This is not a SSCEE because it doesn't compile. It lacks several defined variables, so one must guess what you really mean. Also you have pasted close-comment token in your code: */ but there is no one start-comment token.
Catching and just suppressing exceptions (like in catch-block in read method) is really bad idea unless you really know what you're doing. What it does most of the time is hide the potential problems from you. At least write the stacktrace of an exception is a catch block.
Why don't you just debug it, check what exactly outputs to the destination file? You should learn how to do that because that will speed up your development process, especially for larger projects with hard-to-catch problems.
Back to the solution:
Run the program. It throws an exception:
02-01 17:18:58.171: E/AndroidRuntime(24417): Caused by: java.lang.ArrayIndexOutOfBoundsException
caused by line here:
matrice_full.get(i).add(tokens[2]);
inspecting the variable tokens reveals that it has 2 elements, not 3.
So lets open the file generated by the write method. Doing that shows this output:
here it comes;aHR0cDovL2dvb2dsZS5mcg==
;done
here it comes;aHR0cDovL2dvb2dsZS5mcg==
;done
here it comes;aHR0cDovL2dvb2dsZS5mcg==
;done
Note line breaking here. This is because the Base64.encodeToString() appends additional newline at the end of the encoded string. To generate a one single line, without extra newlines, add Base64.NO_WRAP as the second parameter like this:
test = Base64.encodeToString(test.getBytes(), Base64.NO_WRAP);
Note here, you must delete file that was created earlier as it has improper line breaking.
Run the code again. It now creates a file with the proper contents:
here it comes;aHR0cDovL2dvb2dsZS5mcg==;done
here it comes;aHR0cDovL2dvb2dsZS5mcg==;done
Printing the output of matrice_full now gives:
[
[here it comes, aHR0cDovL2dvb2dsZS5mcg==, done],
[here it comes, aHR0cDovL2dvb2dsZS5mcg==, done]
]
Note that you're not doing anything with the value in decode variable in your code, hence the second element is the Base64 representation of that value which is read from the file.
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("&")
)