Convert files xls to pdf with Android and http apache mime - android

That such a good night, I write to ask if I could help and to coregir the following code, which right through a listView and presslong, took the path of the file, to try and turn the service:
of:
http://www.convertapi.com/excel-pdf-api
I have not to use a webview, or could use a hidden way
thank
code is:
mPrefs = getSharedPreferences("RutaPath", Context.MODE_PRIVATE);
String rutasave = mPrefs.getString("Externa", "");
String resultcode = "0";
HttpPost httppost = new HttpPost("http://do.convertapi.com/Excel2Pdf/json");
MultipartEntity entity = new MultipartEntity( HttpMultipartMode.BROWSER_COMPATIBLE );
// For File parameters
file=new File(rutasave+"prueba.xls");
//Toast.makeText(this,"cargando: " +rutasave+"prueba.xls",Toast.LENGTH_SHORT).show();
outputDir=rutasave;
entity.addPart("file", new FileBody(file, "binary/octet-stream"));//"file"
httppost.setEntity( entity );
HttpClient httpclient = new DefaultHttpClient();
// return new Boolean(true);//eliminar despues
try {
HttpResponse response = httpclient.execute(httppost);
Header rcHeader = response.getFirstHeader("result");
if(rcHeader != null){
resultcode = rcHeader.getValue();
if("True".equals(resultcode)){
filesize = response.getFirstHeader("filesize").getValue();
filename = response.getFirstHeader("OutputFileName").getValue();
//Toast.makeText(this,"Archivo: " +filename,Toast.LENGTH_SHORT).show();
HttpEntity hentity = response.getEntity();
if(hentity != null){
InputStream istream = hentity.getContent();
File file = new File(outputDir+filename+".pdf");//outputDir File.separator
FileOutputStream ostream = new FileOutputStream(file);
byte[] b = new byte[1024];
int num = 0;
while( (num = istream.read(b, 0, b.length)) > 0)
ostream.write(b, 0, num);
istream.close();
ostream.flush();
ostream.close();
return new Boolean(true);
}
}
}
} catch (ClientProtocolException e) {

Related

Pdf download using HttpPost in Android shows incorrect PDF format

Iam trying to download a file using HttpPost. But after downloading using the below code, it shows me invalid pdf format. Please help me rectify this issue?
private void downLoadFile(String Filename) throws ClientProtocolException, IOException{
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(URL);
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
Log.i(TAG, "Filename: " + Filename);
pairs.add(new BasicNameValuePair("Filename:", Filename));
post.setEntity(new UrlEncodedFormEntity(pairs));
HttpResponse response = client.execute(post);
InputStream is = response.getEntity().getContent();
FileOutputStream fos = new FileOutputStream(new File( Environment.getExternalStorageDirectory().getAbsolutePath() +"/omniware/retail/"+Filename));
int read = 0;
byte[] buffer = new byte[1048576];
while((read = is.read(buffer)) > 0){
fos.write(buffer, 0, read);
}
fos.flush();
fos.close();
is.close();
showPdf(Filename);
Log.i(TAG, "Response Code: " + Integer.toString(response.getStatusLine().getStatusCode()));
}
public void showPdf(String Filename){
File file2 = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +"/omniware/retail/"+Filename);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(file2);
intent.setDataAndType(uri, "application/pdf");
startActivity(intent);
}

How to send aes 256 encrypted data to a web server?

I successfully encrypted an audio file on my sd card and placed that encrypted file again in my sd card. I used the below code to save my file in sd card.
SecretKeySpec sks = new SecretKeySpec("MyDifficultPassw".getBytes(), algorithm);
Cipher cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.ENCRYPT_MODE, sks);
CipherOutputStream cos = new CipherOutputStream(outputStream, cipher);
int b;
byte[] d = new byte[8];
while((b = inputStream.read(d)) != -1){
cos.write(d, 0, b);
But now i want to encrypt and send that file to a web server without saving it in sd card. I tried using the above code, but it says
The constructor CipherOutputStream(HttpPost, Cipher) is undefined. Change type of httpPost to OutputStream.
How can i send it. Please help.
This is the method i use to send the original file to server:
public void uploadFile(String outfile) {
int count;
try{
// the URL where the file will be posted
String postReceiverUrl = "The url where i want to send";
// new HttpClient
HttpClient httpClient = new DefaultHttpClient();
// post header
HttpPost httpPost = new HttpPost(postReceiverUrl);
//outfile is the original file in sd card.
File file = new File(outfile);
FileBody fileBody = new FileBody(file);
String file_name_de = "MA_"+u_name.subSequence(0, 3)+u_id;
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("frm_file", fileBody);
reqEntity.addPart("frm_user_id", new StringBody(String.valueOf(u_id), Charset.forName("UTF-8")));
reqEntity.addPart("frm_token", new StringBody(u_token));
reqEntity.addPart("frm_file_name", new StringBody(file_name_de, Charset.forName("UTF-8")));
httpPost.setEntity(reqEntity);
// execute HTTP post request
HttpResponse response = httpClient.execute(httpPost);
//get the InputStream
InputStream is=fileBody.getInputStream();
byte[] data = baos.toByteArray();
//create a buffer
byte data[] = new byte[1024];//1024
//this updates the progress bar
long total=0;
while((count=is.read(d))!=-1){
total+=count;
publishProgress((int)(total*100/file.length()));
}
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
#SuppressWarnings("unused")
String responseStr = EntityUtils.toString(resEntity).trim();
//Log.d("Response: ", responseStr);
}
file.delete();
} catch (NullPointerException e) {
//e.printStackTrace();
} catch (Exception e) {
//e.printStackTrace();
}
}
You probably want to wrap the CipherOutputStream in a ByteArrayOutputStream like this:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
CipherOutputStream cos = new CipherOutputStream(baos, cipher);
int b;
byte[] d = new byte[BUFFER_SIZE];
while((b = inputStream.read(d)) != -1){
cos.write(d, 0, b);
}
byte[] data = baos.toByteArray();
// now send data to server
This way you have the encrypted data packaged in a byte[], ready for you to shoot off to the server.

