How to send data to server javascript using get request - javascript

I'm new to Java and Android development and try to create a simple app which should contact a web server A and send,add some data to text using a http get.
I have simple HTML code with some javascript (server A)
<html>
<head>
<title>This is my Webpage</title>`enter code here`
<h1>My Example</h1>
<script>
function myFunction(){
document.getElementById("myid").value=$ab;
}
</script
</head>
<body onload="myFunction()">
<input id="myid" type="text" />
</body>
</html>
and i have Android code to send http request to a local (server A)
public class MainActivity extends Activity {
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=(Button) findViewById(R.id.click);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String url = "http://www.localhost/tuan/example.html";
MyCommandTask task = new MyCommandTask();
task.execute(url);
}
});
}
public class MyCommandTask extends AsyncTask<String,Void,Document>
{
#Override
protected Document doInBackground(String... params) {
String url=params[0];
try {
HttpGet httpGet = new HttpGet(url);
}
catch (Exception ex)
{
ex.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Document document) {
super.onPostExecute(document);
}
}
}``
Now i want send text data and show result in text on (server A).
Please anyone help me.

Check this out dude. http://developer.android.com/training/basics/network-ops/connecting.html#download . Since you already got url string in doInBackground() method , use below code
InputStream is = null;
// Only display the first 500 characters of the retrieved
// web page content.
int len = 500;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
int response = conn.getResponseCode();
Log.d(DEBUG_TAG, "The response is: " + response);
is = conn.getInputStream();
// Convert the InputStream into a string
String contentAsString = readIt(is, len);
return contentAsString;
// Makes sure that the InputStream is closed after the app is
// finished using it.
} finally {
if (is != null) {
is.close();
}
}
Don't forget to change return type of doInBackground() to String as well. If you wanna go further , try grab volley which is one of the awesome network library https://developer.android.com/training/volley/index.html

Here is how you can post data to server. Put these line inside doInBackground()
private static final String POST_PARAMS = "userName=Pankaj";
URL obj = new URL(POST_URL);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
// For POST only - START
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(POST_PARAMS.getBytes());
os.flush();
os.close();
// For POST only - END
int responseCode = con.getResponseCode();
System.out.println("POST Response Code :: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { //success
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// print result
System.out.println(response.toString());
} else {
System.out.println("POST request not worked");
}
Here is the source

Related

android studio webview to use javascript for the link

this question is how to apply java script by link to webview https://dl.dropboxusercontent.com/s/lmibwymtkebspij/background.js after the page is fully loaded the background should turn green here is a sample code for loading the page
webView = findViewById(R.id.Web);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebChromeClient(new MyWebChromeClient());
thank you in advance
maybe someone will come in handy load the text of the script into the script variable using get request to link the address of the script like this:
#SuppressLint("StaticFieldLeak")
class ProgressTask extends AsyncTask<String, Void, String> {
#Override
public String doInBackground(String... path) {
try {
content = getContent(path[0]);
} catch (IOException ex) {
content = ex.getMessage();
}
return content;
}
#Override
public void onPostExecute(String content) {
scriptbg = content;
Log.d("debug", scriptbg);
}
public String getContent(String path) throws IOException {
BufferedReader reader = null;
try {
URL url = new URL(path);
HttpsURLConnection c = (HttpsURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setReadTimeout(10000);
c.connect();
reader = new BufferedReader(new InputStreamReader(c.getInputStream()));
StringBuilder buf = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
buf.append(line + "\n");
}
return (buf.toString());
} finally {
if (reader != null) {
reader.close();
}
}
}
then we apply the script to our webView when the page is fully loaded like this:
public void onPageFinished(WebView view, String url) {
webView.loadUrl("javascript:" + Script);
Log.d("debug", "finish");
}

How to display and interact with OKHTTP html response in android Studio using webview or Web browser

I am building an android app. I have build a request using OKHTTP and I get the response as a string composed of html css and js content. This response is actualy a form that the user must use to allow the app to communicate with a given website.
Now I want the user to be able to see that response as an html page and clicks on a button to allow the communictaion. Only problem I don't know how to display that response as an html in webview or in the web browser.
From the MainActivity:
Authenticate myAouth = new Authenticate("myCostumerKey","mySecretKey");
try {
myResponse=myAouth.run("myUrlHere");
//System.out.println( myResponse);
} catch (Exception e) {
e.printStackTrace();
}
the Autheticate class
public class Authenticate {
private final OkHttpClient client;
String[] myResponse =new String[2];
public Authenticate( final String consumerKey, final String consumerSecret) {
client = new OkHttpClient.Builder()
.authenticator(new Authenticator() {
#Override public Request authenticate(Route route, Response response) throws IOException {
if (response.request().header("Authorization") != null) {
return null; // Give up, we've already attempted to authenticate.
}
System.out.println("Authenticating for response: " + response);
System.out.println("Challenges: " + response.challenges());
String credential = Credentials.basic(consumerKey, consumerSecret);
Request myRequest =response.request().newBuilder()
.header("Authorization", credential)
.build();
HttpUrl myURL = myRequest.url();
myResponse[0]= String.valueOf(myURL);
return myRequest;
}
})
.build();
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
public String[] run(String url) throws Exception {
Request request = new Request.Builder()
.url(url)
.build();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
myResponse[1]=response.body().string();
System.out.println(" URL is "+myResponse[0]+" my response body is "+myResponse[1]);
}
return myResponse;
}}
Any help would be apriciated.
Kind Regards
You can use the following code to convert the String to HTML and then display it in a WebView
try {
String html = new String(response, "UTF-8");
String mime = "text/html";
String encoding = "utf-8";
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.loadDataWithBaseURL(null, html, mime, encoding, null);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}

