how to parse url in android - java

I have an URL that should parse the value but when I give
private static String url = "http://54.174.74.84/api/index/index?data={%20%22language_code%22:%22en_us%22,%20%22cmd%22:%22search_projects%22,%20%22user_device_id%22:319,%20%22page%22:0,%20%22user_token%22:%22edeN2y0EuakoD2deWGzijeuBQ5HRnhokyAqV4WIHzZz5PM0Qn2xgopKiAcboNJktgXeQMsX7kZmDW3T5Tta3i+Fz1mU5p1yTP1L3m\/OTGkOlDoJrLn6\/+I3rBqESDtFH%22,%20%22source_app%22:%22android%22,%20%22longitude%22:%22567%22,%20%22user_id%22:67,%20%22latitude%22:%22123%22,%20%22records_per_page%22:%2210%22,%20%22search_key%22:%22%22%20}";
like this it is showing error. So please help me. Thanks.

This is not an error. Just string encoding with java encoder class. You have to just decode string before using it like below code...
String url = "http://54.174.74.84/api/index/index?data={%20%22language_code%22:%22en_us%22,%20%22cmd%22:%22search_projects%22,%20%22user_device_id%22:319,%20%22page%22:0,%20%22user_token%22:%22edeN2y0EuakoD2deWGzijeuBQ5HRnhokyAqV4WIHzZz5PM0Qn2xgopKiAcboNJktgXeQMsX7kZmDW3T5Tta3i+Fz1mU5p1yTP1L3m/OTGkOlDoJrLn6/+I3rBqESDtFH%22,%20%22source_app%22:%22android%22,%20%22longitude%22:%22567%22,%20%22user_id%22:67,%20%22latitude%22:%22123%22,%20%22records_per_page%22:%2210%22,%20%22search_key%22:%22%22%20}";
String result = java.net.URLDecoder.decode(url, "UTF-8");

You need to use the Uri class:
String uri = Uri.parse("http://54.174.74.84/api/index/index")
.buildUpon()
.appendQueryParameter("data", "{%20%22language_ ..... %22%22%20}")
.appendQueryParameter("param2", value2)
.appendQueryParameter("param3", value3)
.build().toString();

Related

Creating a URL Using Java - What's the Best Practice?

I have an application that is calling a rest service. I need to pass it a URL and right now I'm creating the URL by concatenating a string.
I'm doing it this way:
String urlBase = "http:/api/controller/";
String apiMethod = "buy";
String url = urlBase + apiMethod;
The above is fake obviously, but the point is I'm using simple string concats.
Is this the best practice? I'm relatively new to Java. Should I be building a URL object instead?
Thanks
if you have a base path which needs some additional string to be added to it you have 2 options:
First is, using String.format():
String baseUrl = "http:/api/controller/%s"; // note the %s at the end
String apiMethod = "buy";
String url = String.format(baseUrl, apiMethod);
Or using String.replace():
String baseUrl = "http:/api/controller/{apiMethod}";
String apiMethod = "buy";
String url = baseUrl.replace("\\{apiMethod}", apiMethod);
The nice thing about both answers is, that the string that needs to be inserted, doesn't have to be at the end.
If you are using jersey-client. The following would be the best practice to access the subresources without making the code ugly
Resource: /someApp
Sub-Resource: /someApp/getData
Client client = ClientBuilder.newClient();
WebTarget webTarget = client.target("https://localhost:7777/someApp/").path("getData");
Response response = webTarget.request().header("key", "value").get();
If you are using plain Java, it's better to use dedicated class for URL building which throws exception if provided data are invalid in semantic way.
It has various constructors, you can read about it here.
Example
URL url = new URL(
"http",
"stackoverflow.com",
"/questions/50989746/creating-a-url-using-java-whats-the-best-practive"
);
System.out.println(url);

Building a JSON search parser

I am working with a database api and they give me the opportunity to search using a url through their database.
This is the url =
http://api.database.com/v2/search?q=(THE PRODCUT)&type=(THE TYPE OF PRODUCT)
&key=(myApiKey)
I want to make a simple search bar were the user can type the product name and choose a type (catagorie) to insert that into the url and then look the product up in the database.
I know how I can parse the data from the url but how can I insert the users text into the url to change it ?
It's always a better approach to use URI to build your search url.
Try something like this
final String FORECAST_BASE_URL ="http://api.openweathermap.org/data/2.5/forecast/daily?";
final String QUERY_PARAM = "q";
Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon()
.appendQueryParameter(QUERY_PARAM, params[0])
.build();
URL url = new URL(builtUri.toString());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
And then read the response from the inputStream.
InputStream inputStream = urlConnection.getInputStream();
You can use string concatenation or you can use String.format(String format, Object... args). For example:
String url = String.format("http://api.database.com/v2/search?q=%s&type=%s&key=%", product, productType, apiKey);
or :
var product = "Product";
var productType="ProductType";
var url = "http://api.database.com/v2/search?q="+product+"&type="+productType+"&key="+myApiKey;

Android - getHost() returns null if URL has #

