How do I pass multiple parameter in URL? - java

I am trying to figure out how to pass multiple parameters in a URL. I want to pass latitude and longitude from my android class to a java servlet. How can I do that?
URL url;
double lat=touchedPoint.getLatitudeE6() / 1E6;
double lon=touchedPoint.getLongitudeE6() / 1E6;
url = new URL("http://10.0.2.2:8080/HelloServlet/PDRS?param1="+lat+lon);
In this case output (written to file) is 28.53438677.472097.
This is working but I want to pass latitude and longitude in two separate parameters so that my work at server side is reduced. If it is not possible how can I at least add a space between lat & lon so that I can use tokenizer class to get my latitude and longitude. I tried following line but to no avail.
url = new URL("http://10.0.2.2:8080/HelloServlet/PDRS?param1="+lat+" "+lon);
output- Nothing is written to file
url = new URL("http://10.0.2.2:8080/HelloServlet/PDRS?param1="+lat+"&?param2="+lon);
output- 28.534386 (Only Latitude)
url = new URL("http://10.0.2.2:8080/HelloServlet/PDRS?param1="+lat+"?param2="+lon);
output- 28.532577?param2=77.502996
My servlet code is as follows:
req.setCharacterEncoding("UTF-8");
resp.setCharacterEncoding("UTF-8");
final String par1 = req.getParameter("param1");
final String par2 = req.getParameter("param2");
FileWriter fstream = new FileWriter("C:\\Users\\Hitchhiker\\Desktop\\out2.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write(par1);
out.append(par2);
out.close();
Also I wanted to the know is this the most safe and secured way to pass the data from android device to server.

This
url = new URL("http://10.0.2.2:8080/HelloServlet/PDRS?param1="+lat+"&param2="+lon);
must work. For whatever strange reason1, you need ? before the first parameter and & before the following ones.
Using a compound parameter like
url = new URL("http://10.0.2.2:8080/HelloServlet/PDRS?param1="+lat+"_"+lon);
would work, too, but is surely not nice. You can't use a space there as it's prohibited in an URL, but you could encode it as %20 or + (but this is even worse style).
1 Stating that ? separates the path and the parameters and that & separates parameters from each other does not explain anything about the reason. Some RFC says "use ? there and & there", but I can't see why they didn't choose the same character.

I do not know much about Java but URL query arguments should be separated by "&", not "?"
https://www.rfc-editor.org/rfc/rfc3986 is good place for reference using "sub-delim" as keyword. http://en.wikipedia.org/wiki/Query_string is another good source.

You can pass multiple parameters as "?param1=value1&param2=value2"
But it's not secure. It's vulnerable to Cross Site Scripting (XSS) Attack.
Your parameter can be simply replaced with a script.
Have a look at this article and article
You can make it secure by using API of StringEscapeUtils
static String escapeHtml(String str)
Escapes the characters in a String using HTML entities.
Even using https url for security without above precautions is not a good practice.
Have a look at related SE question:
Is URLEncoder.encode(string, "UTF-8") a poor validation?

Related

how to pass pameters with brackets to restemplate

I am connecting to a third party tool that uses brackets inside their url parameters. I'm proxying someone else parameters, so I'm not building these parameters up and don't want to have to parse them exactly.
I've tried a basic encoding of parameters, this fails due to the third party application not knowing how to parse the encoding, it tries to read the encoded values directly as far as I can tell.
I realize this is not exactly how resttemplate is designed to work, but everywhere else in our code uses restTemplate and I don't want to bring in a new service simply for a basic proxy.
Is there any way to make resttemplate allow the brackets through without trying to do substitution on them?
You can use escape URL codes for special characters in the URL. e.g. If your URL is http://domainURL/{url-part}/rest-of-the-url then you could refer to it as http://domainURL/%7Burl-part%7D/rest-of-the-url.
Below is the code snippet for the reference:
LoginDetails loginDetails = restTemplate.getForObject(restServiceURL +
"%7Btest-paranthesis%7D/" + userUUID, LoginDetails.class);
For the above code the URL is http://localhost:8087/userLogin{test-paranthesis}/842063819010

Multiple words not getting searched , not taking space

when i pass string with space in bw the words to the servlet and run the android aaplication
error comes like this
03-01 09:32:41.110: E/Excepiton(1301): java.io.FileNotFoundException: http//address of server:8088/First/MyServlet?ads_title=test test&city=Pune
here ads_title=test test and city = Delhi
but it works fine when i pass single word string
like ads_title=test
and city = Delhi
but when i run query on sql with both the value that works that means query is fine.
String stringURL="http//laddress of server:8088/First/MyServlet" +
String.format("?ads_title=%s&city=%s",editText1.getText(),City);
that is where i am passing the values
Data sent as a URL must be "encoded" to ensure that all the data passes properly to the server to be interpreted correctly. Fortunately, Java provides a standard class URLEncoder and the encoding specified by the World Wide Web Consortium is "UTF-8 so, use
String finalURL = URLEncoder(stringURL,"UTF-8");
(That way you don't have to know what the encoding is for each special character.)
I agree with the comments (not sure why they didn't post as an answer though?) - you want to try encoding your URL - so that the space is handled correctly (%20)
Java URL encoding of query string parameters

Parsing a URL in Java

I am looking for an equivalent to PHP's "parse_url" function in Java. I am not running in Tomcat. I have query strings saved in a database that I'm trying to break apart into individual parameters. I'm working inside of Pentaho, so I only have the Java SE classes to work with. I know I could write a plugin or something, but if I'm going to do all that I'll just write the script in PHP and be done with it.
TLDR: Looking for a Java standard class/function that takes a String and spits out an array of parameters.
Thanks,
Roger
You can accomplish that using java.net.URL:
URL url = new URL("http://hostname:port/path?arg=value#anchor");
String protocol = url.getProtocol(); // http
String host = url.getHost(); // hostname
String path = url.getPath(); // /path
int port = url.getPort(); // port
String query = url.getQuery(); // arg=value
String ref = url.getRef(); // anchor
Here's something quick and dirty (have not compiled it, but you should get the idea.
URL url = new URL("http://...");
String query = url.getQuery();
String paramStrings[] = query.split("\\&");
HashMultiMap<String, String> params = HashMultiMap.create(); // <== google guava class
for (int i=0;iparamStrings.length;i++) {
String parts[] = params[i].split("=");
params.put(URLDecoder.decode(parts[0], "UTF-8"), URLDecoder.decode(parts[1], "UTF-8"));
}
Set<String> paramVals = params.get("paramName");
If you don't want to use the guava class, you can accomplish the same thing with some additional code, and a HashMap>
No such thing in Java. You will need to parse the strings manually and create your own array. You could create your own parse_url using StringTokenizer, String.split, or Regular Expressions rather easily.
You could also cast those strings from the database back to URL objects and parse them that way, here are the docs.
String has a split function, but you will need to write your own regex to determine how to split the string.
See: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String)

How to encode URL to avoid special characters in Java? [duplicate]

This question already has answers here:
HTTP URL Address Encoding in Java
(24 answers)
Closed 5 years ago.
i need java code to encode URL to avoid special characters such as spaces and % and & ...etc
URL construction is tricky because different parts of the URL have different rules for what characters are allowed: for example, the plus sign is reserved in the query component of a URL because it represents a space, but in the path component of the URL, a plus sign has no special meaning and spaces are encoded as "%20".
RFC 2396 explains (in section 2.4.2) that a complete URL is always in its encoded form: you take the strings for the individual components (scheme, authority, path, etc.), encode each according to its own rules, and then combine them into the complete URL string. Trying to build a complete unencoded URL string and then encode it separately leads to subtle bugs, like spaces in the path being incorrectly changed to plus signs (which an RFC-compliant server will interpret as real plus signs, not encoded spaces).
In Java, the correct way to build a URL is with the URI class. Use one of the multi-argument constructors that takes the URL components as separate strings, and it'll escape each component correctly according to that component's rules. The toASCIIString() method gives you a properly-escaped and encoded string that you can send to a server. To decode a URL, construct a URI object using the single-string constructor and then use the accessor methods (such as getPath()) to retrieve the decoded components.
Don't use the URLEncoder class! Despite the name, that class actually does HTML form encoding, not URL encoding. It's not correct to concatenate unencoded strings to make an "unencoded" URL and then pass it through a URLEncoder. Doing so will result in problems (particularly the aforementioned one regarding spaces and plus signs in the path).
I also spent quite some time with this issue, so that's my solution:
String urlString2Decode = "http://www.test.com/äüö/path with blanks/";
String decodedURL = URLDecoder.decode(urlString2Decode, "UTF-8");
URL url = new URL(decodedURL);
URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef());
String decodedURLAsString = uri.toASCIIString();
If you don't want to do it manually use Apache Commons - Codec library. The class you are looking at is: org.apache.commons.codec.net.URLCodec
String final url = "http://www.google.com?...."
String final urlSafe = org.apache.commons.codec.net.URLCodec.encode(url);
Here is my solution which is pretty easy:
Instead of encoding the url itself i encoded the parameters that I was passing because the parameter was user input and the user could input any unexpected string of special characters so this worked for me fine :)
String review="User input"; /*USER INPUT AS STRING THAT WILL BE PASSED AS PARAMTER TO URL*/
try {
review = URLEncoder.encode(review,"utf-8");
review = review.replace(" " , "+");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String URL = "www.test.com/test.php"+"?user_review="+review;
I would echo what Wyzard wrote but add that:
for query parameters, HTML encoding is often exactly what the server is expecting; outside these, it is correct that URLEncoder should not be used
the most recent URI spec is RFC 3986, so you should refer to that as a primary source
I wrote a blog post a while back about this subject: Java: safe character handling and URL building

Escaping & in a URL

I am using jsps and in my url I have a value for a variable like say "L & T". Now when I try to retrieve the value for it by using request.getParameter I get only "L". It recognizes "&" as a separator and thus it is not getting considered as a whole string.
How do I solve this problem?
java.net.URLEncoder.encode("L & T", "utf8")
this outputs the URL-encoded, which is fine as a GET parameter:
L+%26+T
A literal ampersand in a URL should be encoded as: %26
// Your URL
http://www.example.com?a=l&t
// Encoded
http://www.example.com?a=l%26t
You need to "URL encode" the parameters to avoid this problem. The format of the URL query string is:
...?<name>=<value>&<name>=<value>&<etc>
All <name>s and <value>s need to be URL encoded, which basically means transforming all the characters that could be interpreted wrongly (like the &) into %-escaped values. See this page for more information:
http://www.w3schools.com/TAGS/ref_urlencode.asp
If you're generating the problem URL with Java, you use this method:
String str = URLEncoder.encode(input, "UTF-8");
Generating the URL elsewhere (some templates or JS or raw markup), you need to fix the problem at the source.
You can use UriUtils#encode(String source, String encoding) from Spring Web. This utility class also provides means for encoding only some parts of the URL, like UriUtils#encodePath.

Categories

Resources