Can't fetch dynamically changed HTML content(by JavaScript) in android using AsyncTask.

I'm using python script to dynamically change the content of my web-page. The link of the web page is: [HERE]
The web page contains table which has two columns:
1) Values between 1 to 5.
2) And the time when it is uploaded on the page.
It is displayed dynamically by the JavaScript on the page. See the source of the page opening the link above.
Now I'm creating a android application which displays the values in the text view by fetching that page and parsing the HTML. But the page source only contains JavaScript code. So whenever I fetch the HTML, it only displays the JavaScript even if it contains more than one rows with values.
My question is how to fetch those values dynamically?
I'm using AsyncTask and scheduling it every 10 seconds. My code is:
public class MainActivity extends AppCompatActivity {
TextView et ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et = (TextView) findViewById(R.id.editText);
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[]{"https://rasppiclient.herokuapp.com/"});
callAsynchronousTask();
}
public void callAsynchronousTask() {
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
DownloadWebPageTask performBackgroundTask = new DownloadWebPageTask();
// PerformBackgroundTask this class is the class that extends AsynchTask
performBackgroundTask.execute(new String[]{"https://rasppiclient.herokuapp.com/"});
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 10000); //execute in every 50000 ms
}
public class DownloadWebPageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
}
}
return response;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Toast.makeText(MainActivity.this,s,Toast.LENGTH_LONG).show();
}
}}
This does not work with DefaultHttpClient. What you could to is the evaluate the javascript and then get the content with AndroidJSCore.
JSContext context = new JSContext();
context.evaluateScript(yourJsString);
context.property("getWhatYouWantHere");
An example from the github looks like this
JSContext context = new JSContext();
context.evaluateScript("a = 10");
JSValue newAValue = context.property("a");
System.out.println(df.format(newAValue.toNumber())); // 10.0
String script =
"function factorial(x) { var f = 1; for(; x > 1; x--) f *= x; return f; }\n" +
"var fact_a = factorial(a);\n";
context.evaluateScript(script);
JSValue fact_a = context.property("fact_a");
System.out.println(df.format(fact_a.toNumber())); // 3628800.0

Adding new line to database and unexpectedly closes app