I have some URLs' in string form, and from these URLs' I want to generate a URI using java.net.URI.
These URLs' are actually hyperlinks in an Android Webview:
clc://C# or clc://C++
final URI u = new URI(newURL);
final String sScheme = u.getScheme();
final String sHost = u.getHost();
final String sPath = u.getPath();
But in the above code, if a URL has # or + then getHost() returns null.
I tried to encode the URL as follows, but it doesn't work:
String encodedUrl = URLEncoder.encode(url, "UTF-8");
I also tried putting %23 for #, then too it doesn`t work.
Please help me to resolve this.....
URLEncoder doesn't always provide the correct output, especially when URIs' are involved.
Try the following approach instead:
Uri u = Uri.parse(newURL)
.buildUpon()
.appendQueryParameter("param", param)
.build();
String url = u.toString();
where param is a web service parameter (if using any). This will encode the URL in UTF-8 format correctly. Then,
final String sScheme = u.getScheme( );
final String sHost = u.getHost( );
final String sPath = u.getPath( );
It will work as expected.

URL encoding issue in java

Here is my sample url:
url.com/data?format=json&pro={%22merchanturl%22:%22http://url.com/logo.pn‌​g%22,%22price%22:599,%22productDesc%22:%22Apple%2032GBBlack%22,%22prodID%22:%2291‌​3393%22,%22merchant%22:%224536%22,%22prourl%22:%22http://url.com/data%22,%22name%‌​22:%22Apple%2032GB%20%2D%20Black%22,%22productUrl%22:%22http://www.url.com/image.‌​jpg%22,%22myprice%22:550,%22mercname%22:%22hello%22,%22mybool%22:false}
I have an android app. I need to post this url to server. So that server responds back with a token. I am doing the httppost through app. But I am not getting any response/exception. If I copy the same url and paste it in browser, that works very well. I hope I am doing mistake with the encoding part. Can anyone point out my issue?
Here is my encoding method:
private String encodeString(String input) {
String output = new String(input.trim().replace(" ", "%20")
.replace("&", "%26").replace(",", "%2c").replace("(", "%28")
.replace(")", "%29").replace("!", "%21").replace("=", "%3D")
.replace("<", "%3C").replace(">", "%3E").replace("#", "%23")
.replace("$", "%24").replace("'", "%27").replace("*", "%2A")
.replace("-", "%2D").replace(".", "%2E").replace("/", "%2F")
.replace(":", "%3A").replace(";", "%3B").replace("?", "%3F")
.replace("#", "%40").replace("[", "%5B").replace("\\", "%5C")
.replace("]", "%5D").replace("_", "%5F").replace("`", "%60")
.replace("{", "%7B").replace("|", "%7C").replace("}", "%7D")
.replace("\"", "%22"));
return output;
}
Update:
The reason why I am doing like this is, I need to send the data as in this format. The parameters part of the url is a json data. If I encode the complete url, that is not working.
Try using URLEncoder, encode only the part after ?
String query = URLEncoder.encode(queryPart, "utf-8");
String url = "http://server.com/search?q=" + query;
Although a self-written encoding isn't bad, I recommend using built-in Java methods that have been proven to be working.
TextUtils contains a method htmlEncode(String s) just for this.
http://developer.android.com/reference/android/text/TextUtils.html#htmlEncode%28java.lang.String%29

URL formatting in Java

String arg="http://www.example.com/user.php?id=<URLRequest Method='GetByUID' />";
java.net.URI uri = new java.net.URI( arg );
java.awt.Desktop desktop = java.awt.Desktop.getDesktop();
desktop.browse( uri );
I want to open the given link in default browser with the above code but it says the url is invalid...i tried escaping characters like ' also but its not working.
If i replace String arg="www.google.com"; then there is no problem and I am able to open google.com.
Please help.
Your string contains characters that aren't valid in a URI, per RFC 2396. You need to properly encode the query parameters. Many utilities support that, like the standard URLEncoder (lower level), JAX-RS UriBuilder, Spring UriUtils, Apache HttpClient URLEncodedUtils and so on.
Edit: Oh, and the URI class can handle it, too, but you have to use a different constructor:
URI uri = new URI("http", "foo.com", null, "a=<some garbage>&b= |{$0m3 m0r3 garbage}| &c=imokay", null);
System.out.println(uri);
Outputs:
http://foo.com?a=%3Csome%20garbage%3E&b=%20%7C%7B$0m3%20m0r3%20garbage%7D%7C%20&c=imokay
which, while ugly, is the correct representation.
Thats because it is invalid. <URLRequest Method='GetByUID' /> should be replaced by the value of the id, or an expression that returns the id which you can concatenate with the arg string. Something like
String arg="http://www.example.com/user.php?id="+getByUID(someUid);
import java.net.URL;
import java.net.URLEncoder;
class ARealURL {
public static void main(String[] args) throws Exception {
String s1 = "http://www.example.com/user.php?id=";
String param = "<URLRequest Method='GetByUID' />";
String encodedParam = URLEncoder.encode(param,"UTF-8");
URL url = new URL(s1+encodedParam);
System.out.println(url);
}
}
Output
http://www.example.com/user.php?id=%3CURLRequest+Method%3D%27GetByUID%27+%2F%3E

Categories