HtmlUnit - "Browser Not Supported" Error on website using JQuery - java

I would like to use HtmlUnit to login to website and click a link so that a file would be downloaded, however, the website, which uses JQuery, returns a "Browser Not Supported" Error. Is there a way that HtmlUnit can be set to look exactly like a normal browser to this website?
Any help would be greatly appreciated.
I'm trying to do this with the following settings, but the error is still occurring:
public void surf(Job job) {
System.out.println("[Enter] surf");
try {
String applicationName = "Netscape";
String applicationVersion = "5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36 OPR/38.0.2220.41";
String userAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36 OPR/38.0.2220.41";
int browserVersionNumeric = 51;
BrowserVersion browser = new BrowserVersion(applicationName, applicationVersion, userAgent, browserVersionNumeric);
WebClient webClient = new WebClient(browser);
final HtmlPage page = webClient.getPage("https://www.europasports.com");
System.out.println(page);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("[Exit] surf");
}

Netscape was discontinued in March 2008, that's why you are getting the message. It no longer exists! If you are targeting Apple, i suggest you use Safari, but Google Chrome currently has the largest browser usage share

Related

Is there any way to exactly implement a "desktop mode" function into my mobile app when loading website content?

Is there any way to exactly implement a "desktop mode" function into my mobile app when loading website content? I'm making a android app, and I want to have a page just with static website content just like in a web browser, I really like how mobile opera implemented this feature, So I just want to know if there is a way to do that. And if there is, then How?
(I'm making this project in Java and viewing the website using WebView from the library "WebKit")
I've also tried changing the User Agent, which didn't work on a static website.
This method helps you to set DesktopMode on webview
public void setDesktopMode(WebView webView,boolean enabled) {
String newUserAgent = webView.getSettings().getUserAgentString();
if (enabled) {
newUserAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_5)\nAppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/85\nVersion/11.1.1 Safari/605.1.15";
}
webView.getSettings().setUserAgentString(newUserAgent);
webView.getSettings().setUseWideViewPort(enabled);
webView.getSettings().setLoadWithOverviewMode(enabled);
webView.reload();
}
Call it like that
Mobile mode : setDesktopMode(webView, false);
Desktop mode : setDesktopMode(webView, true);
For Kotlin:
fun setDesktopMode(webView: WebView, enabled: Boolean) {
var newUserAgent: String? = webView.settings.userAgentString
if (enabled) {
newUserAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_5)\nAppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/85\nVersion/11.1.1 Safari/605.1.15"
}
webView.settings.apply {
userAgentString = newUserAgent
useWideViewPort = enabled
loadWithOverviewMode = enabled
}
webView.reload()
}

Getting 503 error with HttpUrlConnection but site loading on browser

