I am relatively new to programming. I need to fill a form on a url through an Android APP with:
Dropdown menu
TextField
Captacha (Image and TextField)
I will use post requests through JSOUP for 1 and 2.
For 3:
I have gone through the html of the page and the captcha image seems like this:
img id="ctl00_ContentPlaceHolder1_capchaImage" src="JpegImage.aspx"
style="height:50px;width:100%;"
I'm currently able to get captcha image url but unable to display it in Android ImageView. Following is my code:
try {
Bitmap captchaimg = null;
String B = "https://whatever.com";
Document doc2 = Jsoup.connect(B).get();
Element captcha = doc2.select("#ctl00_ContentPlaceHolder1_capchaImage").first();
imgsrc = captcha.attr("abs:src");
System.out.println("\nsrc : " + imgsrc);
InputStream inputStream = new URL(imgsrc).openStream();
captchaimg = BitmapFactory.decodeStream(inputStream);
}
catch (IOException e)
{
builder.append("Error : ").append(e.getMessage()).append("\n");
}
runOnUiThread(new Runnable()
{
#Override
public void run() {
imagev.setImageBitmap(captchaimg);
});
This is the problem that I am actually having.
P.S. The source code of the aspx captcha is given on this site CAPTCHA
Related
I have pdf file stored on my firebase storage, and its link in firebase real-time database, how can I open it inside my android app (android studio, JAVA). Not using INTENT , but directly inside my app.
You can use android-pdfView, see this blog post.
It demonstrates the basic usage of the library to display pdf onto the view with vertical and horizontal swipe.
pdfView = (PDFView) findViewById(R.id.pdfView);
pdfView.fromFile(new File("/storage/sdcard0/Download/pdf.pdf")).defaultPage(1).enableSwipe(true).onPageChange(this).load();
There are also other libraries like Android PDF Viewer,
VuDroid etc.
Also Android API 19 provides feasibility now to present pdf content inside an app and thus no need of 3rd party SDKs.
you can find details here.
If you want to load the file using a URL then you can use a webview.
WebView webview = (WebView) findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
String pdf = "http://www.adobe.com/devnet/acrobat/pdfs/pdf_open_parameters.pdf";
webview.loadUrl("http://docs.google.com/gview?embedded=true&url=" + pdf);
Found the answer with little research :-
no need of webview or Intent which opens another app
Library :-
implementation 'com.github.barteksc:android-pdf-viewer:2.8.2'
xml code :-
<com.github.barteksc.pdfviewer.PDFView
android:visibility="visible"
android:id="#+id/pdfView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
JAVA code :-
{
String pdfurl="firebase_access_token_of_pdf_file";
pdfView = (PDFView) findViewById(R.id.pdfView);
new RetrivePDFfromUrl().execute(pdfUrl);
}
// create an async task class for loading pdf file from URL.
class RetrivePDFfromUrl extends AsyncTask<String, Void, InputStream> {
#Override
protected InputStream doInBackground(String... strings) {
// we are using inputstream
// for getting out PDF.
InputStream inputStream = null;
try {
URL url = new URL(strings[0]);
// below is the step where we are
// creating our connection.
HttpURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
if (urlConnection.getResponseCode() == 200) {
// response is success.
// we are getting input stream from url
// and storing it in our variable.
inputStream = new BufferedInputStream(urlConnection.getInputStream());
}
} catch (IOException e) {
// this is the method
// to handle errors.
e.printStackTrace();
return null;
}
return inputStream;
}
#Override
protected void onPostExecute(InputStream inputStream) {
// after the execution of our async
// task we are loading our pdf in our pdf view.
pdfView.fromStream(inputStream).load();
}
}
}
I'm trying to implement a history-button in my Browser class (created in eclipse), and I want the links in the button to be clickable. Here is my code that gets initiated when the user presses the button History:
private void showMessage() {
try {
String message = new String();
message = history.toString();
JOptionPane.showMessageDialog(null, message);
} catch (NullPointerException e) {
System.out.println("Something is wrong with your historylist!");
}
}
In the code above, history is a list with all the webpages that has been previously visited.
I have tried using the method presented here:
clickable links in JOptionPane, and I got it to work. The problem is, this solution only lets me predefine URL:s, but I want my list history to be displayed, and the URLs in it to be clickable.
For example, if I have visited https://www.google.com and https://www.engadget.com, the list will look like this: history = [www.google.com, www.engadget.com], and both links should be separately clickable.
This is the function that should be called when someone presses the history-button. It uses a JEditorPane with a HyperlinkListener. The string html in the code below adds the needed html-coding so that the HyperlinkListener can read and visit the webpages.
public void historyAction() {
String html = new String();
for (String link : history) {
html = html + "" + link + "\n";
}
html = "<html><body" + html + "</body></html>";
JEditorPane ep = new JEditorPane("text/html", html);
ep.addHyperlinkListener(new HyperlinkListener() {
public void hyperlinkUpdate(HyperlinkEvent e) {
if (e.getEventType().equals(HyperlinkEvent.EventType.ACTIVATED)) {
loadURL(e.getURL().toString());
}
}
});
ep.setEditable(false);
JOptionPane.showMessageDialog(null, ep);
}
I had asked the question previously about how to retrieve the embedded url for a video file and have successfully done so. Now I have a different issue. The json response for a WUnderground API webcam response gives the following url:
https://www.wunderground.com/webcams/cadot1/902/show.html
Using JSoup and per the answer to my initial issue I was able to get this embedded link:
https://www.wunderground.com/webcams/cadot1/902/video.html?month=11&year=2016&filename=current.mp4
While trying to "stream" the video from that url to a VideoView, I kept getting the error "cannot play video". Upon looking at the source for that link I noticed that the video file that needs to be played is not referenced in html but rather javascript. How can I get the direct link for the video file that needs to be played? Using JSoup or other process?
The source for the url https://www.wunderground.com/webcams/cadot1/902/video.html?month=11&year=2016&filename=current.mp4 shows the following for the needed video file within a <script> bracket:
url: "//icons.wunderground.com/webcamcurrent/c/a/cadot1/902/current.mp4?e=1480377508"
I am using JSoup to get the embedded url for the video from the response url like so:
private class VideoLink extends AsyncTask<Void, Void, Void> {
String title;
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog.setTitle("JSOUP Test");
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
try {
// for avoiding javax.net.ssl.SSLProtocolException: handshake alert: unrecognized_name
System.setProperty("jsse.enableSNIExtension", "false");
// WARNING: do it only if security isn't important, otherwise you have
// to follow this advices: http://stackoverflow.com/a/7745706/1363265
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager(){
public X509Certificate[] getAcceptedIssuers(){return null;}
public void checkClientTrusted(X509Certificate[] certs, String authType){}
public void checkServerTrusted(X509Certificate[] certs, String authType){}
}};
// Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
;
}
// Connect to the web site
Document doc = Jsoup.connect(TEST_URL).get();
Elements elements = doc.getElementsByClass("videoText");
// Get the html document title
for (Element link : elements) {
String linkHref = link.attr("href");
// linkHref contains something like video.html?month=11&year=2016&filename=current.mp4
// TODO check if linkHref ends with current.mp4
title = linkHref;
}
} catch (IOException e) {
e.printStackTrace();
mProgressDialog.dismiss();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// Set title into TextView
resultTxt.setText(title);
String resVid = TEST_URL;
Log.d(TAG, "URL: " + resVid);
Uri resUri = Uri.parse(resVid);
try {
// Start the MediaController
MediaController mediacontroller = new MediaController(
MainActivity.this);
mediacontroller.setAnchorView(resultVidVw);
// Get the URL from String VideoURL
Uri video = Uri.parse(resVid);
resultVidVw.setMediaController(mediacontroller);
resultVidVw.setVideoURI(video);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
resultVidVw.requestFocus();
resultVidVw.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
// Close the progress bar and play the video
public void onPrepared(MediaPlayer mp) {
mProgressDialog.dismiss();
resultVidVw.start();
}
});
}
}
Please note that I need to do this on every JSONObject in the response array.
This is how you can GET the file:
(Notice: the Extraction part only works with current html of the site and if that changes, it may not work correctly!)
String url = "https://www.wunderground.com/webcams/cadot1/902/video.html";
int timeout = 100 * 1000;
// Extract video URL
Document doc = Jsoup.connect(url).timeout(timeout).get();
Element script = doc.getElementById("inner-content")
.getElementsByTag("script").last();
String content = script.data();
int indexOfUrl = content.indexOf("url");
int indexOfComma = content.indexOf(',', indexOfUrl);
String videoUrl = "https:" + content.substring(indexOfUrl + 6, indexOfComma - 1);
System.out.println(videoUrl);
[Output: https://icons.wunderground.com/webcamcurrent/c/a/cadot1/902/current.mp4?e=1481246112]
Now you can get the file by specifying .ignoreContentType(true) in order to avoid org.jsoup.UnsupportedMimeTypeException and .maxBodySize(0) to remove the limit on file size.
// Get video file
byte[] video = Jsoup.connect(videoUrl)
.ignoreContentType(true).timeout(timeout).maxBodySize(0)
.execute().bodyAsBytes();
I don't know if you can play it in Android or not but I think you can save it using org.apache.commons.io.FileUtils (I tested it in Java SE but not Android development environment.)
// Save video file
org.apache.commons.io.FileUtils.writeByteArrayToFile(new File("test.mp4"), video);
my problem is that I use in my practice are pdf files. I did not add them into my application. I want pdf files from ftp or a URL to download it. I have no idea about the solution. I've tried a lot ftp code and URL code. All I want, when you pressed the button of the sdcard files from a URL or FTP address to get a download. Thanks for your help.
this code is working for me
public void onClick(View v) {
PrintAttributes printAttrs = new PrintAttributes.Builder().
setColorMode(PrintAttributes.COLOR_MODE_COLOR).
setMediaSize(PrintAttributes.MediaSize.NA_LETTER).
setResolution(new PrintAttributes.Resolution("zooey", PRINT_SERVICE, 300, 300)).
setMinMargins(PrintAttributes.Margins.NO_MARGINS).
build();
PdfDocument document = new PrintedPdfDocument(DynamicPDFHelloWorld.this, printAttrs);
// crate a page description
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(300, 300, 1).create();
// create a new page from the PageInfo
PdfDocument.Page page = document.startPage(pageInfo);
// repaint the user's text into the page
View content = findViewById(R.id.textarea);
content.draw(page.getCanvas());
content.draw(edt.getText().toString().);
// do final processing of the page
document.finishPage(page);
// Here you could add more pages in a longer doc app, but you'd have
// to handle page-breaking yourself in e.g., write your own word processor...
// Now write the PDF document to a file; it actually needs to be a file
// since the Share mechanism can't accept a byte[]. though it can
// accept a String/CharSequence. Meh.
try {
File f = new File(Environment.getExternalStorageDirectory().getPath() + "/pruebaAppModerator.pdf");
FileOutputStream fos = new FileOutputStream(f);
document.writeTo(fos);
document.close();
fos.close();
} catch (IOException e) {
throw new RuntimeException("Error generating file", e);
}
}
});
I'm having this weird problem with HtmlUnit in Java. I am using it to download some data from a website, the process is something like this:
1 - Login
2 - For each element (cars)
----- 3 Search for car
----- 4 Download zip file from a link
The code:
Creation of the webclient:
webClient = new WebClient(BrowserVersion.FIREFOX_3_6);
webClient.setJavaScriptEnabled(true);
webClient.setThrowExceptionOnScriptError(false);
DefaultCredentialsProvider provider = new DefaultCredentialsProvider();
provider.addCredentials(USERNAME, PASSWORD);
webClient.setCredentialsProvider(provider);
webClient.setRefreshHandler(new ImmediateRefreshHandler());
Login:
public void login() throws IOException
{
page = (HtmlPage) webClient.getPage(URL);
HtmlForm form = page.getFormByName("formLogin");
String user = USERNAME;
String password = PASSWORD;
// Enter login and password
form.getInputByName("LoginSteps$UserName").setValueAttribute(user);
form.getInputByName("LoginSteps$Password").setValueAttribute(password);
// Click Login Button
page = (HtmlPage) form.getInputByName("LoginSteps$LoginButton").click();
webClient.waitForBackgroundJavaScript(3000);
// Click on Campa area
HtmlAnchor link = (HtmlAnchor) page.getElementById("ctl00_linkCampaNoiH");
page = (HtmlPage) link.click();
webClient.waitForBackgroundJavaScript(3000);
System.out.println(page.asText());
}
Search for car in website:
private void searchCar(String _regNumber) throws IOException
{
// Open search window
page = page.getElementById("search_gridCampaNoi").click();
webClient.waitForBackgroundJavaScript(3000);
// Write plate number
HtmlInput element = (HtmlInput) page.getElementById("jqg1");
element.setValueAttribute(_regNumber);
webClient.waitForBackgroundJavaScript(3000);
// Click on search
HtmlAnchor anchor = (HtmlAnchor) page.getByXPath("//*[#id=\"fbox_gridCampaNoi_search\"]").get(0);
page = anchor.click();
webClient.waitForBackgroundJavaScript(3000);
System.out.println(page.asText());
}
Download pdf:
try
{
InputStream is = _link.click().getWebResponse().getContentAsStream();
File path = new File(new File(DOWNLOAD_PATH), _regNumber);
if (!path.exists())
{
path.mkdir();
}
writeToFile(is, new File(path, _regNumber + "_pdfs.zip"));
}
catch (Exception e)
{
e.printStackTrace();
}
}
The problem:
The first car works okay, pdf is downloaded, but as soon as I search for a new car, when I get to this line:
page = page.getElementById("search_gridCampaNoi").click();
I get this exception:
Exception in thread "main" java.lang.ClassCastException: com.gargoylesoftware.htmlunit.UnexpectedPage cannot be cast to com.gargoylesoftware.htmlunit.html.HtmlPage
After debugging, I've realized that the moment I make this call:
InputStream is = _link.click().getWebResponse().getContentAsStream();
the return type of page.getElementById("search_gridCampaNoi").click() changes from HtmlPage to WebResponse, so instead of receiving a new page, I'm receiving again the file that I already downloaded.
A couple of screenshots of the debugger showing this situation:
First call, return type OK:
Second call, return type changed and I no longer receive a HtmlPage:
Thanks in advance!
Just in case someone encounters the same problem, I found a workaround.Changing the line:
InputStream is = _link.click().getWebResponse().getContentAsStream();
to
InputStream is = _link.openLinkInNewWindow().getWebResponse().getContentAsStream();
seems to do the trick. Im having problems now when doing several iterations, sometimes it works, sometimes it doesn't but at least I have something now.