Request a HTTP Request with session from a WebView - javascript

I am porting my website to Android using Webview. In my Android app, there is an indicator that shows the number of items in the cart. In Javascript, I call a function named refreshShoppingBadge, that request an AJAX request to update the number. So I write the Javascript Interface for Webview like this:
#JavascriptInterface
public void refreshShoppingBadge(final String pUrl) {
if (pUrl == null) {
return;
}
final DefaultHttpClient request = new DefaultHttpClient();
try {
final HttpResponse response = request.execute(new HttpGet(
this.rootContext + pUrl));
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
final ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
Utils.changeTabIndicator(this.tabCartIndex,
String.format(this.tabCartContent, out.toString()));
} else {
Utils.alertNetworkProblem(this.context);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
Log.e("Shopping", e.getMessage());
} catch (IOException e) {
e.printStackTrace();
Log.e("Shopping", e.getMessage());
}
}
However, the result is always 0, because HttpClient send the request with a new session, so there is nothing in the cart.
Can I "only get result" from the webview, or somehow get its session to request?

Related

block image/jpeg;base64 using url filter

I using WebViewClient's shouldInterceptRequest function to filter photos in my android webView.
The problem
I'm trying to block google's base64 URL photos (like:data:image/jpeg;base64,+) using this regex data:image/(jpg|png|jpeg);base64, but without success.
I done my research and found that:
these base64 background images are injected with JS.
but I don't know to continue.
my code:
#Override
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
String url = request.getUrl().toString();
if (imgCheck(url,res))
{
return new WebResourceResponse(
BrowserUnit.MIME_TYPE_TEXT_PLAIN,
BrowserUnit.URL_ENCODING,
new ByteArrayInputStream("".getBytes())
);
}
return super.shouldInterceptRequest(view, request);
}
private static boolean isImage(String url, Resources res) {
BufferedReader imageUrlRegex = openRawFile(res, R.raw.image_regex);
try {
String line = imageUrlRegex.readLine();
while (line != null) {
Pattern pattern = Pattern.compile(line);
if (pattern.matcher(url).find())
return true;
line = imageUrlRegex.readLine();
}
} catch (IOException e) {
e.printStackTrace();
return true;
}
return false;
}
data:image/(jpg|png|jpeg|svg|ico|webp|tif|tiff|bmp|eps|apng|avif|jfif|pjpeg|pjp|cur);base64,
**note : I tried block like this return url.contains("data:image"); still nothing

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();
}
}

Tableau Integration with Web project