url = "https://www.lmcu.org/?__cf_chl_jschl_tk__=9c114404052361017d9cfe1247981e24813649c7-1592389426-0-AfP07ha5TxZHf64q5tb5nJf9BJguC4U553-OJzJWivTqfgwYLqUODkXj-XsOjZTwpC71ROxHWx4Xhdp2S0LgAVlKgXpy7KWOex7lkoGBm8mNpBsCeJapdYNWty-X2oHE6gp_TtMfH0dcBabvWr_mXV1djsVR_IGlYJA-wCuZpPTGOozyzN9TFwjMPxU-3o6BIUxTh6DDcHmJ_Bw48EYKGpq6n57bVdeLezEs9PduataW1JUcF4GqLE2EHiUxWGubtS8YgcxkkGin4zitHXENMbFi1kMhxI77LsORzKyhkAD1OkG8fGmV--Cgd3EpxWHtHD5vpoIFFIwX0uGQywPnegs";
HttpURLConnection connection = pingHttpUrl(url);
responseCode = connection.getResponseCode();
public HttpURLConnection pingHttpUrl(String url) throws IOException {
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) new URL(url).openConnection();
conn.setRequestMethod("GET");
conn.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76 Safari/537.36");
conn.setConnectTimeout(2000);
conn.setInstanceFollowRedirects(false);
conn.setReadTimeout(10000);
conn.connect();
Thread.sleep(1000);
} catch (Exception e) {
logger.error("Caught exception : {}", e.getMessage());
throw new IOException();
}
return conn;
}
This gives response code as 503. But the site is properly loading on browser. What can be the issue with this ?
The problem is with the headers of the request. I found that this solution hosted on cloudflare requires two headers to be just so, otherwise you will receive the 503 response:
User-Agent - Your header specified chrome version 76, apparently the server has a problem with this. I had success with this User-Agent value: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36
cookie - I found that the cookie value cf_clearance needs to be set, and possibly the other set-cookie values that are returned on the first request. This value has to do with the cloudflare support for privacy pass (https://blog.cloudflare.com/cloudflare-supports-privacy-pass/). It appears to be a means of verifying that a user is human, and not a machine. Which in turn is bad news for your efforts here.
I have a working solution below, but it will be hard to automate - since it will require you to establish a browser session, and use the cookie set there in the code. Upon expiration of the cf_clearance cookie, you will have visit the site again and reset the cookie value in the code.
I would also speculate that the User-Agent header of the request, is used in generating the cf_clearance cookie that is required. Making it more difficult to hijack the cookie, as you would have to use a matching User-Agent of the browser used for the request when the cf_clearance cookie was generated by cloudflare.
I have journaled my investigation here:
When visiting the URL in my browser:
https://www.lmcu.org/?cf_chl_jschl_tk=9c114404052361017d9cfe1247981e24813649c7-1592389426-0-AfP07ha5TxZHf64q5tb5nJf9BJguC4U553-OJzJWivTqfgwYLqUODkXj-XsOjZTwpC71ROxHWx4Xhdp2S0LgAVlKgXpy7KWOex7lkoGBm8mNpBsCeJapdYNWty-X2oHE6gp_TtMfH0dcBabvWr_mXV1djsVR_IGlYJA-wCuZpPTGOozyzN9TFwjMPxU-3o6BIUxTh6DDcHmJ_Bw48EYKGpq6n57bVdeLezEs9PduataW1JUcF4GqLE2EHiUxWGubtS8YgcxkkGin4zitHXENMbFi1kMhxI77LsORzKyhkAD1OkG8fGmV--Cgd3EpxWHtHD5vpoIFFIwX0uGQywPnegs
And inspecting the response that the server is giving, it turns out that it is infact giving back a 503 as well:
For some reson that I can't make out, the browser is redirected to the below URL instead. I cannot see that the location header is passed back in the response, or find this URL anywhere in the response.
https://www.lmcu.org/?cf_chl_jschl_tk=fe835fdc1e7e2f5b2857ab5eb4be84e67d0e8c42-1592506549-0-AQ3E1piNGHg7O7lxgRyItR1U5BzB52q7GmCHe_HPJBsUHv8RcZCgqLPPtyngPmDjvy7pZDprPNK6ihKVEgQ7HqmbDSPXZ1aHPkBDs9re49u_Q_jI04etmtK7E0GIdxhKWCd-p4TR7b_b0JdnwzJOF6z4XaJQOgNU8kazJr5Mo96zxQpUlsKWPSumEmSfynkGeMDgkM-O1mN59LKp0p4kt-2O2IIFrlc8289ZbCSO6JghtvDsLsFDA3VxLV3Irn2W3KQ8sHg_TdwB-0g0WX9J-WTwedVYzj2a7uNtH377ZIritTXKqRw1qeQ6mkpxQ0h_OVMIl8XUiEC0Zj1KP50tUK8
I checked with Postman, and sure enough - I got the 503 error there as well. As far as I could tell, the server (or reverse proxy in front of it) was inspecting the headers of the request, and invalidating the request based on them. I fooled around a little, moving headers from the browser request into Postman, and finally figured out that it is a combination of the cookie and User-Agent headers being set that allows the request to be served.
The User-Agent header is not allowed to have the specified chrome version, I have it working with version 83 here.
The cookkie header is something that the browser will populate from my first visit to the site in the browser. So that is a bit harder to handle in your code. I tried to fetch it in code with connection.getHeaderField("set-cookie") but that cookie does not seem to cut it.
But! I was able to make the code work, when taking the cookie from my browser, and setting it manually in code, along with the User-Agent:
public HttpURLConnection pingHttpUrl(String url) throws IOException {
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) new URL(url).openConnection();
conn.setRequestMethod("GET");
// This one does not work for the reason of the chrome version apparently
// conn.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76 Safari/537.36");
conn.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36");
conn.addRequestProperty("cookie", "<cookie value from the browser, from the header on a successful request>");
conn.setConnectTimeout(2000);
conn.setInstanceFollowRedirects(false);
conn.setReadTimeout(10000);
conn.connect();
Thread.sleep(1000);
} catch (Exception e) {
System.out.println(String.format("Caught exception : %s", e.getMessage()));
throw new IOException();
}
return conn;
}
I later found out that is is the cookie value from the cf_clearance key in the cookie that makes the difference.

