I am creating a chat application but I could not understand how to set user avatar on openfire server using smack api. i am the below code to set user avatar.
public boolean changeImage(File file) {
if (mConnection == null)
return false;
try {
VCard vcard = new VCard();
String userJID = prefs.getString(Prefrences.xmpp_jid, null);
System.out.println("user:- "+userJID);
vcard.load(mConnection, userJID);
byte[] bytes;
bytes = getFileBytes(file);
String encodedImage = StringUtils.encodeHex(bytes);
vcard.setAvatar(bytes, encodedImage);
vcard.setEncodedImage(encodedImage);
vcard.setField("PHOTO", "<TYPE>image/jpg</TYPE><BINVAL>"
+ encodedImage + "</BINVAL>", true);
System.out.println("Encoded image "+encodedImage);
System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++");
ByteArrayInputStream bais = new ByteArrayInputStream(
vcard.getAvatar());
FormatTools.getInstance().InputStream2Bitmap(bais);
vcard.save(mConnection);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* File to byte
*
* #param file
* #return
* #throws java.io.IOException
*/
private byte[] getFileBytes(File file) throws IOException {
BufferedInputStream bis = null;
try {
bis = new BufferedInputStream(new FileInputStream(file));
int bytes = (int) file.length();
byte[] buffer = new byte[bytes];
int readBytes = bis.read(buffer);
if (readBytes != buffer.length) {
throw new IOException("Entire file not read");
}
return buffer;
} finally {
if (bis != null) {
bis.close();
}
}
}
Please Help.
use this code:it might be helpful to you:)
private void loadVCard(XMPPConnection conn, String username) {
VCard vcard = new VCard();
//ProviderManager.addIQProvider("vCard", "vcard-temp", new VCardProvider());
vcard.load(conn, username);
vcard.setFirstName("" + username);
vcard.setEmailHome("" + email);
vcard.setMiddleName("" + middleName);
vcard.setNickName("" + nickName);
vcard.setPhoneHome("Voice", "" + phoneNumber);
vcard.setLastName("" + lastName);
vcard.setOrganization("" + orginiZation);
vcard.setAvatar("" + image_path); //Image Path should be URL or Can be Byte Array etc.
vcard.save(conn);
}
Related
I have a problem inserting or updating a contact picture.
It seems that Android compressed the picture.
For testing, I created a PNG with 200 x 200 px and saved it in the internal app storage.
The size of the byte[] is 52490.
But the size of the contact picture (high res) is always 6767 bytes.
Tested on a HTC U11 (Android 9) and Sony Xperia (Android 8)
Reading the image from internal storage:
byte[] readPicture(String filename) {
FileInputStream in = null;
byte[] result = null;
try {
in = context.openFileInput(filename);
result = new byte[in.available()];
int read = in.read(result);
Log.d("FileUtil", read + " bytes read from " + filename);
} catch (Exception e) {
e.printStackTrace();
} finally {
closeStream(in);
}
return result;
}
Insert the picture to a specific contact:
picture = readPicture(filename);
ContentProviderOperation.Builder builder = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);
builder.withYieldAllowed(true);
builder.withValue(ContactsContract.Data.CONTACT_ID, contactId);
builder.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE);
builder.withValue(ContactsContract.Data.IS_SUPER_PRIMARY, 1);
builder.withValue(ContactsContract.CommonDataKinds.Photo.PHOTO, picture);
ops.add(builder.build());
Load the full-size contact picture:
// contact.getContactId() == ContactsContract.Data.CONTACT_ID
// contact.getLookup() == ContactsContract.Data.LOOKUP_KEY
ContactsContract.Contacts.getLookupUri(Long.parseLong(contact.getContactId()), contact.getLookup());
InputStream is = ContactsContract.Contacts.openContactPhotoInputStream(cr, uri, true);
ByteArrayOutputStream os = new ByteArrayOutputStream();
byte[] result = null;
if (is != null) {
byte[] buffer = new byte[4096];
int length;
try {
while ((length = is.read(buffer)) != -1) {
os.write(buffer, 0, length);
}
result = os.toByteArray();
} catch (Exception ignored) {
return null;
} finally {
FileUtil.closeStream(is);
FileUtil.closeStream(os);
}
}
return result;
I think I'm doing something wrong, but I have no idea what.
Don't you need to loop the read, in following code:
while(in.available()>0){
result = new byte[in.available()];
int read = in.read(result);
//or better make a loop until in.read(readBytes[])!=-1
Log.d("FileUtil", read + " bytes read from " + filename);
}
Hi have implemented programatically downloading of file using inputstream and cipheroutputstream(for encryption). The download is happening very slow. Whereas if i try to download via download manager, it is very fast. What can i do to improve my code and increase the download speed of the file. Below is my code.
private void saveFileUsingEncryption(String aMineType, long length) throws Exception {
int bufferSize = 1024*4;
//byte[] buffer = new byte[1024];
byte[] buffer = new byte[bufferSize];
int bytesRead = 0;
long totalRead = 0;
FileOutputStream outStream = null;
File f = new File(Constants.DWLPATH);
if (!f.exists()) {
f.mkdirs();
}
try {
Cipher aes = Cipher.getInstance("ARC4");
aes.init(Cipher.ENCRYPT_MODE, new SecretKeySpec("mykey".getBytes(), "ARC4"));
if(contDisp==null || contDisp.length()==0) {
// downloadFileName = downloadFileName.replaceAll("[^a-zA-Z0-9_]+", "");
downloadFileName = downloadFileName + "." + getFileExtension(aMineType);
}
outStream = new FileOutputStream(Constants.DWLPATH + downloadFileName,true);
CipherOutputStream out = new CipherOutputStream(outStream, aes);
while ((bytesRead = inputStream.read(buffer, 0, bufferSize)) >= 0) {
out.write(buffer, 0, bytesRead);
try{
// Adjust this value. It shouldn't be too small.
Thread.sleep(50);
}catch (InterruptedException e){
TraceUtils.logException(e);
}
totalRead += bytesRead;
sb=sb.append("\n Total bytes Read:"+totalRead);
Log.e("--",sb.toString());
/* if (this.length > 0) {
Long[] progress = new Long[5];
progress[0] = (long) ((double) totalRead / (double) this.length * 100.0);
publishProgress(progress);
}*/
if (this.isCancelled()) {
if (conn != null)
conn.disconnect();
conn = null;
break;
}
}
Log.e("Download completed","success");
out.flush();
//Utils.putDownloadLogs(requestUrl,mimeType,length, downloadFileName,"Download is Successful",sb.toString(), context);
outStream.close();
buffer = null;
} catch (Exception e) {
TraceUtils.logException( e);
file_newsize = storedFileSizeInDB + totalRead;
if (totalFileSize == 0)
totalFileSize = length;
callback.onRequestInterrupted(file_newsize,totalFileSize);
StringWriter errors = new StringWriter();
e.printStackTrace(new PrintWriter(errors));
// Utils.putDownloadLogs(requestUrl,mimeType,length,downloadFileName,"failure---" + errors.toString(),sb.toString(), context);
throw e;
} finally {
if (outStream != null)
outStream.close();
outStream = null;
}
}
You can use default download manager to download the file because its very easy to implement and provide better features like respond to the internet connection , provide accessibility to add notification in status bar , by running the query on download manager object you can find the total bytes and remaining bytes so you can calculate the progress and after completion of download by tapping the notification one can perform the desired operation.
And also there are many libraries are available for to achieve this like
PRDOWNLOADER
FetchDownloader
This libraires provide you the feature of pause,download, resume download , tracking the progress and cancel download
Also you can customize it as per your need.
Here is the DownloadAndEncryptFileTask.class to download with encryption
public class DownloadAndEncryptFileTask extends AsyncTask<Void, Void, Void> {
private String mUrl;
private File mFile;
private Cipher mCipher;
InputStream inputStream;
FileOutputStream fileOutputStream;
CipherOutputStream cipherOutputStream;
public DownloadAndEncryptFileTask(String url, File file, Cipher cipher) {
if (url == null || url.isEmpty()) {
throw new IllegalArgumentException("You need to supply a url to a clear MP4 file to download and encrypt, or modify the code to use a local encrypted mp4");
}
mUrl = url;
mFile = file;
mCipher = cipher;
}
private void downloadAndEncrypt() throws Exception {
URL url = new URL(mUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
if (mFile.length() > 0) {
connection.setRequestProperty("Range", "bytes=" + mFile.length() + "-");
}
connection.connect();
Log.e("length", mFile.length() + "");
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new IOException("server error: " + connection.getResponseCode() + ", " + connection.getResponseMessage());
}
inputStream = connection.getInputStream();
if (mFile.length() > 0) {
//connection.connect();
fileOutputStream = new FileOutputStream(mFile, true);
} else {
fileOutputStream = new FileOutputStream(mFile);
}
CipherOutputStream cipherOutputStream = new CipherOutputStream(fileOutputStream, mCipher);
byte buffer[] = new byte[1024 * 1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
Log.d(getClass().getCanonicalName(), "reading from http...");
cipherOutputStream.write(buffer, 0, bytesRead);
}
inputStream.close();
cipherOutputStream.close();
connection.disconnect();
}
#Override
protected Void doInBackground(Void... params) {
try {
downloadAndEncrypt();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
Log.d(getClass().getCanonicalName(), "done");
}
}
Call this class
new DownloadAndEncryptFileTask(
myFeedsModel.getVideo().getVideo360(),
new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), myFeedsModel.getFile_name()),
OBJECT OF YOUR CIPHER
i am trying to change HTTPClient deprecated code but i get error on setEntity because its dapricated and i dont know how to paas MultipartEntityBuilder by new httpConnectionUrl.
my old deprecated code snippt
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(imagePostUrl);
for (String fileName : fileNameArrayList) {
File file = new File(fileName);
// 1st
int quality = GeneralUtil.getQualityOfImage(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
if (quality <= 25) { // This means image file size is in MB's so we need to avoide out of memory issues.
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = false;
options.inPreferredConfig = Bitmap.Config.RGB_565;
options.inDither = true;
try {
bitmap = BitmapFactory.decodeFile(file.getPath(), options);
} catch (OutOfMemoryError E) {
System.gc();
bitmap = GeneralUtil.decodeFile(file);
}
bitmap.compress(CompressFormat.JPEG, quality, bos);
bitmap.recycle();
bitmap = null;
} else {
try {
bitmap = BitmapFactory.decodeFile(file.getPath());
bitmap.compress(CompressFormat.JPEG, quality, bos);
bitmap.recycle();
bitmap = null;
} catch (OutOfMemoryError E) {
System.gc();
try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = false;
options.inPreferredConfig = Bitmap.Config.RGB_565;
options.inDither = true;
bitmap = BitmapFactory.decodeFile(file.getPath(), options);
bitmap.compress(CompressFormat.JPEG, quality, bos);
bitmap.recycle();
bitmap = null;
} catch (OutOfMemoryError ex) {
bitmap = GeneralUtil.decodeFile(file);
bitmap.compress(CompressFormat.JPEG, quality, bos);
bitmap.recycle();
bitmap = null;
throw new Exception();
}
}
}
byte[] data = bos.toByteArray();
String timeStamp = GeneralUtil.generateTimeStamp();
ByteArrayBody bin = new ByteArrayBody(data, myMobileNo + "_" + userName + "_" + timeStamp + ".jpg");
MultipartEntityBuilder multiPartEntityBuilder = MultipartEntityBuilder.create();
multiPartEntityBuilder.addPart("uploadedfile1", bin);
multiPartEntityBuilder.addPart("inviteId", new StringBody(inviteIdArrayList.get(0).toString(), Charset.forName("UTF-8")));
post.setEntity(multiPartEntityBuilder.build());
HttpResponse httpResponse = null;
httpResponse = client.execute(post);
InputStream inputStream = null;
inputStream = httpResponse.getEntity().getContent();
if (inputStream != null)
result.add(convertInputStreamToString(inputStream));
else
result.add("Did not work!");
}
my new not working code snippt
try {
HttpURLConnection httpcon = (HttpURLConnection) ((new URL(imagePostUrl).openConnection()));
httpcon.setDoOutput(true);
for (String fileName : fileNameArrayList) {
File file = new File(fileName);
int quality = GeneralUtil.getQualityOfImage(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
if (quality <= 25) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = false;
options.inPreferredConfig = Bitmap.Config.RGB_565;
options.inDither = true;
try {
bitmap = BitmapFactory.decodeFile(file.getPath(), options);
} catch (OutOfMemoryError E) {
System.gc();
bitmap = GeneralUtil.decodeFile(file);
}
bitmap.compress(CompressFormat.JPEG, quality, bos);
bitmap.recycle();
bitmap = null;
} else {
try {
bitmap = BitmapFactory.decodeFile(file.getPath());
bitmap.compress(CompressFormat.JPEG, quality, bos);
bitmap.recycle();
bitmap = null;
} catch (OutOfMemoryError E) {
System.gc();
try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = false;
options.inPreferredConfig = Bitmap.Config.RGB_565;
options.inDither = true;
bitmap = BitmapFactory.decodeFile(file.getPath(), options);
bitmap.compress(CompressFormat.JPEG, quality, bos);
bitmap.recycle();
bitmap = null;
} catch (OutOfMemoryError ex) {
bitmap = GeneralUtil.decodeFile(file);
bitmap.compress(CompressFormat.JPEG, quality, bos);
bitmap.recycle();
bitmap = null;
throw new Exception();
}
}
}
byte[] data = bos.toByteArray();
String timeStamp = GeneralUtil.generateTimeStamp();
ByteArrayBody bin = new ByteArrayBody(data, myMobileNo + "_" + userName + "_" + timeStamp + ".jpg");
MultipartEntityBuilder multiPartEntityBuilder = MultipartEntityBuilder.create();
multiPartEntityBuilder.addPart("uploadedfile1", bin);
multiPartEntityBuilder.addPart("inviteId", new StringBody(inviteIdArrayList.get(0).toString(), Charset.forName("UTF-8")));
httpcon.setEntity(multiPartEntityBuilder.build()); **error**
// Execute POST request to the given URL
// HttpResponse httpResponse = null;
// httpResponse = client.execute(post);
httpcon.setRequestMethod("POST");
httpcon.connect();
Here is my suggested alternative solution:
First of all, you can refer to some of the following libraries: Volley, Retrofit...
If you want to use Volley, you can refer to some following links:
Working POST Multipart Request with Volley and without HttpEntity
How to send a “multipart/form-data” POST in Android with Volley
My sample code relating to the first link above
MultipartActivity.java:
public class MultipartActivity extends Activity {
private final Context context = this;
private final String twoHyphens = "--";
private final String lineEnd = "\r\n";
private final String boundary = "apiclient-" + System.currentTimeMillis();
private final String mimeType = "multipart/form-data;boundary=" + boundary;
private byte[] multipartBody;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_multipart);
byte[] fileData1 = getFileDataFromDrawable(context, R.drawable.ic_action_android);
byte[] fileData2 = getFileDataFromDrawable(context, R.drawable.ic_action_book);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(bos);
try {
// the first file
buildPart(dos, fileData1, "ic_action_android.png");
// the second file
buildPart(dos, fileData2, "ic_action_book.png");
// send multipart form data necesssary after file data
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// pass to multipart body
multipartBody = bos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
String url = "http://192.168.1.100/api/postfile";
MultipartRequest multipartRequest = new MultipartRequest(url, null, mimeType, multipartBody, new Response.Listener<NetworkResponse>() {
#Override
public void onResponse(NetworkResponse response) {
Toast.makeText(context, "Upload successfully!", Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, "Upload failed!\r\n" + error.toString(), Toast.LENGTH_SHORT).show();
}
});
VolleySingleton.getInstance(context).addToRequestQueue(multipartRequest);
}
...
private void buildPart(DataOutputStream dataOutputStream, byte[] fileData, String fileName) throws IOException {
dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\"; filename=\""
+ fileName + "\"" + lineEnd);
dataOutputStream.writeBytes(lineEnd);
ByteArrayInputStream fileInputStream = new ByteArrayInputStream(fileData);
int bytesAvailable = fileInputStream.available();
int maxBufferSize = 1024 * 1024;
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
byte[] buffer = new byte[bufferSize];
// read file and write it into form...
int bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dataOutputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
dataOutputStream.writeBytes(lineEnd);
}
private byte[] getFileDataFromDrawable(Context context, int id) {
Drawable drawable = ContextCompat.getDrawable(context, id);
Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 0, byteArrayOutputStream);
return byteArrayOutputStream.toByteArray();
}
}
MultipartRequest.java:
class MultipartRequest extends Request<NetworkResponse> {
private final Response.Listener<NetworkResponse> mListener;
private final Response.ErrorListener mErrorListener;
private final Map<String, String> mHeaders;
private final String mMimeType;
private final byte[] mMultipartBody;
public MultipartRequest(String url, Map<String, String> headers, String mimeType, byte[] multipartBody, Response.Listener<NetworkResponse> listener, Response.ErrorListener errorListener) {
super(Method.POST, url, errorListener);
this.mListener = listener;
this.mErrorListener = errorListener;
this.mHeaders = headers;
this.mMimeType = mimeType;
this.mMultipartBody = multipartBody;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
return (mHeaders != null) ? mHeaders : super.getHeaders();
}
#Override
public String getBodyContentType() {
return mMimeType;
}
#Override
public byte[] getBody() throws AuthFailureError {
return mMultipartBody;
}
#Override
protected Response<NetworkResponse> parseNetworkResponse(NetworkResponse response) {
try {
return Response.success(
response,
HttpHeaderParser.parseCacheHeaders(response));
} catch (Exception e) {
return Response.error(new ParseError(e));
}
}
#Override
protected void deliverResponse(NetworkResponse response) {
mListener.onResponse(response);
}
#Override
public void deliverError(VolleyError error) {
mErrorListener.onErrorResponse(error);
}
}
Of course, you can find more available in SO.
Hope this helps!
I was able to get my Multipart Form Data upload thing to work after a lot of head scratching and hair pulling.
Below class is used for multipart file uploading and it works.
NB: This is not a question, merely an answer to the op.
public class WebConnector {
String boundary = "-------------" + System.currentTimeMillis();
private static final String LINE_FEED = "\r\n";
private static final String TWO_HYPHENS = "--";
private StringBuilder url;
private String protocol;
private HashMap<String, String> params;
private JSONObject postData;
private List<String> fileList;
private int count = 0;
private DataOutputStream dos;
public WebConnector(StringBuilder url, String protocol,
HashMap<String, String> params, JSONObject postData) {
super();
this.url = url;
this.protocol = protocol;
this.params = params;
this.postData = postData;
createServiceUrl();
}
public WebConnector(StringBuilder url, String protocol,
HashMap<String, String> params, JSONObject postData, List<String> fileList) {
super();
this.url = url;
this.protocol = protocol;
this.params = params;
this.postData = postData;
this.fileList = fileList;
createServiceUrl();
}
public String connectToMULTIPART_POST_service(String postName) {
System.out.println(">>>>>>>>>url : " + url);
StringBuilder stringBuilder = new StringBuilder();
String strResponse = "";
InputStream inputStream = null;
HttpURLConnection urlConnection = null;
try {
urlConnection = (HttpURLConnection) new URL(url.toString()).openConnection();
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setRequestProperty("Connection", "close");
urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 ( compatible ) ");
urlConnection.setRequestProperty("Authorization", "Bearer " + Config.getConfigInstance().getAccessToken());
urlConnection.setRequestProperty("Content-type", "multipart/form-data; boundary=" + boundary);
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setUseCaches(false);
urlConnection.setChunkedStreamingMode(1024);
urlConnection.setRequestMethod("POST");
dos = new DataOutputStream(urlConnection.getOutputStream());
Iterator<String> keys = postData.keys();
while (keys.hasNext()) {
try {
String id = String.valueOf(keys.next());
addFormField(id, "" + postData.get(id));
System.out.println(id + " : " + postData.get(id));
} catch (JSONException e) {
e.printStackTrace();
}
}
try {
dos.writeBytes(LINE_FEED);
dos.flush();
dos.close();
} catch (IOException e) {
e.printStackTrace();
}
if (fileList != null && fileList.size() > 0 && !fileList.isEmpty()) {
for (int i = 0; i < fileList.size(); i++) {
File file = new File(fileList.get(i));
if (file != null) ;
addFilePart("photos[" + i + "][image]", file);
}
}
// forming th java.net.URL object
build();
urlConnection.connect();
int statusCode = 0;
try {
urlConnection.connect();
statusCode = urlConnection.getResponseCode();
} catch (EOFException e1) {
if (count < 5) {
urlConnection.disconnect();
count++;
String temp = connectToMULTIPART_POST_service(postName);
if (temp != null && !temp.equals("")) {
return temp;
}
}
} catch (IOException e) {
e.printStackTrace();
}
// 200 represents HTTP OK
if (statusCode == HttpURLConnection.HTTP_OK) {
inputStream = new BufferedInputStream(urlConnection.getInputStream());
strResponse = readStream(inputStream);
} else {
System.out.println(urlConnection.getResponseMessage());
inputStream = new BufferedInputStream(urlConnection.getInputStream());
strResponse = readStream(inputStream);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (null != inputStream)
inputStream.close();
} catch (IOException e) {
}
}
return strResponse;
}
public void addFormField(String fieldName, String value) {
try {
dos.writeBytes(TWO_HYPHENS + boundary + LINE_FEED);
dos.writeBytes("Content-Disposition: form-data; name=\"" + fieldName + "\"" + LINE_FEED + LINE_FEED/*+ value + LINE_FEED*/);
/*dos.writeBytes("Content-Type: text/plain; charset=UTF-8" + LINE_FEED);*/
dos.writeBytes(value + LINE_FEED);
} catch (IOException e) {
e.printStackTrace();
}
}
public void addFilePart(String fieldName, File uploadFile) {
try {
dos.writeBytes(TWO_HYPHENS + boundary + LINE_FEED);
dos.writeBytes("Content-Disposition: form-data; name=\"" + fieldName + "\";filename=\"" + uploadFile.getName() + "\"" + LINE_FEED);
dos.writeBytes(LINE_FEED);
FileInputStream fStream = new FileInputStream(uploadFile);
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int length = -1;
while ((length = fStream.read(buffer)) != -1) {
dos.write(buffer, 0, length);
}
dos.writeBytes(LINE_FEED);
dos.writeBytes(TWO_HYPHENS + boundary + TWO_HYPHENS + LINE_FEED);
/* close streams */
fStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void addHeaderField(String name, String value) {
try {
dos.writeBytes(name + ": " + value + LINE_FEED);
} catch (IOException e) {
e.printStackTrace();
}
}
public void build() {
try {
dos.writeBytes(LINE_FEED);
dos.flush();
dos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static String readStream(InputStream in) {
StringBuilder sb = new StringBuilder();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String nextLine = "";
while ((nextLine = reader.readLine()) != null) {
sb.append(nextLine);
}
/* Close Stream */
if (null != in) {
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
private void createServiceUrl() {
if (null == params) {
return;
}
final Iterator<Map.Entry<String, String>> it = params.entrySet().iterator();
boolean isParam = false;
while (it.hasNext()) {
final Map.Entry<String, String> mapEnt = (Map.Entry<String, String>) it.next();
url.append(mapEnt.getKey());
url.append("=");
try {
url.append(URLEncoder.encode(mapEnt.getValue(), "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
url.append(WSConstants.AMPERSAND);
isParam = true;
}
if (isParam) {
url.deleteCharAt(url.length() - 1);
}
}
}
When I run the following code in Java the output is a multiple of 128 bits (16 bytes).
The exact same code in Android is no longer a multiple of 16 bytes suggesting that the padding has failed.
Any ideas?
//Compress, Encrypt, Decrypt, Decompress variables
public final static String Secretkey = "###hidden######";
public final static String VectorInitializationKey = "###hidden###";
public final static String transformation = "AES/CFB8/PKCS5Padding";
public static byte[] encryptandCompress(byte[] input)
{
ByteArrayOutputStream ms = new ByteArrayOutputStream();
GZIPOutputStream gos = null; // Added
CipherOutputStream cos= null; // Added
SecretKeySpec skeySpec = new SecretKeySpec(Secretkey.getBytes(), "AES");
Cipher cipher;
try {
cipher = Cipher.getInstance(transformation);
IvParameterSpec iv = new IvParameterSpec(VectorInitializationKey.getBytes());
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
cos = new CipherOutputStream(ms, cipher );
gos= new GZIPOutputStream (cos);
gos.write(input);
gos.close(); // Must be called before we return bytes from ms
cos.close();
byte[] toReturn = ms.toByteArray();
Log.d("FileWriter", "Encrypted and compressed " + input.length + " bytes to " + toReturn.length + " bytes");
Log.d("FileWriter", "Encrypted and compressed " + toReturn.length/16.0 + " blocks written");
return toReturn;
} catch (Exception e) {
Log.e("FileWriter", "Compression failed: " + e.getMessage());
return null;
}
finally
{
try
{
if (gos != null)
{
gos.close();
}
if (cos != null)
{
cos.close();
}
if (ms != null)
{
ms.close();
}
}
catch (IOException e) {
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
I need to download a single image at time from the Internet and then save it on the SD card. How do I do it? I have made an attempt, but when I try to view that downloaded image, it shows the message, "No Preview Available". Please see my code below:
public class ImgDownloader {
private static final int IO_BUFFER_SIZE = 4 * 1024;
public static final byte[] downloadImage(String imgURL) {
byte[] data = null;
try {
Log.v("Down", "1");
InputStream in = null;
BufferedOutputStream out = null;
in = new BufferedInputStream(new URL(imgURL).openStream(), 8 * 1024);
Log.v("Down", "2");
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
copy(in, out);
out.flush();
Log.v("Down", "3");
data = dataStream.toByteArray();
// bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
Log.v("Down", "4");
} catch (Exception ex) {
ex.printStackTrace();
// System.out.println("Exception in Image Downloader .."
// +ex.getMessage());
}
return data;
}
private static void copy(InputStream in, OutputStream out)
throws IOException {
byte[] b = new byte[IO_BUFFER_SIZE];
int read;
while ((read = in.read(b)) != -1) {
out.write(b, 0, read);
}
}
}
Note:
i have download the image from the SSL connection.
Any ideas? Thanks in advance.
You can try something like
try{
URL url = new URL(downloadUrl); //you can write here any link
File file = new File(absolutePath); //Something like ("/sdcard/file.mp3")
//Create parent directory if it doesn't exists
if(!new File(file.getParent()).exists())
{
System.out.println("Path is created " + new File(file.getParent()).mkdirs());
}
file = new File(absolutePath); //Something like ("/sdcard/file.mp3")
file.createNewFile();
/* Open a connection to that URL. */
URLConnection ucon = url.openConnection();
/*
* Define InputStreams to read from the URLConnection.
*/
InputStream is = ucon.getInputStream();
/*
* Read bytes to the Buffer until there is nothing more to read(-1).
*/
FileOutputStream fos = new FileOutputStream(file);
int size = 1024*1024;
byte[] buf = new byte[size];
int byteRead;
while (((byteRead = is.read(buf)) != -1)) {
fos.write(buf, 0, byteRead);
bytesDownloaded += byteRead;
}
/* Convert the Bytes read to a String. */
fos.close();
}catch(IOException io)
{
networkException = true;
continueRestore = false;
}
catch(Exception e)
{
continueRestore = false;
e.printStackTrace();
}
Make the appropriate changes according to your requirement. I use the same code for downloading files from internet and saving it to SDCard.
Hope it helps !!