From the following URL I need to get (http://localhost:9090/dts) alone.
That is I need to remove (documents/savedoc) (OR)
need to get only - (http://localhost:9090/dts)
http://localhost:9090/dts/documents/savedoc
Is there any method available in request to get the above?
I tried the following and got the result. But still trying.
System.out.println("URL****************"+request.getRequestURL().toString());
System.out.println("URI****************"+request.getRequestURI().toString());
System.out.println("ContextPath****************"+request.getContextPath().toString());
URL****************http://localhost:9090/dts/documents/savedoc
URI****************/dts/documents/savedoc
ContextPath****************/dts
Can anyone please help me in fixing this?
You say you want to get exactly:
http://localhost:9090/dts
In your case, the above string consist of:
scheme: http
server host name: localhost
server port: 9090
context path: dts
(More info about the elements of a request path can be found in the official Oracle Java EE Tutorial: Getting Information from Requests)
##First variant:###
String scheme = request.getScheme();
String serverName = request.getServerName();
int serverPort = request.getServerPort();
String contextPath = request.getContextPath(); // includes leading forward slash
String resultPath = scheme + "://" + serverName + ":" + serverPort + contextPath;
System.out.println("Result path: " + resultPath);
##Second variant:##
String scheme = request.getScheme();
String host = request.getHeader("Host"); // includes server name and server port
String contextPath = request.getContextPath(); // includes leading forward slash
String resultPath = scheme + "://" + host + contextPath;
System.out.println("Result path: " + resultPath);
Both variants will give you what you wanted: http://localhost:9090/dts
Of course there are others variants, like others already wrote ...
It's just in your original question you asked about how to get http://localhost:9090/dts, i.e. you want your path to include scheme.
In case you still doesn't need a scheme, the quick way is:
String resultPath = request.getHeader("Host") + request.getContextPath();
And you'll get (in your case): localhost:9090/dts
AFAIK for this there is no API provided method, need to customization.
String serverName = request.getServerName();
int portNumber = request.getServerPort();
String contextPath = request.getContextPath();
// try this
System.out.println(serverName + ":" +portNumber + contextPath );
Just remove URI from URL and then append context path to it. No need to fiddle with loose schemes and ports which is only more tedious when you're dealing with default port 80 which don't need to appear in URL at all.
StringBuffer url = request.getRequestURL();
String uri = request.getRequestURI();
String ctx = request.getContextPath();
String base = url.substring(0, url.length() - uri.length() + ctx.length());
// ...
See also:
Browser can't access/find relative resources like CSS, images and links when calling a Servlet which forwards to a JSP (for the JSP/JSTL variant of composing the base URL)
In my understanding, you need the domain part and Context path only. Based on this understanding, You can use this method to get the required string.
String domain = request.getRequestURL().toString();
String cpath = request.getContextPath().toString();
String tString = domain.subString(0, domain.indexOf(cpath));
tString = tString + cpath;
For those who want to get, in their endpoint, the URL of the front page which targeted the endpoint. You can use this:
request.getHeader("referer")
Usually I have a method like this:
public String getAbsoluteContextPath() throws MalformedURLException {
ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
HttpServletRequest request = (HttpServletRequest) context.getRequest();
URL url = new URL(request.getRequestURL().toString());
return url.getProtocol() + "://" + url.getAuthority() + context.getRequestContextPath();
}
This method will return what you want, with the port number only if it exists in the current request. In your case it will return: http://localhost:9090/dts
Related
I am trying to pass a URL as a path variable, but when I input the URL as a parameter and access the route, it returns an error. I want to be able to see the address after it passes into the route as a parameter.
#RequestMapping("/addAddress/{address}")
public String addAddress(#PathVariable("address") String address) {
System.out.println("Address: "+address)
return address;
}
For example, if I put into the URL:
localhost:8080/addAddress/http://samplewebsite.com
I should see
http://samplewebsite.com
printed out in the back end.
The forward slashes are your issue.
You have a few choices.
Use 2 path variables. This still works with a double forward slash. This works with URL: "localhost:8080/addAddress/http://samplewebsite.com"
#GetMapping("/addAddress/{schema}/{address}")
public String addAddress(#PathVariable("schema") String schema, #PathVariable("address") String address) {
System.out.println("Address: "+ schema + "//" + address);
return schema + "//" + address;
}
Use a query (request) param, your url would then be URL: "localhost:8080/addAddress/?address=http://samplewebsite.com"
#GetMapping("/addAddress2")
public String addAddress2(#RequestParam("address") String address) {
System.out.println("Address: "+address);
return address;
}
Encode the slashes in URL:
localhost:8080/addAddress/http:%2F%2Fsamplewebsite.com"
and configure Tomcat or Jetty, whatever you use to allow encoded slashes. Here is an example in Tomcat
You can do the following;
#RequestMapping("/addAddress/**")
public String addAddress(HttpServletRequest request) {
String fullUrl = request.getRequestURL().toString();
String url = fullUrl.split("/addAddress/")[1];
System.out.println(url);
return url;
}
with #PathVariable that is not doable due to the / char breaking the behaviour you are looking for, unless you encode/decode, but I feel like this is a simpler way to go for both user of the endpoint, and for the backend.
Also this will not fetch the request query part, e.g. ?input=user,
to do that you can add this logic
You can use SafeUrl to parse your URL in your path.
Some documentation:
https://www.urlencoder.io/java/
It let you pass parameters safe by the url and you can decode where you need.
I have a relative url string, know host and protocol. How can I build an absolute url string?
Seems easy? Yes at first look, but until escaped characters coming. I have to build absolute url from 302 code http(s) response Location header.
lets consider an example
protocol: http
host: example.com
location: /path/path?param1=param1Data¶m2= "
First I tried to build url string like:
Sting urlString = protocol+host+location
Constructor of URL class not escapes spaces and double quotes:
new URL(urlString)
Constructors of URI class fail with exception:
new URI(urlString)
URI.resolve method also fails with exception
Then I found URI can escape params in query string, but only with few constructors like for example:
URI uri = new URI("http", "example.com",
"/path/path", "param1=param1Data¶m2= \"", null);
This constructor needs path and query be a separate arguments, but I have a relative URL, and it not split by path and query parts.
I could consider to check if relative URL contains "?" question sign and think everything before it is path, and everything after it is query, but what if relative url not contain path, but query only, and query contains "?" sign? Then this will not works because part of query will be considered as path.
Now I cannot get how to build absolute url from relative url.
These accepted answers seems just wrong:
how to get URL using relative path
Append relative URL to java.net.URL
Building an absolute URL from a relative URL in Java
It could be nice to consider scenario when relative url was given in relation to url with both host and some path part:
initial url http://example.com/...some path...
relative /home?...query here ...
It would be great to get java core solution, though it still possible to use a good lib.
The first ? indicates where the query string begins:
3.4. Query
[...] The query component is indicated by the first question mark (?) character and terminated by a number sign (#) character or by the end of the URI.
A simple approach (that won't handle fragments and assumes that the query string is always present) is as simple as:
String protocol = "http";
String host = "example.com";
String location = "/path/path?key1=value1&key2=value2";
String path = location.substring(0, location.indexOf("?"));
String query = location.substring(location.indexOf("?") + 1);
URI uri = new URI(protocol, host, path, query, null);
A better approach that can also handle fragments could be :
String protocol = "http";
String host = "example.com";
String location = "/path/path?key1=value1&key2=value2#fragment";
// Split the location without removing the delimiters
String[] parts = location.split("(?=\\?)|(?=#)");
String path = null;
String query = null;
String fragment = null;
// Iterate over the parts to find path, query and fragment
for (String part : parts) {
// The query string starts with ?
if (part.startsWith("?")) {
query = part.substring(1);
continue;
}
// The fragment starts with #
if (part.startsWith("#")) {
fragment = part.substring(1);
continue;
}
// Path is what's left
path = part;
}
URI uri = new URI(protocol, host, path, query, fragment);
The best way seems to be to create a URI object with the multi piece constructors, and then convert it to a URL like so:
URI uri = new URI("https", "sitename.domain.tld", "/path/goes/here", "param1=value¶m2=otherValue");
URL url = uri.toURL();
i want to remove cookie with domain name and context path as "/" which is running in my cloud server.
i have below code for clearing cookie in cloud server
Cookie cookie = new Cookie(cookieName, null);// cookieName = TEST_COOKIE
String cookiePath = request.getContextPath();
cookie.setPath(cookiePath); // path = "/"
cookie.setDomain("mydomain.com");
cookie.setMaxAge(0);
response.addCookie(cookie);
if i notice the cookie in my browser i have below details
cookie name = "TEST_COOKIE" value = "MUZJd3NuNDhy" domain = "mydomain.com" path = "/"
where in my localhost, above code works fine, without setting domain name. even i tried with empty domain name which is not working. dont know how to proceed with this, direction is much appreciated.
EDIT -
below code without domain in localhost is working fine with context path as /MyApp.
Cookie cookie = new Cookie(cookieName, null);
String cookiePath = request.getContextPath();
cookie.setPath(cookiePath); // path = "/"
cookie.setMaxAge(0);
response.addCookie(cookie);
when i removed contextPath "/MyApp", it stopped working in localhost too, where in my cloud server my context path is "/" .
After lot of debugging, i found the request.getContextPath was returning empty string instead of "/" in my remote server, and in jave doc
* Returns the portion of the request URI that indicates the context
* of the request. The context path always comes first in a request
* URI. The path starts with a "/" character but does not end with a "/"
* character. For servlets in the default (root) context, this method
* returns "". The container does not decode this string.
since i am having root context , the method return empty string instead of "/", i have fixed it by below code and it is working now.
if (cookiePath.isEmpty()) {
cookie.setPath("/");
} else {
cookie.setPath(cookiePath);
}
You cannot set a Cookie as null but you can delete it (i.e. : when you'll try to get it next time, it will return null).
Just change your first line with :
Cookie cookie = new Cookie(cookieName, "");
String cookiePath = request.getContextPath();
cookie.setPath(cookiePath); // path = "/"
cookie.setDomain("mydomain.com");
cookie.setMaxAge(0);
response.addCookie(cookie);
So I have successfully post data onto a Google Spreadsheet using the Google Form source. Everything works perfect UNTIL I make the field (in the Google Form) "required." When I do that, the Android Emulator still responds as if the information sent was properly saved. But on the Google spreadsheet it isn't there.
Am I missing something?
This is my AsyncTask:
new BackgroundTask().execute(
"https://docs.google.com/forms/d/10QStmb9Nr-hcfv889FMSNTZdA_hNUErxeK7vISzkx0E/formResponse",
student.FirstName, "entry_2030274183=",
student.LastName, "entry_1558758483=",
student.Age, "entry_1871336861=",
student.Gender, "entry.2013677542=",
student.Grade, "entry_1921311866=");
This is my Background.
protected String doInBackground(String... params) {
HttpRequest reg = new HttpRequest();
String URL = params[0];
String FirstName = params[1];
String FirstNameEntry = params[2];
String LastName = params[3];
String LastNameEntry = params[4];
String Age = params[5];
String AgeEntry = params[6];
String Gender = params[7];
String GenderEntry = params[8];
String Grade = params[9];
String GradeEntry = params[10];
#SuppressWarnings("deprecation")
String data =
FirstNameEntry + URLEncoder.encode(FirstName) + "&" +
LastNameEntry + URLEncoder.encode(LastName) + "&" +
AgeEntry + URLEncoder.encode(Gender) + "&" +
GenderEntry + URLEncoder.encode(Age) + "&" +
GradeEntry + URLEncoder.encode(Grade);
String response = reg.sendPost(URL, data);
return response;
}
Do I need to put something in the entries if it is a required field?
If you want to look at the HttpRequest class go here (Not My Code):
Secure HTTP Post in Android
Much Appreciated
The only way I can immediately think of is by processing the response and then making your app behave accordingly.
For instance - I tried one test form and if the request send had some required field empty, then the HTTPResponse contains "Looks like you have a question or two that still need attention".
Another way would be to validate if the save was actually successful by searching for the text you gave in the "Confirmation Page".
In both cases, you should be able to differentiate between a successful post and a failed one.
I have an URL address like: http://myfile.com/File1/beauty.png
I have to remove http://site address/ from main string
That mean result should be File1/beauty.png
Note: site address might be anything(e.g some.com, some.org)
See here: http://docs.oracle.com/javase/tutorial/networking/urls/urlInfo.html
Just create a URL object out of your string and use URL.getPath() like this:
String s = new URL("http://myfile.com/File1/beauty.png").getPath();
If you don't need the slash at the beginning, you can remove it via s.substring(1, s.length());
Edit, according to comment:
If you are not allowed to use URL, this would be your best bet: Extract main domain name from a given url
See the accepted answer. Basically you have to get a TLD list, find the domain and substract everything till the domain names' end.
If, as you say, you only want to use the standard String methods then this should do it.
public static String getPath(String url){
if(url.contains("://")){
url = url.substring(url.indexOf("://")+3);
url = url.substring(url.indexOf("/") + 1);
} else {
url = url.substring(url.indexOf("/")+1);
}
return url;
}
If the url contains :// then we know that the string you are looking for will come after the third /. Otherwise, it should come after the first. If we do the following;
System.out.println(getPath("http://myfile.com/File1/beauty.png"));
System.out.println(getPath("https://myfile.com/File1/beauty.png"));
System.out.println(getPath("www1.myfile.com/File1/beauty.png"));
System.out.println(getPath("myfile.co.uk/File1/beauty.png"));;
The output is;
File1/beauty.png
File1/beauty.png
File1/beauty.png
File1/beauty.png
You can use the below approach to fetch the required data.
String url = "http://myfile.org/File1/beauty.png";
URL u = new URL(url);
String[] arr = url.split(u.getAuthority());
System.out.println(arr[1]);
Output - /File1/beauty.png
String s = "http://www.freegreatpicture.com/files/146/26189-abstract-color-background.jpg";
s = s.substring(s.indexOf("/", str.indexOf("/") + 1));