I have a program that has a button which prints out the html text of a web address.I have got a variable that will have an address in the text box already, the issue is if I change the text in the text box to another address it will still print out the same html address. I've worded this issue badly but hopefully it's understandable. I want to be able to enter an URL and get that address html instead of going into the code eveytime and change the variable manually.
/* Create a HttpInteract object. */
public HttpInteract(String url) {
/* Split the "URL" into "host name" and "path name", and
* set host and path class variables.
* if URL is only a host name, use "/" as path
*/
System.out.println("URL splits into host name and path name.");
host = "cgi.csc.liv.ac.uk";
System.out.println("Host is:" +host);
path = "/~gairing/test.txt";
System.out.println("Path is:" +path);
//Request message. Connection closes after response because http 1.0
//is non persistent
requestMessage= "GET "+path+ " HTTP/1.1\r\n"
+"Host: " +host+ "\r\n"
+"\r\n" ;
return;
}
Simple example using URL:
// Note that you need protocol for valid URL
URL url = new URL("http://cgi.csc.liv.ac.uk/~gairing/test.txt");
System.out.println("Host:" + url.getHost());
System.out.println("Path:" + url.getPath());
Related
I'm weak in network technologies and maybe you can help me. I have a simple code
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
.getRequest();
UriComponents uriComponents = UriComponentsBuilder.fromHttpUrl(request.getRequestURL().toString()).build();
UriComponents newUriComponents = UriComponentsBuilder.newInstance().scheme(uriComponents.getScheme())
.host(uriComponents.getHost()).port(uriComponents.getPort()).build();
return newUriComponents.toUriString() + request.getContextPath();
This code should return link to my server with specific path. The problem is - on product server uriComponents.getHost() returns IP instead of domain name. Domain works when I go via browser to server. I can go to
http://exmaple.com/some/one/path and want to get in answer (in JSON, there are no redirections. just get request and json answer) - http://exmaple.com/some/another/path but code which I have showed returns - http://78.54.128.98.com/some/another/path (IP address just example). So I don't know why my code returns IP but not domain name. Only what I can to say more - in my local machine I don't have any problems with it. Code returns localhost, or if i add 127.0.0.1 exmaple.com to hosts file, my code will return correct exmaple.com, no any ip
This is not a problem of the URIComponents, it parses what it gets in input. More specifically looking at the source of UriComponentsBuilder.fromHttpUrl you see:
public static UriComponentsBuilder fromHttpUrl(String httpUrl) {
Assert.notNull(httpUrl, "HTTP URL must not be null");
Matcher matcher = HTTP_URL_PATTERN.matcher(httpUrl);
if (matcher.matches()) {
UriComponentsBuilder builder = new UriComponentsBuilder();
String scheme = matcher.group(1);
builder.scheme(scheme != null ? scheme.toLowerCase() : null);
builder.userInfo(matcher.group(4));
String host = matcher.group(5);
if (StringUtils.hasLength(scheme) && !StringUtils.hasLength(host)) {
throw new IllegalArgumentException("[" + httpUrl + "] is not a valid HTTP URL");
}
builder.host(host);
String port = matcher.group(7);
if (StringUtils.hasLength(port)) {
builder.port(port);
}
builder.path(matcher.group(8));
builder.query(matcher.group(10));
return builder;
}
else {
throw new IllegalArgumentException("[" + httpUrl + "] is not a valid HTTP URL");
}
}
where you can notice that a pattern matcher is defined on an expected structure of the url and parts are parsed according to the matcher. If you see IP it means that the url specified in input (request.getRequestURL().toString()) contained the IP address as a host.
This means that you should be looking for the guilty one above in the chain, starting by whoever calls this piece of code and following the links until you find the cause.
So I'm making a program that extracts the lyrics from a user given song off of AZ Lyrics.
The problem I'm having is that after converting the string to a URL, it says Jsoup is not able to parse it because it doesn't accept strings despite the variable being a URL that we are passing in.
String strURL = "http://www.azlyrics.com/lyrics/" + artist + "/" + song + ".html";
URL url = new URL(strURL);
Document doc = Jsoup.parse(url);
What should I do?
I dont know which version of jsoup your are using, but as per latest version the parse method with url alone is not available. You need to pass a timeOut. So try
Document doc = Jsoup.parse(url, 30000);
There is a connect method which would be the best option (IMO). You could pass the stringURL variable directly. Try
Document doc = Jsoup.connect(strURL).get();
If these didn't help check the value of artist and song variables.
You don't need to convert the string strURL to URL, this should work:
Document doc = Jsoup.connect("http://www.azlyrics.com/lyrics/" + artist + "/" + song + ".html").timeout(10000).get();
String html = doc.text();
I've set a timeout of 10 seconds, adjust to fit your needs.
You can take a look at the available methods here
I have written a code in java, where there are forms (input fields) and finally a send email button at the bottom. when the user clicks on the button, the data from the input fields should get extracted then be used as data for the body in the email.
this is the code i have:
if (role.getValue().equals("1")) {
Desktop desktop = Desktop.getDesktop();
String message = "mailto:username#domain.com?subject=Profildaten&body=" +
"Externe%20Referenz:%20" +
person.getExternalReference() + "%20" + "-%20" +
person.getExternalReferenceType() + "%0A" +
person.getTitle() + "%20" +
person.getContactLandline() + "%0A" +
"Mobil:%20" + person.getContactMobile() + "%0A" +
"Addresse:" + person.getContactStreet();
URI uri = URI.create(message);
try {
desktop.mail(uri);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
It all works perfectly, but the only issue is for Address: person.getContactStreet() the actual input field requires the user to enter a street name, and usually it would be two words, e.g. Cromwell Road - with a space inbetween cromwell and road. now the body of the email doesnt allow to have spaces and other invalid characters, hence why it is popping an error message saying invalid characters have been entered. how can i make it accept this or convert the invalid characters automatically to url encodings?
Have a look at this site, it tells you how to encode the URLS in the body automatically.
Best way to encode URL in Java
The following is my piece of code
SmbFile catalExp = new SmbFile("smb://<Shared machine name>/Project share/Home/4. Folders/planning - Design & Exec/sample.txt",
new NtlmPasswordAuthentication(LoadProp.getShrdDomain(),"user","paswd"));
In this i am getting the error
jcifs.smb.SmbException: The network name cannot be found
at jcifs.smb.SmbTransport.send(SmbTransport.java:753)
at jcifs.smb.SmbSession.sessionSetup(SmbSession.java:140)
at jcifs.smb.SmbSession.send(SmbSession.java:103)
at jcifs.smb.SmbTree.treeConnect(SmbTree.java:132)
at jcifs.smb.SmbFile.connect(SmbFile.java:674)
at jcifs.smb.SmbFile.connect0(SmbFile.java:644)
at jcifs.smb.SmbFile.open0(SmbFile.java:700)
at jcifs.smb.SmbFile.createNewFile(SmbFile.java:2027)
Is this anything to do with the user rights to that particular shared folder or am I doing anything wrong
Please advice
I ran into this error message, and it turned out the problem was that my network path was incorrect. You'll want to ensure that the NtlmPasswordAuthentication object is configured correctly, that your network path is correct, and that you've set the jcifs.netbios.wins property correctly, as indicated in the first example on this page.
For example, to load a remote properties file:
final NtlmPasswordAuthentication AUTH = new NtlmPasswordAuthentication("domainname", "username", "password");
Config.setProperty("jcifs.netbios.wins", "10.10.1.1");
Properties props = new Properties();
InputStream in = new SmbFileInputStream(new SmbFile("smb://10.10.1.1:445/rootfolder/path/filename.properties", AUTH));
props.load(in);
(You'll need to add try/catch and input stream closing)
A good way to ensure that all of your parameters are correct is to test logging into and locating the file using a smb/cifs client. For example smbclient on linux/unix:
smbclient -Uusername -p 139 //10.10.1.1/rootfolder
The domain is displayed at the top when you login with smbclient:
Domain=[DOMAINNAME]
..and you can navigate to your file to make sure you've got the path correct.
After running into this issue for almost 1 day i realize that these exception is meaningless
I was just giving wrong path of server side location
Below is the peace of groovy code worked for me
String domain = "domain"
String user = "username"
String pass = "password"
String IP = "xx.yy.zz.aa"
String sharedFolder="//my//path//to//server//";
String path="smb://$IP"+sharedFolder+"test.txt";
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(domain, user, pass );
SmbFile smbFile = new SmbFile(path,auth);
SmbFileOutputStream smbfos = new SmbFileOutputStream(smbFile);
smbfos.write("testing....and writing to a file".getBytes());
System.out.println("completed ...nice !");
Well I'm getting this error also but only on one device, my code that works on Android 4.04 is
String strprog = "STRING CREATED| "; //debug log string
try {
strprog += "NTLM| ";
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication("username:password");
strprog += "SMB| ";
SmbFile file = new SmbFile("smb://<pcname>/foldername/filename.txt",auth);
strprog += "EXIST| ";
String there = String.valueOf(file.exists());
strprog += "View| ";
TextView pp;
pp = (TextView) findViewById(R.id.tv);
pp.setText(there);
} catch (Exception e) {
// TODO Auto-generated catch block
strprog += "ERROR! ";
TextView ll;
ll = (TextView) findViewById(R.id.tv);
ll.setText(strprog + e.getStackTrace().toString() + " " + e.getMessage() + " " + e.getLocalizedMessage() );
}
The only difference I see is where you have your NtlmPasswordAuth compared to mine.
But as I stated for some reason this throws null input param on Andriod 2.0 when I dive deeper then smb://host but I hope this helps you out.
I had this problem, and it turned out that I did not see what the share name was that was mapped to my Windows shared drive... So, using Mac OS, I ran:
smbutil view smb://MYUSERNAME#HOSTNAME
After I was prompted for my password, I then was displayed a list of share names (that weren't evident when I looked at this stuff using Windows). Once I found my share name, it was as simple as using that when connecting with JCIFS:
new SmbFile("smb://HOSTNAME/SHARENAME/path/I/was/trying/to/access", auth);
I desperately need your expertise in resolving a Windows-7 issue.
Scenario: I have a frame-based Help package that is set up for context-sensitive help calls. A Java application is able to control what page the Help packages opens to by passing a tag representing the desired HTML named anchor to an HTML file called pophelp. This file has javascripting that reads the passed tag from the end of the URL and maps it to the appropriate HTML file in the help package and opens it.
Issue: The above scenario works in Windows XP, but no longer in Windows 7.
Calling mechanism from Java application: rundll32 url.dll,FileProtocolHandler file://filepath/pophelp.html?tag
Summary of findings so far: It appears that url.dll no longer allows parameters to be passed with URLs in Windows 7. Parameters are being stripped. I also tried the same type of call using Desktop.getDesktop().browse() from Java, but it too seems to strip off all parameters after .html.
Sample code:
Original call that works in Windows XP --
Running command: rundll32 url.dll,FileProtocolHandler file://C:\Program Files\App System\App-Editor-8.0.1\help\pophelp.html?TAG=callsubflow
Result: ?TAG=callsubflow is not passed.
New code using Desktop.getDesktop().browse() --
public static void main(String[] args) {
String url = "file:///C:/Program Files/App System/App-Editor-8.0.1/help/pophelp.html?TAG=callsubflow";
try {
if (Desktop.isDesktopSupported()) {
Desktop desktop = Desktop.getDesktop();
if (desktop.isSupported(Desktop.Action.BROWSE)) {
desktop.browse(new URI(url.replace(" ", "%20")));
}
}
} catch (IOException e) {
System.out.println("Unable to open "+url+": "+e.getMessage());
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
Result: ?TAG=callsubflow is not passed.
Any assistance would be appreciated!
I really can't tell why Windows removes parameters on local files. As mentioned in the comments this seams to be some kind of weird restrictions for security. But I once had a similar problem and I found a workaround that fits in this situation as well.
Simply create a local temporary HTML file (without parameters) that redirects you to the desired one (with parameters).Have a look at these two methods:
// creates w3c conform redirect HTML page
public String createRedirectPage(String url){
return "<!DOCTYPE HTML>" +
"<meta charset=\"UTF-8\">" +
"<meta http-equiv=\"refresh\" content=\"1; url=" + url + "\">" +
"<script>" +
"window.location.href = \"" + url + "\"" +
"</script>" +
"<title>Page Redirection</title>" +
"<!-- Note: don't tell people to `click` the link, just tell them that it is a link. -->" +
"If you are not redirected automatically, follow the <a href='" + url + "'>link</a>";
}
// creates temporary file with content of redirect HTML page
public URI createRedirectTempFile(String url) {
BufferedWriter writer = null;
File tmpFile = null;
try {
// creates temporary file
tmpFile = File.createTempFile("pophelp", ".html", null);
// deletes file when the virtual machine terminate
tmpFile.deleteOnExit();
// writes redirect page content to file
writer = new BufferedWriter(new FileWriter(tmpFile));
writer.write(createRedirectPage(url));
writer.close();
}
catch (IOException e) {
return null;
}
return tmpFile.toURI();
}
Now you can use these like this:
String url = "file:///C:/Program Files/App System/App-Editor-8.0.1/help/pophelp.html?TAG=callsubflow";
if (Desktop.isDesktopSupported()) {
Desktop desktop = Desktop.getDesktop();
if (desktop.isSupported(Desktop.Action.BROWSE)) {
desktop.browse(createRedirectTempFile(url.replace(" ", "%20")));
}
}
I have a solution, not a quick (or pretty) solution, but a solution nonetheless :)
rundll32 url.dll,FileProtocolHandler does pass params when using URLs with http/s protocol (try rundll32 url.dll,FileProtocolHandler http://www.google.com?q=google), so you can setup small http server (like Jetty i guess) to serve your help files and show them using
rundll32 url.dll,FileProtocolHandler http://localhost:[helpServerIp]/help/pophelp.html?TAG=callsubflow