I am currently a beginner to android programming and right now I am developing an app to make a JSON connection to a LAMP server and display the JSON data. The connection is currently successfully being made and i can create product and see it in the db but the app unexpectedly close's every time, can someone help and point me in the right direction, will add more if needed.
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
is = null;
jObj = null;
json = "";
// Making HTTP request
try {
Log.i("url", url);
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
Log.i("url", url);
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
Log.i("url", url);
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Log.i("Stage 1", "Stage 1");
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
Log.i("1 ", line);
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
Log.i("Stage 2", "Stage 2");
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
Log.i("Stage 3", "Stage 3");
// return JSON String
return jObj;
}
public class NewProductActivity extends Activity {
// Progress Dialog
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText inputName;
EditText inputPrice;
EditText inputDesc;
// url to create new product
private static String url_create_product = "http://192.168.1.165/wp-admin/android_connect/create_product.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_product);
// Edit Text
inputName = (EditText) findViewById(R.id.inputName);
inputPrice = (EditText) findViewById(R.id.inputPrice);
inputDesc = (EditText) findViewById(R.id.inputDesc);
// Create button
Button btnCreateProduct = (Button) findViewById(R.id.btnCreateProduct);
// button click event
btnCreateProduct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// creating new product in background thread
new CreateNewProduct().execute();
}
});
}
/**
* Background Async Task to Create new product
* */
class CreateNewProduct extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NewProductActivity.this);
pDialog.setMessage("Creating Product..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
#SuppressWarnings("ResourceType")
protected String doInBackground(String... args) {
String name = inputName.getText().toString();
String price = inputPrice.getText().toString();
String description = inputDesc.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("price", price));
params.add(new BasicNameValuePair("description", description));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
logcat 09-16 10:47:27.285
23440-23458/com.example.androidhive.productjsonphp I/OpenGLRenderer﹕
Initialized EGL, version 1.4 09-16 10:47:27.287
23440-23458/com.example.androidhive.productjsonphp D/OpenGLRenderer﹕
Enabling debug mode 0 09-16 10:47:28.372
23440-23440/com.example.androidhive.productjsonphp V/Monotype﹕
SetAppTypeFace- try to flip, app =
com.example.androidhive.productjsonphp 09-16 10:47:28.372
23440-23440/com.example.androidhive.productjsonphp V/Monotype﹕
Typeface getFontPathFlipFont - systemFont = default#default 09-16
10:47:28.449 23440-23471/com.example.androidhive.productjsonphp
I/url﹕
http://api.androidhive.info/android_connect/get_all_products.php 09-16
10:47:28.451 23440-23471/com.example.androidhive.productjsonphp
I/url﹕
http://api.androidhive.info/android_connect/get_all_products.php?
09-16 10:47:28.674 23440-23458/com.example.androidhive.productjsonphp
D/OpenGLRenderer﹕ endAllStagingAnimators on 0xb7f62f50
(RippleDrawable) with handle 0xb7f75e00 09-16 10:47:29.017
23440-23471/com.example.androidhive.productjsonphp I/Stage 1﹕ Stage 1
09-16 10:47:29.022 23440-23471/com.example.androidhive.productjsonphp
I/1﹕ Unknown database 'download_androidhive' 09-16 10:47:29.022
23440-23471/com.example.androidhive.productjsonphp I/Stage 2﹕ Stage 2
09-16 10:47:29.023 23440-23471/com.example.androidhive.productjsonphp
E/JSON Parser﹕ Error parsing data org.json.JSONException: Value
Unknown of type java.lang.String cannot be converted to JSONObject
09-16 10:47:29.023 23440-23471/com.example.androidhive.productjsonphp
I/Stage 3﹕ Stage 3 09-16 10:47:29.029
23440-23471/com.example.androidhive.productjsonphp E/AndroidRuntime﹕
FATAL EXCEPTION: AsyncTask #1
Process: com.example.androidhive.productjsonphp, PID: 23440
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.toString()' on a
null object reference
at com.example.androidhive.productjsonphp.AllProductsActivity$LoadAllProducts.doInBackground(AllProductsActivity.java:130)
at com.example.androidhive.productjsonphp.AllProductsActivity$LoadAllProducts.doInBackground(AllProductsActivity.java:105)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818) 09-16 10:47:29.528 23440-23440/com.example.androidhive.productjsonphp
E/WindowManager﹕ android.view.WindowLeaked: Activity
com.example.androidhive.productjsonphp.AllProductsActivity has leaked
window com.android.internal.policy.impl.PhoneWindow$DecorView{78d7c4f
V.E..... R......D 0,0-479,116} that was originally added here
at android.view.ViewRootImpl.(ViewRootImpl.java:363)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:261)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:298)
at com.example.androidhive.productjsonphp.AllProductsActivity$LoadAllProducts.onPreExecute(AllProductsActivity.java:117)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
at android.os.AsyncTask.execute(AsyncTask.java:535)
at com.example.androidhive.productjsonphp.AllProductsActivity.onCreate(AllProductsActivity.java:57)
at android.app.Activity.performCreate(Activity.java:5975)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2269)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2378)
at android.app.ActivityThread.access$800(ActivityThread.java:147)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1281)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5255)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:838)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:651) 09-16
10:47:34.521 23440-23471/com.example.androidhive.productjsonphp
I/Process﹕ Sending signal. PID: 23440 SIG: 9
Your try to parse Json from String "json" but this "json" string give null value, if Please check "json" string is null, before use it.
so, try this code
if(json!=null && !json.equals(""))
{
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
)else{
Toast.makeText(context, "json is empty", Toast.LENGTH_LONG).show();
}

Get content string (not source code) of webPage on Android

I made a Javascript page to generate a JSON object for read it then from Android device.
I read it with the following code
StringBuilder stringBuilder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200){
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null){
stringBuilder.append(line);
}
} else {
Log.e("JSON", "Failed to donwload file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
The problem is that this code returns the source code of the webpage, and the source code is the script in Javascript, not the JSON string generated after execute it.
I need the JSON string and I need use Javascript to generate the JSON string because I access to an external service.
I haven't find any solution for this. I don't care if the possible solution involves the server or the Android terminal.
Thanks.
String myresponse=Html.escapeHtml(YourStringHere);
Try this.
private class MyJavaScriptInterface {
private MyJavaScriptInterface () {
}
public void setHtml(String contentHtml) {
//here you get the content html
}
}
private WebViewClient webViewClient = new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
view.loadUrl("javascript:window.ResponseChecker.setHtml"
+ "(document.body.innerHTML);");
}
}

Categories

Resources