I want my app to automatically access a webpage, check or uncheck a box and click submit
I have tried many codes given here with no success.
eg:
html snippet:
<tr>
<td align="center"><input type="checkbox" name="Yes" ></td>
</tr>
</table>
<p> </td>
<td width="112" height="27" align="right">
<input type="submit" value="SubmitForm" style="float: left"></td>
I want my code to toggle the "yes" and then click the submit button "SubmitForm"
thanks!
usually something like this http://kspace.in/blog/2008/05/30/submit-html-form-using-java/
package post;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpPostForm
{
public static void main(String[] args)
{
try
{
URL url = new URL( "http://www.aaaa.com/xyz.asp" );
HttpURLConnection hConnection = (HttpURLConnection)
url.openConnection();
HttpURLConnection.setFollowRedirects( true );
hConnection.setDoOutput( true );
hConnection.setRequestMethod("POST");
PrintStream ps = new PrintStream( hConnection.getOutputStream() );
ps.print("param1=abcd¶m2=10341");
ps.close();
hConnection.connect();
if( HttpURLConnection.HTTP_OK == hConnection.getResponseCode() )
{
InputStream is = hConnection.getInputStream();
OutputStream os = new FileOutputStream("output.html");
int data;
while((data=is.read()) != -1)
{
os.write(data);
}
is.close();
os.close();
hConnection.disconnect();
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}
Related
Trying to get data from website through HTML parsing.
java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
Why is the array empty?
I included only the class that contains Jsoup because im sure the error is in it. And also i included the HTML part of the website in case you guys wanna take a look at it.
Jsoup Class
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
public class contentExcluding {
public String[] createData(final String [] text, final String [] pictures)
{
Runnable rMain = new Runnable() {
#Override
public void run() {
try {
Document doc = Jsoup.connect("http://egyptianstreets.com/").get();
Element content = doc.getElementById("featured-multi-main-img");
Elements headlines = content.getElementsByTag("img");
Elements img = content.getElementsByAttribute("src");
String x = img.toString();
pictures[0] = x;
text[0] = x;
} catch (IOException e) {
e.printStackTrace();
}
}
};
Thread t = new Thread(rMain);
t.start();
return pictures;
}
}
HTML
<div id="head-wrap" class="left relative">
<div class="head-wrap-out">
<div class="head-wrap-in">
<div id="featured-multi-wrap" class="left relative">
<div id="featured-multi-main" class="left relative">
<a href="http://egyptianstreets.com/2016/08/06/egyptian-rowers-nadia-negm-and-abdel-khalek-elbana-reach-quarter-finals-at-olympics/" rel="bookmark">
<div id="featured-multi-main-img" class="left relative">
<img width="1000" height="512" src="http://egyptianstreets.com/wp-content/uploads/2016/08/pablo-2-1000x512.png" class="unlazy reg-img wp-post-image" alt="pablo (2)" /> <img width="400" height="240" src="http://egyptianstreets.com/wp-content/uploads/2016/08/pablo-2-400x240.png" class="unlazy mob-img wp-post-image" alt="pablo (2)" />
It looks like pictures or text are 0 length arrays.
Check that you initialized them (before call createData method) with a higher size of 0.
Example:
String[] pictures = contentExcluding.createData(new String[1], new String[1]);
The code is aim for grap content by using jsoup, and i'm try to upgrade the code
Here is my code so far:
package com.phonegap.g7.plugin;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.apache.cordova.api.CordovaPlugin;
import org.apache.cordova.api.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class UrlFeedJava extends CordovaPlugin {
//#Override
public PluginResult execute(String action, JSONArray data, String callbackId) {
PluginResult.Status status = PluginResult.Status.OK;
PluginResult r=null;
try
{
String target = data.getString(0);
String selector = data.getString(1);
Document doc = Jsoup.connect(target).get();
Element masthead = doc.select(selector).first();
String content=masthead.toString();
String title = doc.title();
r=new PluginResult(status,content);
}
catch(Exception ee)
{
System.out.print("ee:"+ee.getMessage());
}
return r;
}
}
the PhonegapPlugin.js file
UrlFeed.prototype = {
send: function(success, error, url, selector){
cordova.exec(success, error, "UrlFeedJava", "send", [url, selector]);
}
};
PhoneGap.addConstructor(function() {
PhoneGap.addPlugin('urlfeed', new UrlFeed());
});
the index.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />
<script type='text/javascript' src='jquery-1.8.3.min.js'></script>
<script type='text/javascript' src='cordova-2.7.0.js'></script>
<script type='text/javascript' src='PhonegapPlugin.js'></script>
<script type='text/javascript'>
$(function(){
var onSend = function(){
var success = function(data){
$('#show').html(data);
};
var error = function(e){
alert(e);
};
var url = 'http://sports.163.com/12/0618/09/8496QLNG00051C8V.html';
var selector = $('#selector').val();
window.plugins.urlfeed.send(success, error, url, selector);
};
$('#send').bind('click', onSend);
});
</script>
</head>
<body>
<div id='messageDiv'>
<input type='text' id='selector'></input>
<div id='show'></div>
<button type='button' id='send'>Send Me</button>
</div>
</body>
</html>
Especially i don't understand the function of the constructor.
With newer phonegap releases you define the constructor in javascript like this:
var UrlFeed = function(){};
cordova.addConstructor(function() {
if (!window.plugins) {
window.plugins = {};
}
window.plugins.UrlFeed = new UrlFeed();
});
It makes the urlfeed object available to your entire application, you access it anywhere like
window.plugins.UrlFeed.doSomething();
Adding methods to your plugin:
UrlFeed.prototype.doSomething = function(arguments){
//do stuff
//send to phonegap
return PhoneGap.exec(
successCallback,
failureCallback,
'UrlFeed',
null,
[arguments]
);
};
You have to change your java plugin like this:
public class UrlFeedJava extends CordovaPlugin {
//#Override
public boolean execute(String action, JSONArray args,
final CallbackContext callbackContext) throws JSONException {
//your code
return true;
}
}
So basic change is that you do not return a plugin result anymore, but a simple boolean. So remove all plugin result code from your java code.
Please have a look at the simple toast plugin. It shows you how a phonegap plugin is developed https://github.com/giver/cordova-android-toast-plugin
Ref: http://docs.phonegap.com/en/2.8.0/guide_plugin-development_index.md.html#Plugin%20Development%20Guide
I want to open the contents of a html file which I have saved in my assets folder. The html file contains the chart api provided by the Google graphs.
Content of the HTML file are:
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi">
</script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart()
{
var data = google.visualization.arrayToDataTable([ ['Task', 'Hours per Day'],
['Work', 11],
['Eat', 2],
['Commute', 2],
['Watch TV', 2],
['Sleep', 7]
]);
var options = {title: 'My Daily Activities'};
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
</body>
</html>
I have written my main activity class as:
package com.example.webapptest;
import java.io.IOException;
import java.io.InputStream;
import java.net.ConnectException;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.webkit.WebSettings;
import android.webkit.WebView;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
WebView webview = new WebView(this);
WebSettings webSettings = webview.getSettings();
webSettings.setJavaScriptEnabled(true);
setContentView(webview);
InputStream fin;
try {
fin = getAssets().open("web_page_test.html");
byte[] buffer = new byte[fin.available()];
fin.read(buffer);
fin.close();
webview.loadData(new String(buffer), "text/html", "UTF-8");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
But it is showing that web page is down or not available error.
I am working on phonegap with android. i want to download a file from given url to my sd card.
**this is my index.html**
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=320; user-scalable=no" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>PhoneGap Demo With JQuery Mobile</title>
<link rel="stylesheet" href="jquery.mobile/jquery.mobile-1.0b2.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="pgandjqm-style-override.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="jquery.mobile/jquery-1.6.2.min"></script>
<script type="text/javascript" charset="utf-8" src="phonegap-1.0.0.js"></script>
<script src="jquery.mobile/jquery.mobile-1.0b2.js"></script>
<script type="text/javascript" charset="utf-8" src="main.js"></script>
<script type="text/javascript" charset="utf-8" src="downloader.js"></script>
<script type="text/javascript">
function down1()
{
window.plugins.downloader.downloadFile("http://192.168.1.214/sample/Winter.jpg","/mnt/sdcard/","archive.zip", false,
function(data){
if(data=="exist")
{
alert("File already exist");
}
else
{
alert("File saved on sd card")
}
},function(data){ alert("error is : "+data); });
}
</script>
</head>
<body>
<div data-role="button" onclick="down1();">Get data</div>
</body>
</html>
**this is my downloader.js**
function Downloader() {
}
Downloader.prototype.downloadFile = function(fileUrl,dirName,fileName,overwrite,win,fail) {
if(overwrite==false) overwrite="false";
else overwrite="true";
PhoneGap.exec(win, fail, "Downloader", "downloadFile", [fileUrl,dirName,fileName,overwrite]);
};
PhoneGap.addConstructor(function() {
console.log('=============i am in addConstructor================');
PhoneGap.addPlugin("downloader", new Downloader());
PluginManager.addService("Downloader","com.example.pgplugins.DownloaderPlugin");
});
**this is my Downloader.java**
package com.example.pgplugins.DownloaderPlugin;
//package com.example.pgplugins.downloaderPlugin;
/*
#author Mauro Rocco http://www.toforge.com
*/
import org.json.JSONArray;
import org.json.JSONException;
import android.util.Log;
import com.phonegap.DroidGap;
import com.phonegap.api.Plugin;
import com.phonegap.api.PluginResult;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class Downloader extends Plugin{
#Override
public PluginResult execute(String action, JSONArray args, String callbackId) {
System.out.println("=============i am in head class================");
if (action.equals("downloadFile")) {
try {
return this.downloadUrl(args.getString(0),args.getString(1),args.getString(2),args.getString(3));
} catch (JSONException e) {
return new PluginResult(PluginResult.Status.ERROR, "Param errrors");
}
}
else {
return new PluginResult(PluginResult.Status.INVALID_ACTION);
}
}
private PluginResult downloadUrl(String fileUrl, String dirName, String fileName, String overwrite){
try{
Log.d("DownloaderPlugin", "DIRECTORY CALLED /sdcard/"+dirName+" created");
File dir = new File("/sdcard/"+dirName);
if(!dir.exists()){
Log.d("DownloaderPlugin", "directory /sdcard/"+dirName+" created");
dir.mkdirs();
}
File file = new File("/sdcard/"+dirName+fileName);
if(overwrite.equals("false") && file.exists()){
Log.d("DownloaderPlugin", "File already exist");
return new PluginResult(PluginResult.Status.OK, "exist");
}
URL url = new URL(fileUrl);
HttpURLConnection ucon = (HttpURLConnection) url.openConnection();
ucon.setRequestMethod("GET");
ucon.setDoOutput(true);
ucon.connect();
Log.d("DownloaderPlugin", "download begining");
Log.d("DownloaderPlugin", "download url:" + url);
InputStream is = ucon.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
FileOutputStream fos = new FileOutputStream(file);
while ( (len1 = is.read(buffer)) > 0 ) {
fos.write(buffer,0, len1);
}
fos.close();
Log.d("DownloaderPlugin", "Download complete in" + fileName);
} catch (IOException e) {
Log.d("DownloaderPlugin", "Error: " + e);
return new PluginResult(PluginResult.Status.ERROR, "Error: " + e);
}
return new PluginResult(PluginResult.Status.OK, fileName);
}
}
**and this is my simple main class:-**
package com.example.pgplugins.DownloaderPlugin;
import com.phonegap.*;
import android.os.Bundle;
public class musicdownloader extends DroidGap {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.loadUrl("file:///android_asset/www/index.html");
}
}
when i run this program, it is not doing anything. This is my whole project code, so please tell me what is mistake i have done.
Did you follow the instructions from this page where: https://github.com/phonegap/phonegap-plugins/tree/master/Android/Downloader I've used this plugin without issues.
Also, I noticed the URL is an internal IP, does the phone or simulator have access to it?
To install the plugin, move downloader.js to your project's www folder and include a reference to it in your html files.
Create a folder called 'com/phonegap/plugins/downloader' within your project's src/ folder.
And copy the java file into that new folder.
Add the following to res/xml/plugins.xml file
There is a download method from URL in PhoneGap 1.3.0
hi i want to display my html image on android emulator, please help
package com.Htmlview;
import ja va.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.MessageFormat;
import android.app.Activity;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.webkit.WebView;
public class Htmlview extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.main);
WebView webview = new WebView(this);
setContentView(webview);
try {
String imageString="<html><body>" +
"<h2>Norwegian Mountain Trip</h2>" +
"<img src=\"C:/Users/Public/Pictures/Sample Pictures/pulpit.jpg\" alt=\"Pulpit rock\" width=\"304\" height=\"228\" /></body></html>";
AssetManager mgr = this.getAssets();
InputStream is = mgr.open("index3.html");
BufferedInputStream in = new BufferedInputStream(is); // read the contents of the file
webview.loadData(MessageFormat.format(imageString,arguments),"text/html", "UTF-8");
} catch (IOException e) {
e.printStackTrace();
}
}
}
You're never going to be able to access something on your workstation's hard drive from within Android. What you want to do is put the image into the assets folder in your Android app (which will then get bundled into the app) and link to it appropriately with file:///android_assets/. There are other ways of dealing with the issue, but that is the simplest.