android multipart image upload with json object

I want to upload images to server.
Here is the code,
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(Constants.yigit);
Charset chars = Charset.forName("UTF-8"); // Setting up the encoding
MultipartEntity reqEntity = new MultipartEntity();
StringBody jsonBody = new StringBody(getNewDemandRequestParams(), "application/json",null);
FormBodyPart jsonBodyPart = new FormBodyPart("data", jsonBody);
reqEntity.addPart(jsonBodyPart);
if (getMainActivity().getImagesSavedData(0).size() > 0) {
for (int i = 0; i < getMainActivity().getImagesSavedData(0).size(); i++) {
File _file = new File(getMainActivity().getImagesSavedData(0).get(i).getFilePath());
FileBody _fileBody = new FileBody(_file, "image/jpg", "UTF-8");
FormBodyPart fileBodyPart = new FormBodyPart(getMainActivity().getImagesSavedData(0).get(i).getImageName().replace(".jpg", ""), _fileBody);
reqEntity.addPart(fileBodyPart);
reqEntity.addPart(getMainActivity().getImagesSavedData(0).get(i).getImageName().replace(".jpg",""), _fileBody);
}
}
post.setEntity(reqEntity);
String result = EntityUtils.toString(reqEntity);
Log.e("rsul", result);
HttpResponse response = client.execute(post);
resEntity = response.getEntity();
final String response_str = EntityUtils.toString(resEntity);
}
But the problem is jsonBodyPart is including slashes.
Request body like this:
{"data"=>"{\"action\":\"YENITALEP\",\"app\":{\"version\":\"verisyon\"},\"data\":{\"invoices\":[{\"imageName\":\"1395914025134\",\"note\":\"\",\"type\":\"FATURA\",\"typeNo\":\"0\"}],\"note\":\"\",\"notification\":[{\"type\":\"BeniAray?n\",\"typeNo\":\"0\"}]},\"device\":{\"hardwareModel\":\"m7\",\"model\":\"HTC
One\",\"systemVersion\":\"4.4.2\",\"uid\":\"00000000-7f39-faab-b500-7f280e9b4fed\"},\"timestamp\":\"Date(1391073711000+0200)\"}",
"1395914025134"=>#,
#original_filename="1395914025134.jpg", #content_type="image/jpg;
charset=UTF-8", #headers="Content-Disposition: form-data;
name=\"1395914025134\";
filename=\"1395914025134.jpg\"\r\nContent-Type: image/jpg;
charset=UTF-8\r\nContent-Transfer-Encoding: binary\r\n">}
How can I post a complex json object and images using multipart? Thanks for help
check once this code iam using this one for uploading images to server
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(urls[0]);
MultipartEntity multipartContent = new MultipartEntity();
for(int i=0;i<allimagespath.size();i++){
Bitmap bm = ShrinkBitmap(allimagespath.get(i), 140, 140);
String format = allimagespath.get(i).substring((allimagespath.get(i).lastIndexOf(".")+1) , allimagespath.get(i).length());
Bitmap bit=Bitmap.createScaledBitmap(bm, 140, 140, true);
ByteArrayOutputStream blob = new ByteArrayOutputStream();
if(format.equalsIgnoreCase("png")){
bit.compress(CompressFormat.PNG, 100 , blob);
}else{
bit.compress(CompressFormat.JPEG, 100 , blob);
}
bitmapdata = blob.toByteArray();
ByteArrayBody thumbbmp = new ByteArrayBody(bitmapdata, "thumb."+format);
FileBody bin2 = new FileBody(new File(allimagespath.get(i)));
multipartContent.addPart("uploaded_file["+i+"]", bin2);
multipartContent.addPart("uploaded_thumb["+i+"]", thumbbmp);
}
multipartContent.addPart("count", new StringBody(""+allimagespath.size()));
postRequest.setEntity(multipartContent);
HttpResponse response = httpClient.execute(postRequest);
HttpEntity entity = response.getEntity();
is = entity.getContent();

OCR not recognizing the contents of Camera pic?

i am trying to develop an OCR app, which will recognize the content of Camera pic , but getting a response "This Image Is too Big",i tried to resize the image,,, but still not happening. My code of OCR is this
public class weocr {
String response;
#SuppressWarnings("unused")
private String selectedpath;
weocr(String selectedpath) throws UnsupportedEncodingException, ParseException, ClientProtocolException, IOException
{
String url="http://appsv.ocrgrid.org/cgi-bin/weocr/submit_tesseract.cgi";
response="";
this.selectedpath=selectedpath;
HttpClient client = new DefaultHttpClient();
client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpPost post=new HttpPost(url);
MultipartEntity entity = new MultipartEntity( HttpMultipartMode.BROWSER_COMPATIBLE );
//test start
try {
File imgFile = new File(selectedpath);
int h = 200; // height in pixels
int w = 200; // width in pixels
Bitmap bm = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
Bitmap bm1 = Bitmap.createScaledBitmap(bm, h, w, true);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bm.compress(CompressFormat.JPEG, 50, bos);
byte[] data = bos.toByteArray();
ByteArrayBody bab = new ByteArrayBody(data, "testbin.png");
//test end
entity.addPart( "userfile", bab);
// For usual String parameters
entity.addPart( "outputencoding", new StringBody("utf-8"));
entity.addPart( "outputformat", new StringBody("txt"));
post.setEntity( entity );
HttpResponse response = client.execute(post);
BufferedReader reader = new BufferedReader(new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
String sResponse;
StringBuilder s = new StringBuilder();
while ((sResponse = reader.readLine()) != null) {
s = s.append(sResponse);
}
this.response=new String(s.toString());
//System.out.println("Response: " + s);
// Here we go!
//String response = EntityUtils.toString( client.execute( post ).getEntity(), "UTF-8" );
//client.getConnectionManager().shutdown();
//System.out.println(response);
//Toast toast=Toast.makeText(getApplicationContext(), response, Toast.LENGTH_LONG);
//toast.show();
}
catch (Exception e) {
Log.e(e.getClass().getName(), e.getMessage());
}
}
}

Android getting pictures from webservice, how to?

I have an android application that needs to receive several pictures from the webservice.
But how to do this?
In my webservice i'm currently sending only 1 image as a byte[].
public static byte[] GetMapPicture(string SeqIndex)
{
try
{
byte[] maps;
InterventionEntity interventie = new InterventionEntity(long.Parse(SeqIndex));
MyDocumentsCollection files = interventie.Location.MyDocuments;
maps = null;
foreach (MyDocumentsEntity file in files)
{
if (file.SeqDocumentType == (int)LocationDocumentType.GroundPlanDocument && file.File.Filename.EndsWith(".jpg"))
maps = (file.File.File);
}
return maps;
} catch (Exception e) {
Log.Error(String.Format("Map not send, {0}", e));
return null;
}
}
The byte[] is returned from my webservice.
But in my android project the bitmap is not decoded and therefor null.
public Bitmap getPicture(String message, String url, Context context) throws IOException{
HttpClient hc = MySSLSocketFactory.getNewHttpClient();
Log.d(MobileConnectorApplication.APPLICATION_TAG, "NETWORK - Message to send: "+ message);
HttpPost p = new HttpPost(url);
Bitmap picture;
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setSoTimeout(httpParams, threeMinutes );
p.setParams(httpParams);
try{
if (message != null)
p.setEntity(new StringEntity(message, "UTF8"));
}catch(Exception e){
e.printStackTrace();
}
p.setHeader("Content-type", "application/json");
HttpContext httpcontext = new BasicHttpContext();
httpcontext.setAttribute(ClientContext.COOKIE_STORE, MobileConnectorApplication.COOKIE_STORE);
try{
HttpResponse resp = hc.execute(p,httpcontext);
InputStream is = resp.getEntity().getContent();
picture = BitmapFactory.decodeStream(is); //here is goes wrong
int httpResponsecode = resp.getStatusLine().getStatusCode() ;
checkResponse(url, message, "s", httpResponsecode);
Log.d(MobileConnectorApplication.APPLICATION_TAG, String.format("NETWORK - Response %s", httpResponsecode));
} finally{
}
return picture;
}
Can anyone help me on this?
assuming incomingbytearray is a byte array,
Bitmap bitmapimage = BitmapFactory.decodeByteArray(incomingbytearray, 0, incomingbytearray.length);
String filepath = "/sdcard/xyz.png";
File imagefile = new File(filepath);
FileOutputStream fos = new FileOutputStream(imagefile);
bitmapimage.compress(CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
This should be fine.
EDIT: input stream to bytearray,
InputStream in = new BufferedInputStream(url.openStream(), IO_BUFFER_SIZE);
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
copy(in, out);
out.flush();
final byte[] data = dataStream.toByteArray();
conversion code from Android: BitmapFactory.decodeByteArray gives pixelated bitmap

Categories

Resources