I have used a CircleImageView using the 'de.hdodenhof:circleimageview:2.0.0' library.
code:
#Override
public boolean onMenuItemClick(MenuItem item){
switch(item.getItemId()){
case R.id.slot1:
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (cameraIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
ex.printStackTrace();
}
// Continue only if the File was successfully created
if (photoFile != null) {
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
startActivityForResult(cameraIntent, CAMERA_IMAGE_REQUEST);
}
}
return true;
case R.id.slot2:
Intent i = new Intent();
i.setType("image/*");
i.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(i, "Select Picture"), PICK_IMAGE_REQUEST);
return true;
default:
return true;
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "Widget_profile_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, // prefix
".jpg", // suffix
storageDir // directory
);
// Save a file: path for use with ACTION_VIEW intents
photoPath = "file:" + image.getAbsolutePath();
return image;
}
and in the onActivityResult() method:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Bitmap photo = BitmapFactory.decodeFile(photoPath);
profile = (ImageView)findViewById(R.id.profile_image);
profile.setImageBitmap(photo);
} else if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri uri = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
profile = (ImageView) findViewById(R.id.profile_image);
profile.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
i have created a menu option to select between Gallery and Camera where the Gallery seems to work perfectly, but Camera option doesn't set any image.
public void setImage(View view){
PopupMenu popupMenu = new PopupMenu(MainActivity.this, view);
popupMenu.setOnMenuItemClickListener(this);
popupMenu.getMenu().add(1, R.id.slot1, 1, "Camera");
popupMenu.getMenu().add(1,R.id.slot2,2,"Gallery");
popupMenu.show();
}
Could someone please help me with this?
Related
I have a website that is navigated from within a webview. One of the pages generates a ZIP file that is downloaded via a BLOB URL. I discovered that this is not supported by webview, so I have tried implementing this solution:
Download Blob file from Website inside Android WebViewClient
However, it is not working for me. Breakpoints in convertBase64StringToZipAndStoreIt are never hit.
UPDATE: I've found that I'm getting an HTTP 404. I've tried using blobUrl and blobUrl.substring(5) and the result is the same either way. The BLOBs are downloading fine in Chrome, though.
Webview setup:
private void launchWV() {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
1);
setContentView(R.layout.activity_self_service_launcher);
mWebView = (WebView) findViewById(R.id.activity_launcher_webview);
WebSettings webSettings = mWebView.getSettings();
webSettings.setBuiltInZoomControls(true);
webSettings.setSupportZoom(true);
webSettings.setJavaScriptEnabled(true);
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
webSettings.setSupportMultipleWindows(true);
webSettings.setAllowContentAccess(true);
webSettings.setAllowFileAccess(true);
webSettings.setAllowFileAccessFromFileURLs(true);
webSettings.setUserAgentString("Mozilla/5.0 (Android; X11; Linux x86_64) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/11.0.696.34 Safari/534.24" + getClientVersionInfo());
webSettings.setDomStorageEnabled(true);
webSettings.setLoadWithOverviewMode(true);
mWebView.setWebViewClient(new MyWebViewClient(this));
mWebView.setWebChromeClient(new MyWebChromeClient(this));
mWebView.addJavascriptInterface(new JavaScriptInterface(getApplicationContext()), "Android");
}
Function called from shouldOverrideUrlLoading() (only the else condition for BLOB URLs is of concern):
private boolean handleRequest(WebView view, String url) {
String filename;
if (!checkInternetConnection()) {
ShowNetworkUnavailableDialog(false);
return true;
}
else {
if (url.contains("view/mys") || url.contains("view/myy") || url.contains("blob") || url.contains("view/mye")) {
if (url.contains("view/mys")) {
filename = getResources().getString(R.string.mys_file_name).concat(".pdf");
} else if (url.contains("view/myy")) {
filename = getResources().getString(R.string.form_file_name).concat(".pdf");
} else if (url.contains("blob")) {
filename = getResources().getString(R.string.mys_file_name).concat(".zip");
} else {
filename = getResources().getString(R.string.mye_file_name).concat(".pdf");
}
if (!url.contains("blob")) {
String cookies = CookieManager.getInstance().getCookie(url);
DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(url));
downloadRequest.addRequestHeader("cookie", cookies);
downloadRequest.allowScanningByMediaScanner();
downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename);
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
try {
dm.enqueue(downloadRequest);
} catch (SecurityException e) {
Toast.makeText(getApplicationContext(), getResources().getString(R.string.connection_unavailable), Toast.LENGTH_LONG).show();
return false;
}
} else {
String blobURL = JavaScriptInterface.getBase64StringFromBlobUrl(url);
mWebView.loadUrl(blobURL);
}
Toast.makeText(getApplicationContext(), getResources().getString(R.string.download_message), Toast.LENGTH_LONG).show();
return true;
} else if (!url.contains(getMetadata(getApplicationContext(), HOSTNAME))) {
//Navigate to external site outside of webview e.g. Help site
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return true;
} else if(url.contains(getResources().getString(R.string.about_url))) {
mWebView.loadUrl(url);
return false;
} else {
if (savedInstanceState == null) {
mWebView.loadUrl(url);
}
return false;
}
}
}
JavaScriptInterface class:
public class JavaScriptInterface {
private Context context;
private NotificationManager nm;
public JavaScriptInterface(Context context) {
this.context = context;
}
#JavascriptInterface
public void getBase64FromBlobData(String base64Data) throws IOException {
convertBase64StringToZipAndStoreIt(base64Data);
}
public static String getBase64StringFromBlobUrl(String blobUrl){
if(blobUrl.startsWith("blob")){
return "javascript: var xhr = new XMLHttpRequest();" +
"xhr.open('GET', '" + blobUrl.substring(5) + "', true);" +
"xhr.setRequestHeader('Content-type','application/zip');" +
"xhr.responseType = 'blob';" +
"xhr.onload = function(e) {" +
" if (this.status == 200) {" +
" var blobZip = this.response;" +
" var reader = new FileReader();" +
" reader.readAsDataURL(blobZip);" +
" reader.onloadend = function() {" +
" base64data = reader.result;" +
" Android.getBase64FromBlobData(base64data);" +
" }" +
" }" +
"};" +
"xhr.send();";
}
return "javascript: console.log('It is not a Blob URL');";
}
private void convertBase64StringToZipAndStoreIt(String base64Zip) throws IOException {
final int notificationId = 1;
String currentDateTime = DateFormat.getDateTimeInstance().format(new Date());
final File dwldsPath = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS) + "/YourFileName_" + currentDateTime + "_.zip");
byte[] zipAsBytes = Base64.decode(base64Zip.replaceFirst("^data:application/zip;base64,", ""), 0);
FileOutputStream os;
os = new FileOutputStream(dwldsPath, false);
os.write(zipAsBytes);
os.flush();
if(dwldsPath.exists()) {
NotificationCompat.Builder b = new NotificationCompat.Builder(context, "MY_DL")
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentTitle("MY TITLE")
.setContentText("MY TEXT CONTENT");
nm = (NotificationManager) this.context.getSystemService(Context.NOTIFICATION_SERVICE);
if(nm != null) {
nm.notify(notificationId, b.build());
Handler h = new Handler();
long delayInMilliseconds = 5000;
h.postDelayed(new Runnable() {
public void run() {
nm.cancel(notificationId);
}
}, delayInMilliseconds);
}
}
}
}
One thing I know I am unclear on is what URL should be going into the call to xhr.open in the class.
I also tried using onDownloadStart with the same result.
Any insight is greatly appreciated!
I am trying to create a PDF from a server-side controller (report) (ireport) with ajax (and so on), and try to return the data to pdfwriter, servletoutputstream, and httpservletresponse. (I do not know exactly what I'm doing, but I'm doing it this way).
The original purpose was to send a server-side pdf file to the client, find the printer and print without a preview window.
Among them, I wrote 'application / pdf' on the server side and 'datetype: text' on the client side ajax (there is an error if I do not use ajax datatype: text)
If you print the results to the console, they will only be listed as unknown code.
Currently I am trying to put it into an iframe frame.
Question!
1. What should I do to use the text string sent to server -> client as pdf or script code?
(I have already asked you two weeks ago)
2. How do I send a pdf to server -> client? I would like to apply it to the screen by expressing it directly in code instead of downloading it. To print out.
ENG)>
// I used ajax only, because I dont know any other way
$.ajax({
url : "url",
data : JSON.stringify(data),
dataType : "text",
type: "POST",
contentType: 'application/json; charset=utf-8',
async : false,
success: function(result){
// I want to view PDF contents and directly print to PDF.
}
})
public Params createIbExItemLabelReport(HttpServletRequest resq, HttpSession session, Params inParams, HttpServletResponse resp) throws Exception{
Params outParams = ParamsFactory.createParams(inParams);
resp.setHeader("Cache-Control", "no-cache");
resp.setHeader("Pragma", "no-cache");
resp.setHeader("Expires", "0");
List<DataRow> list = new ArrayList<DataRow>();
String reportCd = "15";
String fileName = "ibExItemLabel"+reportCd+"Report";
String nullJpgFile = "";
int flag = 0;
int nullCheck = 0;
for(DataRow dr : inParams.getDataTable("dt_data")){
String imgName = "c:\\WMS\\LABEL\\FIAC021_" +reportCd + ".jpg";
File f = new File(imgName);
if (!f.isFile()) {
flag = 1;
if(nullCheck != 0){
nullJpgFile += ", ";
}
nullJpgFile += "FIAC021";
nullCheck++;
continue;
}
String bacodeCd = "FIAC02120180416001";
dr.setParam("imgName", imgName);
dr.setParam("bacodeCd", bacodeCd);
list.add(dr);
}
if(flag == 1){
outParams.setParam("ERROR_FILE", "제품코드 ["+nullJpgFile+"]의 라벨 사이즈" + reportCd + "인 파일이 존재하지않습니다.");
return outParams;
}
String appPath = session.getServletContext().getRealPath("/");
String pdfPath = null;
List<DataRow> list2 = new ArrayList<DataRow>();
for(int i = 0; i < list.size(); i++){
for(int j = 0; j < list.get(i).getInt("printQty"); j++){
list2.add(list.get(i));
}
}
Report report = new Report();
pdfPath = report.reportToPdf(session, list2, fileName);
outParams.setParam("fileName", pdfPath);
System.out.println("Found! FileName is ' : "+ pdfPath);
pdfPath = appPath + pdfPath;
pdfPath = pdfPath.replace("//", "/");
ServletOutputStream servletOutput = resp.getOutputStream();
PdfWriter pdfWriter = null;
StringBuffer pdfJs = null;
ByteArrayOutputStream pdfOutput = null;
InputStream pdfInput = null;
PdfReader pdfReader = null;
PdfStamper pdfStamper = null;
pdfOutput = convertPDFToByteArrayOutputStream(pdfPath);
int printCopy = 1;
if (printCopy == 0) {
printCopy = 1;
}
if (printCopy > 1) {
PdfCopyFields pdfPrintCopy = new PdfCopyFields(pdfOutput);
for (int i = 0; i < printCopy; i++) {
pdfPrintCopy.addDocument(new PdfReader(outputToInputStream(pdfOutput)));
}
pdfPrintCopy.close();
}
pdfInput = outputToInputStream(pdfOutput);
pdfReader = new PdfReader(pdfInput);
pdfStamper = new PdfStamper(pdfReader, servletOutput);
pdfWriter = pdfStamper.getWriter();
String printerNm = "SINDOH D410 Series PCL";
pdfWriter.setViewerPreferences(PdfWriter.HideMenubar | PdfWriter.HideToolbar | PdfWriter.HideWindowUI);
pdfJs = new StringBuffer();
pdfJs.append("var param=this.getPrintParams();\r");
pdfJs.append("param.printerName=\"").append(printerNm).append("\";\r");
pdfJs.append("param.interactive=param.constants.interactionLevel.silent;\r");
pdfJs.append("param.pageHandling=param.constants.handling.shrink;\r");
pdfJs.append("this.print(param);\r");
pdfJs.append("this.closeDoc();");
pdfWriter.addJavaScript(pdfJs.toString(), false);
servletOutput.flush();
Log.debug("servletOutput " );
if (pdfInput != null) {
try {
pdfInput.close();
} catch (Exception e) {
}
pdfInput = null;
}
if (pdfOutput != null) {
try {
pdfOutput.close();
} catch (Exception e) {
}
pdfOutput = null;
}
if (pdfReader != null) {
pdfReader.close();
pdfReader = null;
}
pdfWriter = null;
try {
if (pdfStamper != null) {
pdfStamper.close();
pdfStamper = null;
}
} catch (Exception e) {
}
resp.setHeader("Content-Disposition", "inline; filename="+pdfPath);
resp.setHeader("Content-Type", "application/pdf; charset=UTF-8");
resp.setCharacterEncoding("UTF-8");
Log.debug("before outParams " );
return outParams;
}
private InputStream outputToInputStream(ByteArrayOutputStream source) {
return new ByteArrayInputStream(source.toByteArray());
}
private static ByteArrayOutputStream convertPDFToByteArrayOutputStream(String FilePath) {
InputStream inputStream = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
inputStream = new FileInputStream(new File(FilePath));
byte[] buffer = new byte[1024];
baos = new ByteArrayOutputStream();
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
baos.write(buffer, 0, bytesRead);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return baos;
}
please answer my question
Can someone please help me how to read serial number ,Time stamp from two rfid readers connected to Raspbery Pi.There are some solutions in python, c# .Net but not in javascript.
I am trying to ímplement with Node Js but did not find any helpful resources for reading data from two rfid readers.
Many Thanks in advance
To read the data from multiple RFID readers you could use the following:
1. For reading the data from node:
There are a few projects out there reading that involve reading RFID tags from node, e.g. here and here.
Additionally also some npm packages, e.g. rfidreader.
There are even ones that are especially for RC522, e.g. rc522-c7z
2. For multiple readers:
Every reader should be provided by a unique serial port. This needs to be passed to the code from step 1.
this is a sample for windows 10 uwp app on raspbbery pi. you must be carefull using asynchronous programming on uwp consept.
using System;
using System.Collections.ObjectModel;
using System.Threading;
using System.Threading.Tasks;
using Windows.Devices.Enumeration;
using Windows.Devices.SerialCommunication;
using Windows.Storage.Streams;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
namespace Prova_comunicazione_seriale
{
public sealed partial class MainPage : Page
{
private SerialDevice serialPort = null;
DataWriter dataWriteObject = null;
DataReader dataReaderObject = null;
private ObservableCollection<DeviceInformation> listOfDevices;
private CancellationTokenSource ReadCancellationTokenSource;
public MainPage()
{
InitializeComponent();
btnAccendiled.IsEnabled = false;
btnSpegniled.IsEnabled = false;
listOfDevices = new ObservableCollection<DeviceInformation>();
ListAvailablePorts();
}
private async void ListAvailablePorts()
{
try
{
string aqs = SerialDevice.GetDeviceSelector();
var dis = await DeviceInformation.FindAllAsync(aqs);
for (int i = 0; i < dis.Count; i++)
{
listOfDevices.Add(dis[i]);
}
lstSerialDevices.ItemsSource = listOfDevices;
btnAccendiled.IsEnabled = true;
btnSpegniled.IsEnabled = true;
lstSerialDevices.SelectedIndex = -1;
}
catch (Exception ex)
{
tbkAllarmi.Text = ex.Message;
}
}
private async void ButtonClick(object sender, RoutedEventArgs e)
{
var buttonClicked = sender as Button;
switch(buttonClicked.Name)
{
case "btnSerialConnect":
SerialPortConfiguration();
break;
case "btnSerialDisconnect":
SerialPortDisconnect();
break;
case "btnAccendiled":
if (serialPort != null)
{
dataWriteObject = new DataWriter(serialPort.OutputStream);
await ManageLed("2");
}
if (dataWriteObject != null)
{
dataWriteObject.DetachStream();
dataWriteObject = null;
}
break;
case "btnSpegniled":
if (serialPort != null)
{
dataWriteObject = new DataWriter(serialPort.OutputStream);
await ManageLed("1");
}
if (dataWriteObject != null)
{
dataWriteObject.DetachStream();
dataWriteObject = null;
}
break;
case "btnPulse1000ms":
if (serialPort != null)
{
dataWriteObject = new DataWriter(serialPort.OutputStream);
await ManageLed("3");
}
if (dataWriteObject != null)
{
dataWriteObject.DetachStream();
dataWriteObject = null;
}
break;
case "btnPulse2000ms":
if (serialPort != null)
{
dataWriteObject = new DataWriter(serialPort.OutputStream);
await ManageLed("4");
}
if (dataWriteObject != null)
{
dataWriteObject.DetachStream();
dataWriteObject = null;
}
break;
}
}
private async void SerialPortConfiguration()
{
var selection = lstSerialDevices.SelectedItems;
if (selection.Count <= 0)
{
tbkAllarmi.Text = "Seleziona un oggetto per la connessione seriale!";
return;
}
DeviceInformation entry = (DeviceInformation)selection[0];
try
{
serialPort = await SerialDevice.FromIdAsync(entry.Id);
serialPort.WriteTimeout = TimeSpan.FromMilliseconds(1000);
serialPort.ReadTimeout = TimeSpan.FromMilliseconds(1000);
serialPort.BaudRate = 9600;
serialPort.Parity = SerialParity.None;
serialPort.StopBits = SerialStopBitCount.One;
serialPort.DataBits = 8;
serialPort.Handshake = SerialHandshake.None;
tbkAllarmi.Text = "Porta seriale correttamente configurata!";
ReadCancellationTokenSource = new CancellationTokenSource();
Listen();
}
catch (Exception ex)
{
tbkAllarmi.Text = ex.Message;
btnAccendiled.IsEnabled = false;
btnSpegniled.IsEnabled = false;
}
}
private void SerialPortDisconnect()
{
try
{
CancelReadTask();
CloseDevice();
ListAvailablePorts();
}
catch (Exception ex)
{
tbkAllarmi.Text = ex.Message;
}
}
private async Task ManageLed(string value)
{
var accendiLed = value;
Task<UInt32> storeAsyncTask;
if (accendiLed.Length != 0)
{
dataWriteObject.WriteString(accendiLed);
storeAsyncTask = dataWriteObject.StoreAsync().AsTask();
UInt32 bytesWritten = await storeAsyncTask;
if (bytesWritten > 0)
{
tbkAllarmi.Text = "Valore inviato correttamente";
}
}
else
{
tbkAllarmi.Text = "Nessun valore inviato";
}
}
private async void Listen()
{
try
{
if (serialPort != null)
{
dataReaderObject = new DataReader(serialPort.InputStream);
while (true)
{
await ReadData(ReadCancellationTokenSource.Token);
}
}
}
catch (Exception ex)
{
tbkAllarmi.Text = ex.Message;
if (ex.GetType().Name == "TaskCanceledException")
{
CloseDevice();
}
else
{
tbkAllarmi.Text = "Task annullato";
}
}
finally
{
if (dataReaderObject != null)
{
dataReaderObject.DetachStream();
dataReaderObject = null;
}
}
}
private async Task ReadData(CancellationToken cancellationToken)
{
Task<UInt32> loadAsyncTask;
uint ReadBufferLength = 1024;
cancellationToken.ThrowIfCancellationRequested();
dataReaderObject.InputStreamOptions = InputStreamOptions.Partial;
loadAsyncTask = dataReaderObject.LoadAsync(ReadBufferLength).AsTask(cancellationToken);
UInt32 bytesRead = await loadAsyncTask;
if (bytesRead > 0)
{
tbkStatusLed.Text = dataReaderObject.ReadString(bytesRead);
}
}
private void CancelReadTask()
{
if (ReadCancellationTokenSource != null)
{
if (!ReadCancellationTokenSource.IsCancellationRequested)
{
ReadCancellationTokenSource.Cancel();
}
}
}
private void CloseDevice()
{
if (serialPort != null)
{
serialPort.Dispose();
}
serialPort = null;
btnAccendiled.IsEnabled = false;
btnSpegniled.IsEnabled = false;
listOfDevices.Clear();
}
}
}
}
This line
dojs("jQuery('#result').html('"+encoded+"')");
is not working and not displaying encoded String on WebView. Other codes are working without problem.
If I replace
dojs("jQuery('#result').html('"+encoded+"')");
line with
Toast.makeText(this, encoded, Toast.LENGTH_SHORT).show();
it displays encoded String on Toast.
public void dojs(String command) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
webView.evaluateJavascript(command, null);
}
else {
webView.loadUrl("javascript:" + command);
}
}
public String getRealPathFromURI(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1001 && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri selectedImage = data.getData();
File sfile = new File(getRealPathFromURI(selectedImage));
int file_size = Integer.parseInt(String.valueOf(sfile.length()/1024));
if (file_size>200) {
dojs("jQuery('#result').html('File size is more than 200 kb')");
} else {
ContentResolver cR = getApplicationContext().getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
String type = mime.getExtensionFromMimeType(cR.getType(selectedImage));
if (type=="jpeg" || type=="jpg" || type=="png") {
try {
InputStream inputStream = new FileInputStream(sfile);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
if (type=="png") {
bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
} else {
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
}
byte[] byteArray = byteArrayOutputStream .toByteArray();
String encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);
dojs("jQuery('#result').html('"+encoded+"')");
} catch (FileNotFoundException e) {
dojs("jQuery('#result').html('"+e.getMessage()+"')");
} catch (IOException e) {
dojs("jQuery('#result').html('"+e.getMessage()+"')");
}
} else {
dojs("jQuery('#result').html('png or jpg is accepted')");
}
}
}
}
There is not any error on logcat. please advice.
I wanna intercept all of http request for adding header to my request and build response. I used all algorithm and libraries ( okHttp, HttpUrlConnection) but no hope :(
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
String urlString = request.getUrl().toString();
if (Build.VERSION.SDK_INT >= 21) {
try {
URL url = new URL(urlString);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestProperty(Constants.KEY_HEADER, Constants.VALUE_KEY_HEADER);
if (request.getMethod().equals("POST")) {
urlConnection = getPostData(urlConnection, request);
}
InputStream in;
int statusCode = urlConnection.getResponseCode();
if (statusCode == 400 || statusCode == 401 || statusCode == 404) {
in = urlConnection.getErrorStream();
} else {
in = urlConnection.getInputStream();
}
String typeMime = urlConnection.getHeaderField("Content-Type");
if (typeMime == null){
typeMime = "text/html";
}
if (urlString.equals("fontawesome-webfont.woff")) {
typeMime = "application/font-woff";
}
if (typeMime.contains("text/html")) {
typeMime = "text/html";
} else if (typeMime == null || typeMime.contains("application/font-woff")) {
typeMime = "application/font-woff";
}
return new WebResourceResponse(typeMime, "utf-8", in);
} catch (IOException ioe) {
Log.d(Constants.LOG_TAG, "IOException : " + ioe.getMessage());
return null;
}
} else {
return null;
}
private HttpURLConnection getPostData(HttpURLConnection urlConnection, WebResourceRequest request) throws IOException {
urlConnection.setReadTimeout(10000);
urlConnection.setConnectTimeout(15000);
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
for (String key : request.getRequestHeaders().keySet()) {
String valueKey = request.getRequestHeaders().get(key);
Log.d("key is = ", "" + key + " and value = " + valueKey);
urlConnection.setRequestProperty(key, valueKey);
}
urlConnection.setRequestProperty(URLCache.KEY_X_CSRF_Token, URLCache.VALUE_X_CSRF_Token);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("signin[username]", "dfgdfg"));
params.add(new BasicNameValuePair("signin[password]", "dfgdfg"));
OutputStream os = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "utf-8"));
writer.write(getQuery(params));
writer.flush();
writer.close();
os.close();
urlConnection.connect();
return urlConnection;
}
For "GET" Method its work fine but not method "POST" in forum action