I am doing Tableau integration with web project using java script api. I have configured my ip in tableau server using commnad :tabadmin set wgserver.trusted_hosts "" and respective commands .But I am not able to get the ticket, ended up with -1. I have followed all configuration steps.
public class TableauServlet extends javax.servlet.http.HttpServlet {
private static final long serialVersionUID = 1L;
public TableauServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
final String user = "raghu";
final String wgserver = "103.xxx.xxx.xx";
final String dst = "views/Regional/College?:iid=1";
final String params = ":embed=yes&:toolbar=yes";
String ticket = getTrustedTicket(wgserver, user, request.getRemoteAddr());
if ( !ticket.equals("-1") ) {
response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
response.setHeader("Location", "http://" + wgserver + "/trusted/" + ticket + "/" + dst + "?" + params);
}
else
// handle error
throw new ServletException("Invalid ticket " + ticket);
}
// the client_ip parameter isn't necessary to send in the POST unless you have
// wgserver.extended_trusted_ip_checking enabled (it's disabled by default)
private String getTrustedTicket(String wgserver, String user, String remoteAddr)
throws ServletException
{
OutputStreamWriter out = null;
BufferedReader in = null;
try {
// Encode the parameters
StringBuffer data = new StringBuffer();
data.append(URLEncoder.encode("username", "UTF-8"));
data.append("=");
data.append(URLEncoder.encode(user, "UTF-8"));
data.append("&");
data.append(URLEncoder.encode("client_ip", "UTF-8"));
data.append("=");
data.append(URLEncoder.encode(remoteAddr, "UTF-8"));
// Send the request
URL url = new URL("http://" + wgserver + "/trusted");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
out = new OutputStreamWriter(conn.getOutputStream());
out.write(data.toString());
out.flush();
// Read the response
StringBuffer rsp = new StringBuffer();
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ( (line = in.readLine()) != null) {
rsp.append(line);
}
return rsp.toString();
} catch (Exception e) {
throw new ServletException(e);
}
finally {
try {
if (in != null) in.close();
if (out != null) out.close();
}
catch (IOException e) {}
}
}
}
I think you are missing 'target_site' parameter in your URL where you get trusted ticket, its needed if you don't have the 'views/Regional/College' in your default site.
I had gone through a lot of frustration with the '-1' ticket too!
One thing you might try is restarting the tableau server after you have added your web server IP to the trusted_hosts of tableau.
Another thing we ended up doing was adding both the internal ip and external ip of the web server to trusted_hosts on tableau. Since you are using 103.xxx.xxx.xx as your tableau server I am assuming both servers live on the same internal network. You might try that if everything else fails.
My code is almost exactly same as yours and works fine. So if your problem persists, it must be something related to configuration.
here is my code:
private String getAuthenticationTicket(String tableauServerUserName,String tableauServerUrl, String targetSite) {
OutputStreamWriter out = null;
BufferedReader in = null;
try {
StringBuffer data = new StringBuffer();
data.append(URLEncoder.encode("username", Constant.UTF_8));
data.append("=");
data.append(URLEncoder.encode(tableauServerUserName, Constant.UTF_8));
data.append("&");
data.append(URLEncoder.encode("target_site", Constant.UTF_8));
data.append("=");
data.append(URLEncoder.encode(targetSite, Constant.UTF_8));
URL url = new URL(tableauServerUrl + "/" + "trusted");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
out = new OutputStreamWriter(conn.getOutputStream());
out.write(data.toString());
out.flush();
StringBuffer rsp = new StringBuffer();
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
rsp.append(line);
}
return rsp.toString();
} catch (Exception ex) {
//log stuff, handle error
return null;
} finally {
try {
if (in != null)
in.close();
if (out != null)
out.close();
} catch (IOException ex) {
//log stuff, handle error
}
}
}

isConnected failed: ECONNREFUSED (Connection refused)

I try to transfer data between phones via wifi-direct and my code works fine everyfirst time I run through it. However, after I close all the sockets in both client and server and try to connect the socket again, it gives me this Exception. Also, after I lock the screen of the server phone and unlock it, I can built up the connection once again. Can someone familar with socket give me any advice?
This shouldn't be about wrong IP address/port right?
CODE for Client phone
protected void onHandleIntent(Intent intent) {
Context context = getApplicationContext();
if (intent.getAction().equals(ACTION_SEND_FILE)) {
if(!socket.isConnected())
{
String host = intent.getExtras().getString(
EXTRAS_GROUP_OWNER_ADDRESS);
int port = intent.getExtras().getInt(EXTRAS_GROUP_OWNER_PORT);
try {
socket.bind(null);
InetSocketAddress MyAddress = new InetSocketAddress(host, port);
socket.connect(MyAddress, SOCKET_TIMEOUT);
}
catch(IOException e) {
Log.e(TAG, e.getMessage());
}
}
try{
/*returns an output stream to write data into this socket*/
OutputStream stream = socket.getOutputStream();
String count = String.valueOf(_count);
stream.write(count.getBytes());
} catch (IOException e) {
Log.e(TAG, e.getMessage());
} finally {
if (socket != null) {
if (socket.isConnected()) {
try {
InputStream is = socket.getInputStream();
socket.shutdownOutput(); // Sends the 'FIN' on the network
while (is.read() >= 0) ; // "read()" returns '-1' when the 'FIN' is reached
socket.close();
}
catch (IOException e) {
// Give up
e.printStackTrace();
}
}
}
}
}
}
CODE for Server phone
protected String doInBackground(Void... params) {
try {
ServerSocket serverSocket = new ServerSocket(8888);
Socket client = serverSocket.accept();
InputStream inputstream = client.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int i;
while ((i = inputstream.read()) != -1) {
baos.write(i);
}
String str = baos.toString();
client.shutdownOutput(); // Sends the 'FIN' on the network
while (inputstream.read() >= 0) ; // "read()" returns '-1' when the 'FIN' is reached
client.close(); // Now we can close the Socket
serverSocket.close();
return str;
} catch (IOException e) {
return null;
}
}

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