copyURLToFile() throwing java.net.SocketException

When I run the following code:
try {
URL url = new URL("https://www1.nseindia.com/live_market/dynaContent/live_watch/get_quote/GetQuote.jsp?symbol=HUDCO&series=N2");
File f = new File("/Users/Vaibhav/Desktop/nseurltest.txt");
FileUtils.copyURLToFile(url, f);
} catch (Exception e) {
e.printStackTrace();
}
I get a java.net.SocketException: Operation timed out after about 30 seconds. Up to about a month ago, the same code was running without error. What could be the reason for this exception suddenly, and how can I fix it?
The objective of this code is to ultimately extract the latest market price of the HUDCO N2 bond from the .txt file the URL is copied into. If there is another simple way to extract the market price from the URL, I would love to hear.
I guess the website you try to reach, blocks unknown connections. But you can overcome this problem with jsoup library. With the following code, I've managed to download the content of the link.
Response response = Jsoup.connect(
"https://www1.nseindia.com/live_market/dynaContent/live_watch/get_quote/GetQuote.jsp?symbol=HUDCO&series=N2")
.ignoreContentType(true)
.userAgent(
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36")
.referrer("http://www.google.com").timeout(30000).followRedirects(true).execute();
Document doc = response.parse();
JSOUP dependecy :
<!-- https://mvnrepository.com/artifact/org.jsoup/jsoup -->
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.11.3</version>
</dependency>
You can change useragent. I put chrome 70 version's useragent string There are many options in the following link.
http://www.useragentstring.com/pages/useragentstring.php

WebView setUserAgentString() fails to load images

I set the user agent in webView
mWebview.getSettings().setUserAgentString(getString(R.string.str_user_agent));
String : Mozilla/5.0 (iPad; CPU OS 11_0 like Mac OS X) AppleWebKit/604.1.34 (KHTML, like Gecko) Version/11.0 Mobile/15A5341f Safari/604.1
When i set the user agent it fails to load some images. If anyone knows the reason or the answer please mention.

How can a java application identify a specific browser?

How can I identify whether the browser is Firefox or Chrome? Basically, I want an application to run only on the specific browser that is registered by a user. For this scenario, I want my application to identify the browser which the user is using, to know whether the application is permitted to run.
I am using java servlet.
I tried a the browser’s local storage, but it can be deleted with no control from my application. If local storage can be used, please let me know how.
(Yes I can get a browser info, but I want to identify a specific machine with a browser from where my application user is permitted to run the application; otherwise, I need to restrict that user from accessing my application.)
Fetch user-agent properties from the HTTP requeste header.
String userAgent=req.getHeader("user-agent");
String browserName = "";
String browserVer = "";
if(userAgent.contains("Chrome")){ //checking if Chrome
String substring=userAgent.substring(userAgent.indexOf("Chrome")).split(" ")[0];
browserName=substring.split("/")[0];
browserVer=substring.split("/")[1];
}
else if(userAgent.contains("Firefox")){ //Checking if Firefox
String substring=userAgent.substring(userAgent.indexOf("Firefox")).split(" ")[0];
browserName=substring.split("/")[0];
browserVer=substring.split("/")[1];
}
httpRequest.getHeader("user-agent")
Please use the below code in servlet to know what browser is hitting your servlet.
String userAgent = request.getHeader("user-agent");
public class MyServlet extends HttpServlet
{
#Override
public void doGet(final HttpServletRequest aRequest,
final HttpServletResponse aResponse) throws ServletException, IOException
{
final String agent = aRequest.getHeader("user-agent");
// agent will looks like
// Mozilla/5.0 (Windows NT 5.1; rv:23.0) Gecko/20100101 Firefox/23.0
// Mozilla/2.0 (compatible; MSIE 6.0; Windows NT 5.2)
// Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36
// etc.
}
}
Here is the code :
String userAgent = req.getHeader("user-agent");
UserAgent ua = UserAgent.parseUserAgentString(userAgent);
Version browserVersion = ua.getBrowserVersion();
String browserName = ua.getBrowser().toString();
int majVersion = Integer.parseInt(browserVersion.getMajorVersion());
Or use can easily get the browser deatils from javascript code like this -
Browser CodeName = navigator.appCodeName
Browser Name = navigator.appName
Browser Version = navigator.appVersion

Categories