Uploading Images to Server android - android

I want to know which is the best way to upload image to server without losing its quality.
I have searched on google found various methods of posting data. But I am not sure which one would be best to upload.
I came across:
Multipart Image Upload.
Uploading images using byte array
Uploading images using base64 encoded string.
I have tried Base64 encoding it leads me to OOM(Out of memory) if image is too high in resolution.

Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, 1);
ABOVE CODE TO SELECT IMAGE FROM GALLERY
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1)
if (resultCode == Activity.RESULT_OK) {
Uri selectedImage = data.getData();
String filePath = getPath(selectedImage);
String file_extn = filePath.substring(filePath.lastIndexOf(".") + 1);
image_name_tv.setText(filePath);
try {
if (file_extn.equals("img") || file_extn.equals("jpg") || file_extn.equals("jpeg") || file_extn.equals("gif") || file_extn.equals("png")) {
//FINE
} else {
//NOT IN REQUIRED FORMAT
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public String getPath(Uri uri) {
String[] projection = {MediaColumns.DATA};
Cursor cursor = managedQuery(uri, projection, null, null, null);
column_index = cursor
.getColumnIndexOrThrow(MediaColumns.DATA);
cursor.moveToFirst();
imagePath = cursor.getString(column_index);
return cursor.getString(column_index);
}
NOW POST THE DATA USING MULTIPART FORM DATA
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("LINK TO SERVER");
Multipart FORM DATA
MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
if (filePath != null) {
File file = new File(filePath);
Log.d("EDIT USER PROFILE", "UPLOAD: file length = " + file.length());
Log.d("EDIT USER PROFILE", "UPLOAD: file exist = " + file.exists());
mpEntity.addPart("avatar", new FileBody(file, "application/octet"));
}
FINALLY POST DATA TO SERVER
httppost.setEntity(mpEntity);
HttpResponse response = httpclient.execute(httppost);

Main activity class to take pick and upload
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
//import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
public class MainActivity extends Activity {
Button btpic, btnup;
private Uri fileUri;
String picturePath;
Uri selectedImage;
Bitmap photo;
String ba1;
public static String URL = "Paste your URL here";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btpic = (Button) findViewById(R.id.cpic);
btpic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
clickpic();
}
});
btnup = (Button) findViewById(R.id.up);
btnup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
upload();
}
});
}
private void upload() {
// Image location URL
Log.e("path", "----------------" + picturePath);
// Image
Bitmap bm = BitmapFactory.decodeFile(picturePath);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte[] ba = bao.toByteArray();
//ba1 = Base64.encodeBytes(ba);
Log.e("base64", "-----" + ba1);
// Upload image to server
new uploadToServer().execute();
}
private void clickpic() {
// Check Camera
if (getApplicationContext().getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA)) {
// Open default camera
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent, 100);
} else {
Toast.makeText(getApplication(), "Camera not supported", Toast.LENGTH_LONG).show();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 100 && resultCode == RESULT_OK) {
selectedImage = data.getData();
photo = (Bitmap) data.getExtras().get("data");
// Cursor to get image uri to display
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
picturePath = cursor.getString(columnIndex);
cursor.close();
Bitmap photo = (Bitmap) data.getExtras().get("data");
ImageView imageView = (ImageView) findViewById(R.id.Imageprev);
imageView.setImageBitmap(photo);
}
}
public class uploadToServer extends AsyncTask<Void, Void, String> {
private ProgressDialog pd = new ProgressDialog(MainActivity.this);
protected void onPreExecute() {
super.onPreExecute();
pd.setMessage("Wait image uploading!");
pd.show();
}
#Override
protected String doInBackground(Void... params) {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("base64", ba1));
nameValuePairs.add(new BasicNameValuePair("ImageName", System.currentTimeMillis() + ".jpg"));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
String st = EntityUtils.toString(response.getEntity());
Log.v("log_tag", "In the try Loop" + st);
} catch (Exception e) {
Log.v("log_tag", "Error in http connection " + e.toString());
}
return "Success";
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
pd.hide();
pd.dismiss();
}
}
}
php code to handle upload image and also create image from base64 encoded data
<?php
error_reporting(E_ALL);
if(isset($_POST['ImageName'])){
$imgname = $_POST['ImageName'];
$imsrc = base64_decode($_POST['base64']);
$fp = fopen($imgname, 'w');
fwrite($fp, $imsrc);
if(fclose($fp)){
echo "Image uploaded";
}else{
echo "Error uploading image";
}
}
?>

use below code it helps you....
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
options.inPurgeable = true;
Bitmap bm = BitmapFactory.decodeFile("your path of image",options);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG,40,baos);
// bitmap object
byteImage_photo = baos.toByteArray();
//generate base64 string of image
String encodedImage =Base64.encodeToString(byteImage_photo,Base64.DEFAULT);
//send this encoded string to server

Try this method for uploading Image file from camera
package com.example.imageupload;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.message.BasicHeader;
public class MultipartEntity implements HttpEntity {
private String boundary = null;
ByteArrayOutputStream out = new ByteArrayOutputStream();
boolean isSetLast = false;
boolean isSetFirst = false;
public MultipartEntity() {
this.boundary = System.currentTimeMillis() + "";
}
public void writeFirstBoundaryIfNeeds() {
if (!isSetFirst) {
try {
out.write(("--" + boundary + "\r\n").getBytes());
} catch (final IOException e) {
}
}
isSetFirst = true;
}
public void writeLastBoundaryIfNeeds() {
if (isSetLast) {
return;
}
try {
out.write(("\r\n--" + boundary + "--\r\n").getBytes());
} catch (final IOException e) {
}
isSetLast = true;
}
public void addPart(final String key, final String value) {
writeFirstBoundaryIfNeeds();
try {
out.write(("Content-Disposition: form-data; name=\"" + key + "\"\r\n")
.getBytes());
out.write("Content-Type: text/plain; charset=UTF-8\r\n".getBytes());
out.write("Content-Transfer-Encoding: 8bit\r\n\r\n".getBytes());
out.write(value.getBytes());
out.write(("\r\n--" + boundary + "\r\n").getBytes());
} catch (final IOException e) {
}
}
public void addPart(final String key, final String fileName,
final InputStream fin) {
addPart(key, fileName, fin, "application/octet-stream");
}
public void addPart(final String key, final String fileName,
final InputStream fin, String type) {
writeFirstBoundaryIfNeeds();
try {
type = "Content-Type: " + type + "\r\n";
out.write(("Content-Disposition: form-data; name=\"" + key
+ "\"; filename=\"" + fileName + "\"\r\n").getBytes());
out.write(type.getBytes());
out.write("Content-Transfer-Encoding: binary\r\n\r\n".getBytes());
final byte[] tmp = new byte[4096];
int l = 0;
while ((l = fin.read(tmp)) != -1) {
out.write(tmp, 0, l);
}
out.flush();
} catch (final IOException e) {
} finally {
try {
fin.close();
} catch (final IOException e) {
}
}
}
public void addPart(final String key, final File value) {
try {
addPart(key, value.getName(), new FileInputStream(value));
} catch (final FileNotFoundException e) {
}
}
public long getContentLength() {
writeLastBoundaryIfNeeds();
return out.toByteArray().length;
}
public Header getContentType() {
return new BasicHeader("Content-Type", "multipart/form-data; boundary="
+ boundary);
}
public boolean isChunked() {
return false;
}
public boolean isRepeatable() {
return false;
}
public boolean isStreaming() {
return false;
}
public void writeTo(final OutputStream outstream) throws IOException {
outstream.write(out.toByteArray());
}
public Header getContentEncoding() {
return null;
}
public void consumeContent() throws IOException,
UnsupportedOperationException {
if (isStreaming()) {
throw new UnsupportedOperationException(
"Streaming entity does not implement #consumeContent()");
}
}
public InputStream getContent() throws IOException,
UnsupportedOperationException {
return new ByteArrayInputStream(out.toByteArray());
}
}
Use of class for uploading
private void doFileUpload(File file_path) {
Log.d("Uri", "Do file path" + file_path);
try {
HttpClient client = new DefaultHttpClient();
//use your server path of php file
HttpPost post = new HttpPost(ServerUploadPath);
Log.d("ServerPath", "Path" + ServerUploadPath);
FileBody bin1 = new FileBody(file_path);
Log.d("Enter", "Filebody complete " + bin1);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("uploaded_file", bin1);
reqEntity.addPart("email", new StringBody(useremail));
post.setEntity(reqEntity);
Log.d("Enter", "Image send complete");
HttpResponse response = client.execute(post);
resEntity = response.getEntity();
Log.d("Enter", "Get Response");
try {
final String response_str = EntityUtils.toString(resEntity);
if (resEntity != null) {
Log.i("RESPONSE", response_str);
JSONObject jobj = new JSONObject(response_str);
result = jobj.getString("ResponseCode");
Log.e("Result", "...." + result);
}
} catch (Exception ex) {
Log.e("Debug", "error: " + ex.getMessage(), ex);
}
} catch (Exception e) {
Log.e("Upload Exception", "");
e.printStackTrace();
}
}
Service for uploading
<?php
$image_name = $_FILES["uploaded_file"]["name"];
$tmp_arr = explode(".",$image_name);
$img_extn = end($tmp_arr);
$new_image_name = 'image_'. uniqid() .'.'.$img_extn;
$flag=0;
if (file_exists("Images/".$new_image_name))
{
$msg=$new_image_name . " already exists."
header('Content-type: application/json');
echo json_encode(array("ResponseCode"=>"2","ResponseMsg"=>$msg));
}else{
move_uploaded_file($_FILES["uploaded_file"]["tmp_name"],"Images/". $new_image_name);
$flag = 1;
}
if($flag == 1){
require 'db.php';
$static_url =$new_image_name;
$conn=mysql_connect($db_host,$db_username,$db_password) or die("unable to connect localhost".mysql_error());
$db=mysql_select_db($db_database,$conn) or die("unable to select message_app");
$email = "";
if((isset($_REQUEST['email'])))
{
$email = $_REQUEST['email'];
}
$sql ="insert into alert(images) values('$static_url')";
$result=mysql_query($sql);
if($result){
echo json_encode(array("ResponseCode"=>"1","ResponseMsg"=> "Insert data successfully.","Result"=>"True","ImageName"=>$static_url,"email"=>$email));
} else
{
echo json_encode(array("ResponseCode"=>"2","ResponseMsg"=> "Could not insert data.","Result"=>"False","email"=>$email));
}
}
else{
echo json_encode(array("ResponseCode"=>"2","ResponseMsg"=> "Erroe While Inserting Image.","Result"=>"False"));
}
?>

//Kotlin Version
private fun setImageForUploading (imagePath:String):String{
val options = BitmapFactory.Options();
options.inSampleSize = 2
//options.inPurgeable = true //deprecated
val bitmap = BitmapFactory.decodeFile(imagePath,options)
val byteArrayOutPutStream = ByteArrayOutputStream()
bitmap.compress(Bitmap.CompressFormat.PNG,90,byteArrayOutPutStream)
// bitmap object
val byteImagePhoto = byteArrayOutPutStream.toByteArray()
//generate base64 string of image
val encodedImage = Base64.encodeToString(byteImagePhoto,Base64.DEFAULT)
return encodedImage
}

Related

Android IBM Watson visual recognition service

IBM Watson has a Visual Recognition service: http://www.ibm.com/watson/developercloud/visual-recognition.html
Here is the API explorer to test calls to the API:
http://www.ibm.com/watson/developercloud/visual-recognition/api/v3/
The tutorials and API reference are available in the documentation.
I am trying to use the service in order to retrieve the JSON data response through android. However, after debugging, it keeps showing error 404. I am completely lost on how to fix this issue.
If you are going to run the following code, please replace api_key in Main_activity.java with your own key. This key is generated when you create your own service for IBM Watson's Visual Recognition service on IBM Bluemix.
Here is my MainActivity.java file:
package com.innam.httpapptotestrestservice;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
TextView etResponse;
TextView tvIsConnected;
TextView imageRespone;
ImageView imgPreview;
// VideoView vidPreview;
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 200;
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
private Uri fileUri;
static String IMAGE_DIRECTORY_NAME = "Watson";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get reference to the views
etResponse = (TextView) findViewById(R.id.etResponse);
tvIsConnected = (TextView) findViewById(R.id.tvIsConnected);
imgPreview = (ImageView) findViewById(R.id.imgPreview);
imageRespone = (TextView) findViewById(R.id.ImgResponse);
MediaController mediaController = new MediaController(this);
// mediaController.setAnchorView(vidPreview);
// vidPreview.setMediaController(mediaController);
// check if you are connected or not
if (isConnected()) {
tvIsConnected.setBackgroundColor(0xFF00CC00);
tvIsConnected.setText("You are conncted");
} else {
tvIsConnected.setText("You are NOT conncted");
}
// call AsynTask to perform network operation on separate thread
new HttpAsyncTaskOne().execute();
}
public static String GET(String url) {
InputStream inputStream = null;
String result = "";
try {
// create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// make GET request to the given URL
HttpResponse httpResponse = httpclient.execute(new HttpGet(url));
// receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// convert inputstream to string
if (inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
return result;
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
String result = "";
while ((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
public boolean isConnected() {
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Activity.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected())
return true;
else
return false;
}
private class HttpAsyncTaskOne extends AsyncTask<String, Void, String>
{
ProgressDialog pd;
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = ProgressDialog.show(MainActivity.this, "Hi!", "Please wait your response is about to generate");
}
#Override
protected String doInBackground(String... urls) {
//return GET(urls[0]);
return getResponseOne();
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
pd.dismiss();
Toast.makeText(getBaseContext(), "Received!", Toast.LENGTH_LONG).show();
String formattedResult="";
String classifer_id="" ;
String name="";
String owner="";
String status="";
String created ="";
String classesobj="";
try{
JSONObject jObj = new JSONObject(result);
classifer_id = jObj.optString("classifier_id");
name = jObj.optString("name");
owner = jObj.optString("owner");
status = jObj.optString("status");
created = jObj.optString("created");
JSONArray jsonArray = jObj.optJSONArray("classes");
//Iterate the jsonArray and print the info of JSONObjects
for(int i=0; i < jsonArray.length(); i++)
{
classesobj = jsonArray.getJSONObject(i).optString("class");
//classesobj += jObj.optString("class");
}
formattedResult = "{ \n" + " classifer_id: "+ classifer_id
+ ",\n name: "+ name
+ ",\n owner: "+ owner
+ ",\n status: "+ status
+ ",\n created: "+ created
+ ",\n classes: [\n"+
"{ class: " + classesobj + "}\n" +
" ] \n }";
}
catch(JSONException e) {
e.printStackTrace();
}
etResponse.setText(formattedResult);
}
}
/**
* https://watson-api-explorer.mybluemix.net/visual-recognition/api/v3/classifiers?
* api_key=*****
* #return
*/
private String getResponseOne() {
//String endPointUrl = AppConstants.BASE_URL + "";
/*String params = "api_key=*********" +
"&url=http://thumbs.dreamstime.com/t/orange-apple-banana-isolated-white-background-51942284.jpg" +
"&classifier_ids=default,fruits_960559343" +
"&owners=me,IBM" +
"&threshold=0.2" +
"&version=2016-05-20";*/
String postParams = "api_key=**********" +
"&version=2016-05-19" +
"&negative_examples=negative_examples.zip" +
"&classname_positive_examples=baypay_positive_examples.zip&name=baypay";
//String url = "https://gateway-a.watsonplatform.net/visual-recognition/api/v3/classify?";
String url = "https://watson-api-explorer.mybluemix.net/visual-recognition/api/v3/classifiers?"+postParams;
// String params ="api_key=********" +
// "version=2016-05-19";
//
// String url = "https://watson-api-explorer.mybluemix.net/visual-recognition/api/v3/classifiers/baypay_309108553?" ;
ServiceHandler serviceHandler = new ServiceHandler(this);
try {
// return serviceHandler.doPost(url, params);
return serviceHandler.doGet(url);
} catch (IOException e) {
e.printStackTrace();
}
return "Response Not returned";
}
public void openCamera(View v)
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
/**
* Launching camera app to record video
*/
// public void openVideo(View v) {
// Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
//
// fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);
//
// // set video quality
// intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
//
// intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file
// // name
//
// // start the video capture Intent
// startActivityForResult(intent, CAMERA_CAPTURE_VIDEO_REQUEST_CODE);
// }
String photoPath = "";
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) //what to do once the image has been captured
{
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// successfully captured the image
// launching upload activity
//launchUploadActivity(true);
// bimatp factory
photoPath = fileUri.getPath();
BitmapFactory.Options options = new BitmapFactory.Options();
// down sizing image as it throws OutOfMemory Exception for larger
// images
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(photoPath, options);
imgPreview.setVisibility(View.VISIBLE);
// vidPreview.setVisibility(View.GONE);
imgPreview.setImageBitmap(bitmap);
//next parse result string
} else if (resultCode == RESULT_CANCELED) {
// user cancelled Image capture
Toast.makeText(getApplicationContext(),
"User cancelled image capture", Toast.LENGTH_SHORT)
.show();
} else {
// failed to capture image
Toast.makeText(getApplicationContext(),
"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
.show();
}
}
// else if (requestCode == CAMERA_CAPTURE_VIDEO_REQUEST_CODE) {
// if (resultCode == RESULT_OK) {
//
// // video successfully recorded
// // launching upload activity
//
// imgPreview.setVisibility(View.GONE);
// vidPreview.setVisibility(View.VISIBLE);
// vidPreview.setVideoPath(fileUri.getPath());
// // start playing
// vidPreview.start();
//
//
// } else if (resultCode == RESULT_CANCELED) {
//
// // user cancelled recording
// Toast.makeText(getApplicationContext(),
// "User cancelled video recording", Toast.LENGTH_SHORT)
// .show();
//
// } else {
// // failed to record video
// Toast.makeText(getApplicationContext(),
// "Sorry! Failed to record video", Toast.LENGTH_SHORT)
// .show();
// }
// }
}
#Override
protected void onPause() {
super.onPause();
// if(vidPreview != null && vidPreview.isPlaying())
// {
// vidPreview.pause();
// }
}
#Override
protected void onDestroy() {
super.onDestroy();
// if(vidPreview != null && vidPreview.isPlaying())
// {
// vidPreview.stopPlayback();
// }
}
/**
* Creating file uri to store image/video
*/
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
/**
* returning image / video
*/
private static File getOutputMediaFile(int type) {
// External sdcard location
File mediaStorageDir = new File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), IMAGE_DIRECTORY_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("IMG Capture", "Oops! Failed create "
+ IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
}
// else if (type == MEDIA_TYPE_VIDEO) {
// mediaFile = new File(mediaStorageDir.getPath() + File.separator
// + "VID_" + timeStamp + ".mp4");
// }
else {
return null;
}
return mediaFile;
}
public void uploadImage(View view)
{
new HttpAsyncTaskTwo().execute();
}
private class HttpAsyncTaskTwo extends AsyncTask<String, Void, String>
{
ProgressDialog pd;
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = ProgressDialog.show(MainActivity.this, "Uploading image!", "Please Wait..");
}
#Override
protected String doInBackground(String... urls)
{
return getResponseTwo();
}
#Override
protected void onPostExecute(String result)
{
pd.dismiss();
Toast.makeText(getBaseContext(), "Received!", Toast.LENGTH_LONG).show();
imageRespone.setText(result);
}
}
// onPostExecute displays the results of the AsyncTask.
private String getResponseTwo()
{
String result;
String testName = fileUri.getPathSegments().get(fileUri.getPathSegments().size()-1);
//setup params
Map<String, String> params = new HashMap<>();
params.put("api_key", "******");
params.put("images_file", testName);
params.put("parameters", "{\"urls\": [], \"classifier_ids\": [\"baypay_1337105903\"], \"owners\": [\"0c9e0d07-7000-4b60-9181-b2e1d0596a30\", \"me\"], \"threshold\": 0.4}");
params.put("Accept-Language", "en");
params.put("version", "2016-05-19");
ServiceHandler serviceHandler = new ServiceHandler(this);
try
{
return serviceHandler.multipartRequest("https://watson-api-explorer.mybluemix.net/visual-recognition/api/v3/classify", params, fileUri.getPath(), "image", "image/jpg");
} catch (Exception e) {
e.printStackTrace();
}
return "Response Not returned";
}
}
Here is the ServiceHandler.java file:
package com.innam.httpapptotestrestservice;
import android.content.Context;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;
public class ServiceHandler {
private static final String USER_AGENT = "Mozilla/5.0";
String filename = "myJsonResponse.txt";
String outputString = "Hello world!";
File myDir;
static final int READ_BLOCK_SIZE = 100;
Context context;
public ServiceHandler(Context context) {
this.context = context;
myDir = context.getFilesDir();
}
public String doGet(String GET_URL) throws IOException {
URL obj = new URL(GET_URL);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setConnectTimeout(150000);
int responseCode = con.getResponseCode();
System.out.println("GET 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());
return response.toString();
} else {
System.out.println("GET request not worked: Response Code: " + responseCode);
return "GET request not worked: Response Code: " + responseCode;
}
}
public String doPost(String POST_URL, String POST_PARAMS) throws IOException {
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);
con.setConnectTimeout(150000);
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());
/*try
{
File respFile = new File(myDir + "/text/", filename);
if (respFile.getParentFile().mkdirs())
{
outputString = response.toString();
respFile.createNewFile();
FileOutputStream fos = new FileOutputStream(respFile);
fos.write(outputString.getBytes());
System.out.println(myDir + " /" + filename);
fos.flush();
fos.close();
}
}
catch (Exception e)
{
e.printStackTrace();
} */
return response.toString();
} else {
System.out.println("POST request not worked: Response Code: " + responseCode);
return "POST request not worked: Response Code: " + responseCode;
}
}
public String multipartRequest(String urlTo, Map<String, String> parmas, String filepath,
String filefield, String fileMimeType) throws Exception {
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
InputStream inputStream = null;
String twoHyphens = "--";
String boundary = "*****" + Long.toString(System.currentTimeMillis()) + "*****";
String lineEnd = "\r\n";
String result = "";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
String[] q = filepath.split("/");
int idx = q.length - 1;
try {
File file = new File(filepath);
FileInputStream fileInputStream = new FileInputStream(file);
URL url = new URL(urlTo);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("User-Agent", "Android Multipart HTTP Client 1.0");
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"" + filefield + "\"; filename=\"" + q[idx] + "\"" + lineEnd);
outputStream.writeBytes("Content-Type: " + fileMimeType + lineEnd);
outputStream.writeBytes("Content-Transfer-Encoding: binary" + lineEnd);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
outputStream.writeBytes(lineEnd);
// Upload POST Data
Iterator<String> keys = parmas.keySet().iterator();
while (keys.hasNext()) {
String key = keys.next();
String value = parmas.get(key);
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"" + key + "\"" + lineEnd);
outputStream.writeBytes("Content-Type: application/json" + lineEnd);
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(value);
outputStream.writeBytes(lineEnd);
}
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
int respCode = connection.getResponseCode();
System.out.println("Response Code: " + respCode);
inputStream = connection.getInputStream();
result = this.convertStreamToString(inputStream);
fileInputStream.close();
inputStream.close();
outputStream.flush();
outputStream.close();
return result;
} catch (Exception e) {
//logger.error(e);
//throw new CustomException(e);
e.printStackTrace();
}
return result;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
Here is the CustomException.java file:
package com.innam.httpapptotestrestservice;
import android.util.Log;
/**
* Created by Innam on 8/5/2016.
*/
public class CustomException extends Throwable {
public CustomException(String s) {
Log.e("CustomException", s);
}
}
Here is the AndroidManifest.xml file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.innam.httpapptotestrestservice">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Here is the activity_main.xml file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/scrollView" >
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/tvIsConnected"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:background="#FF0000"
android:textColor="#FFF"
android:textSize="18dp"
android:layout_marginBottom="5dp"
android:text="is connected? " />
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="20dp"
android:layout_marginBottom="10dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="JSON reult after the service has been trained"
android:textSize="18sp"
android:textColor="#000000"
android:layout_marginLeft="5dp" />
<TextView
android:id="#+id/etResponse"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_marginTop="5dp">
</TextView>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_gravity="center">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Open Camera"
android:id="#+id/button1"
android:onClick="openCamera"
android:layout_marginLeft="20dp"
/>
<ImageView
android:id="#+id/imgPreview"
android:layout_width="200dp"
android:layout_height="165dp"
android:src="#mipmap/ic_launcher"
android:layout_marginTop="10dp"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="UPLOAD"
android:id="#+id/button2"
android:onClick="uploadImage"
android:layout_marginLeft="20dp"
android:layout_marginTop="10dp"
/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="JSON reult after image has been uploaded"
android:textSize="18sp"
android:textColor="#000000"
android:layout_marginTop="20dp"
android:layout_marginLeft="5dp"/>
<TextView
android:id="#+id/ImgResponse"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_marginTop="5dp">
</TextView>
</LinearLayout>
</LinearLayout>
</ScrollView>
</LinearLayout>
I believe the main part of your problem is that you have the wrong URL in your code - both the wrong domain (watson-api-explorer.mybluemix.net) and the wrong path (classify vs classifiers) - the correct one is commented out.
But, as Glenn and German pointed out in comments, there are SDKs available that make the entire process much simpler, so I would strongly advise taking that route.

Application crashes when I save image to SD card

I am trying to use a simple image view and download application, everything works fine till I click on the button to download the application, the moment I click on the button, I get an error saying the application has been closed because it stopped working.
package com.theappguruz.imagedownload;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.SQLException;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.Display;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import com.theappguruz.R;
public class ImageViewAndDownload extends Activity implements OnClickListener {
private Button btnImageDownload;
private ProgressDialog pd;
private ImageView viewDownloadImage;
private Images imageId;
private File folderName;
private String imageName;
private Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
if (msg.what == 1) {
if (pd != null) {
pd.dismiss();
}
Utils.showNetworkAlert(ImageViewAndDownload.this);
} else if (msg.what == 2) {
if (pd != null) {
pd.dismiss();
}
Utils.displayMessage("Image downloade succesfully",
ImageViewAndDownload.this);
// Media scaning
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://"
+ Environment.getExternalStorageDirectory())));
} else if (msg.what == 3) {
if (pd != null) {
pd.dismiss();
}
Utils.displayMessage("Image already downloaded ",
ImageViewAndDownload.this);
} else if (msg.what == 4) {
if (pd != null) {
pd.dismiss();
}
displayImageFromUrl((Bitmap) msg.obj);
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.imagedisplay);
viewDownloadImage = (ImageView) findViewById(R.id.viewImage);
btnImageDownload = (Button) findViewById(R.id.btnImageDownload);
imageId = new Images();
imageName = imageId.getImageId();
LoadImageFromWeb(Constant.IMAGE_BASE_URL + File.separator + imageName);
btnImageDownload.setOnClickListener(this);
}
public void onClick(View v) {
if (v == btnImageDownload) {
pd = ProgressDialog.show(ImageViewAndDownload.this, "",
"Downloading Image....", true, false);
new Thread(new Runnable() {
public void run() {
try {
String imageUrl = Constant.IMAGE_BASE_URL
+ File.separator + imageName;
String isDownloded = downloadImage(imageUrl, imageName);
if (isDownloded.equalsIgnoreCase("complete")) {
handler.sendEmptyMessage(2);
} else if (isDownloded.equalsIgnoreCase("")) {
handler.sendEmptyMessage(3);
} else {
handler.sendEmptyMessage(1);
}
} catch (Exception e) {
e.printStackTrace();
handler.sendEmptyMessage(1);
}
}
}).start();
}
}
// set display image to Imageview
public void displayImageFromUrl(Bitmap obj) {
viewDownloadImage.setImageBitmap(obj);
}
// image display from the webview
private void LoadImageFromWeb(final String url1) {
pd = ProgressDialog.show(ImageViewAndDownload.this, "",
"Loading Image....", true, false);
new Thread(new Runnable() {
public void run() {
try {
URL url = new URL(url1);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
InputStream is = connection.getInputStream();
Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(is, null, options);
if (options.outWidth > 3000 || options.outHeight > 2000) {
options.inSampleSize = 4;
} else if (options.outWidth > 2000
|| options.outHeight > 1500) {
options.inSampleSize = 3;
} else if (options.outWidth > 1000
|| options.outHeight > 1000) {
options.inSampleSize = 2;
}
// Do the actual decoding
options.inJustDecodeBounds = false;
is.close();
is = getHTTPConnectionInputStream(url1);
Bitmap myBitmap = BitmapFactory.decodeStream(is, null,
options);
is.close();
if (myBitmap != null) {
Message msg = new Message();
msg.obj = myBitmap;
msg.what = 4;
handler.sendMessage(msg);
} else {
handler.sendEmptyMessage(1);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
public InputStream getHTTPConnectionInputStream(String url1) {
URL url;
InputStream is = null;
try {
url = new URL(url1);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
is = connection.getInputStream();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return is;
}
// image download code
public String downloadImage(String imageDownloadUrl, String imageName) {
// create directory in SDCARD
if (android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED))
folderName = new File(Constant.STORE_IN_FOLDER);
else
folderName = getFilesDir();
if (!folderName.exists())
folderName.mkdirs();
String response = "";
// create file name and file.
File storeImageInSDCard = new File(folderName + File.separator
+ imageName);
if (!(storeImageInSDCard.exists() && storeImageInSDCard.length() > 0)) {
// start download image
response = downloadFile(imageDownloadUrl, imageName,
folderName.toString());
}
return response;
}
// start download image
public String downloadFile(final String url, final String name,
String foldername) {
File file;
FileOutputStream os = null;
Bitmap myBitmap;
try {
URL url1 = new URL(url.replaceAll(" ", "%20"));
System.out.println("Image url :::" + url1);
HttpURLConnection urlConnection = (HttpURLConnection) url1
.openConnection();
urlConnection.setDoOutput(false);
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// here create a file which define folder name and image name with
// extension.
file = new File(foldername, name + ".jpg");
InputStream inputStream = urlConnection.getInputStream();
byte[] buffer = new byte[1024];
int bufferLength = 0;
os = new FileOutputStream(file);
while ((bufferLength = inputStream.read(buffer)) > 0) {
os.write(buffer, 0, bufferLength);
}
os.flush();
os.close();
// if image size is too large we can scale image than download.
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
myBitmap = BitmapFactory
.decodeFile(file.getAbsolutePath(), options);
if (options.outWidth > 3000 || options.outHeight > 2000) {
options.inSampleSize = 4;
} else if (options.outWidth > 2000 || options.outHeight > 1500) {
options.inSampleSize = 3;
} else if (options.outWidth > 1000 || options.outHeight > 1000) {
options.inSampleSize = 2;
}
options.inJustDecodeBounds = false;
myBitmap = BitmapFactory
.decodeFile(file.getAbsolutePath(), options);
os = new FileOutputStream(file);
myBitmap.compress(CompressFormat.JPEG, 90, os);
os.flush();
os.close();
myBitmap.recycle();
return "complete";
} catch (SQLException e) {
e.printStackTrace();
return "error";
} catch (Exception e) {
e.printStackTrace();
return "error";
}
}
}
Link to the LogCat
You have:
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://"
+ Environment.getExternalStorageDirectory())));
First, this was never something appropriate to use.
Second, it is blocked now, because it was never something appropriate to use, and now Google is stopping it on newer versions of Android.
The proper approach is to use MediaScannerConnection and its scanFile() method, or perhaps ACTION_MEDIA_SCANNER_SCAN_FILE.

Code not hitting the server side

I am trying to send an image from android mobile to .NET server, android code:-
package com.example.imageupload;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.util.Base64;
import android.util.Log;
import android.view.Menu;
public class MainActivity extends Activity {
InputStream mInputStream;
String mUrl = "http://10.0.2.2:49246/WebSite1/";
// Async task helps to run network operations in Non-UI thread..
private class GetRouteInfo extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params)
{
try
{
//resize the bitmap...
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/android.jpg";
Bitmap bitmap = resizeBitMapImage1(path, 800, 600);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG,30, stream);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("image_data", Base64.encodeToString(stream.toByteArray(),Base64.NO_WRAP)));
stream.flush();
stream.close();
bitmap.recycle();
nameValuePairs.add(new BasicNameValuePair("FileName", "TrueSeeImage"));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(mUrl);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response1 = httpclient.execute(httppost);
Log.i("response", response1.toString());
Log.i("DataUploaderOffline_Image ","Status--> Completed");
}
catch (Exception e) {
Log.i("SvcMgr", "Service Execution Failed!", e);
}
finally {
Log.i("SvcMgr", "Service Execution Completed...");
}
return null;
}
#Override
protected void onCancelled() {
Log.i("SvcMgr", "Service Execution Cancelled");
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Log.i("SvcMgr", "Service Execution cycle completed");
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new GetRouteInfo().execute();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
public String convertResponseToString(HttpResponse response) throws IllegalStateException, IOException{
String res = "";
StringBuffer buffer = new StringBuffer();
mInputStream = response.getEntity().getContent();
int contentLength = (int) response.getEntity().getContentLength(); //getting content length…..
System.out.println("contentLength : " + contentLength);
if (contentLength < 0){
}
else{
byte[] data = new byte[512];
int len = 0;
try
{
while (-1 != (len = mInputStream.read(data)) )
{
buffer.append(new String(data, 0, len)); //converting to string and appending to stringbuffer…..
}
}
catch (IOException e)
{
e.printStackTrace();
}
try
{
mInputStream.close(); // closing the stream…..
}
catch (IOException e)
{
e.printStackTrace();
}
res = buffer.toString(); // converting stringbuffer to string…..
System.out.println("Result : " + res);
}
return res;
}
// Method to compress image..
// Input : filepath, target width, target height..
// Output : resized bitmap image..
public static Bitmap resizeBitMapImage1(String filePath, int targetWidth,int targetHeight) {
Bitmap bitMapImage = null;
try {
Options options = new Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, options);
double sampleSize = 0;
Boolean scaleByHeight = Math.abs(options.outHeight - targetHeight) >= Math
.abs(options.outWidth - targetWidth);
if (options.outHeight * options.outWidth * 2 >= 1638) {
sampleSize = scaleByHeight ? options.outHeight / targetHeight
: options.outWidth / targetWidth;
sampleSize = (int) Math.pow(2d,Math.floor(Math.log(sampleSize) / Math.log(2d)));
}
options.inJustDecodeBounds = false;
options.inTempStorage = new byte[128];
while (true) {
try {
options.inSampleSize = (int) sampleSize;
bitMapImage = BitmapFactory.decodeFile(filePath, options);
break;
} catch (Exception ex) {
try {
sampleSize = sampleSize * 2;
} catch (Exception ex1) {
}
}
}
} catch (Exception ex) {
}
return bitMapImage;
}
}
And the .NET part is
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (System.IO.Directory.Exists(Server.MapPath("~/Data")))
{
}
else
{
System.IO.Directory.CreateDirectory(Server.MapPath("~/Data"));
}
if (Request.InputStream.Length != 0 && Request.InputStream.Length < 32768)
{
Response.ContentType = "text/plain";
string c = Request.Form["image_data"];
string FileName = Request.Form["FileName"];
byte[] bytes = Convert.FromBase64String(c);
System.Drawing.Image image;
using (MemoryStream ms = new MemoryStream(bytes))
{
image = System.Drawing.Image.FromStream(ms);
image.RotateFlip(System.Drawing.RotateFlipType.Rotate90FlipNone);
String Fname = FileName + ".jpeg";
image.Save(Server.MapPath("save\\" + Fname), System.Drawing.Imaging.ImageFormat.Jpeg);
Response.End();
}
}
}
}
When I try to access the server side code from android browser it hits the server side code in the debug mode, but when I run the program from eclipse or debug the program from eclipse, it doesn't hit the code in the visual studio. What could be the reason?

post image in Instagram

Question : In my app I need to post image in Instagram just like FB or Twitter.
What I have already done : Login and fetched photographs from the Instagram to my own app. But not getting any way for image posting in Instagram.
Yet it is not possible to post image in Instagram like FB or twitter.
But this is another way to achieve this using already installed Instagram and if not this will notify user to download app .
public void onClick(View v) {
Intent intent = getPackageManager().getLaunchIntentForPackage("com.instagram.android");
if (intent != null)
{
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.setPackage("com.instagram.android");
try {
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(MediaStore.Images.Media.insertImage(getContentResolver(), imagePath, "I am Happy", "Share happy !")));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
shareIntent.setType("image/jpeg");
startActivity(shareIntent);
}
else
{
// bring user to the market to download the app.
// or let them choose an app?
intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setData(Uri.parse("market://details?id="+"com.instagram.android"));
startActivity(intent);
}
}
No, you can't. Quoted from Instagram API docs :
At this time, uploading via the API is not possible. We made a conscious choice not to add this for the following reasons:
Instagram is about your life on the go – we hope to encourage photos from within the app. However, in the future we may give whitelist access to individual apps on a case by case basis.
We want to fight spam & low quality photos. Once we allow uploading from other sources, it's harder to control what comes into the Instagram ecosystem. All this being said, we're working on ways to ensure users have a consistent and high-quality experience on our platform.
UPDATE: However, if you're working on iOS (though you tagged Android), there is a way to "send" a photo (in fact, it opens the image in Instagram) via Custom URL Scheme. See this.
Try this link :
You can use this class to upload image to instagram.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpCookie;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.net.ssl.HttpsURLConnection;
import org.apache.commons.codec.binary.Hex;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class InstagramPostHelper {
private static InstagramPostHelper instance = null;
protected InstagramPostHelper() {}
public static InstagramPostHelper getInstance() {
if (instance == null) {
instance = new InstagramPostHelper();
}
return instance;
}
private String GenerateSignature(String value, String key)
{
String result = null;
try {
byte[] keyBytes = key.getBytes();
SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA256");
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(signingKey);
byte[] rawHmac = mac.doFinal(value.getBytes());
byte[] hexBytes = new Hex().encode(rawHmac);
result = new String(hexBytes, "UTF-8");
}
catch (Exception e) {
}
return result;
}
private static final String COOKIES_HEADER = "Set-Cookie";
public static java.net.CookieManager msCookieManager = new java.net.CookieManager();
private HttpsURLConnection conn;
private static String TextUtilsJoin(CharSequence delimiter, List<HttpCookie> list) {
StringBuilder sb = new StringBuilder();
boolean firstTime = true;
for (Object token: list) {
if (token.toString().trim().length()<1) continue;
if (firstTime) {
firstTime = false;
} else {
sb.append(delimiter + " ");
}
sb.append(token);
}
return sb.toString();
}
private String GetJSONStringAndPostData(String jsonaddress,String postdata,String agent)
{
String sonuc = "";
try {
byte[] postDataBytes = postdata.toString().getBytes("UTF-8");
URL url = new URL(jsonaddress);
conn = (HttpsURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
conn.setRequestProperty("User-Agent", agent);
//Set Cookies
if(msCookieManager.getCookieStore().getCookies().size() > 0)
{
conn.setRequestProperty("Cookie", TextUtilsJoin(";", msCookieManager.getCookieStore().getCookies()));
}
conn.setDoOutput(true);
conn.getOutputStream().write(postDataBytes);
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
//Get Cookies
Map<String, List<String>> headerFields = conn.getHeaderFields();
List<String> cookiesHeader = headerFields.get(COOKIES_HEADER);
if(cookiesHeader != null)
{
for (String cookie : cookiesHeader)
{
msCookieManager.getCookieStore().add(null,HttpCookie.parse(cookie).get(0));
}
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
while ((output = br.readLine()) != null) {
sonuc += output;
}
conn.disconnect();
} catch (MalformedURLException e) {
return "";
} catch (IOException e) {
return "";
}
return sonuc;
}
public void SendImage(String Caption,byte[] ImageByteArray) throws UnsupportedEncodingException, ParseException
{
String Agent = "Instagram 6.21.2 Android (19/4.4.2; 480dpi; 1152x1920; Meizu; MX4; mx4; mt6595; en_US)";
String Guid = java.util.UUID.randomUUID().toString();
String DeviceId = "android-" + Guid;
String Data = "{\"device_id\":\"" + DeviceId + "\",\"guid\":\"" + Guid + "\",\"username\":\"MYUSERNAME\",\"password\":\"MYPASSWORD\",\"Content-Type\":\"application/x-www-form-urlencoded; charset=UTF-8\"}";
String Sig = GenerateSignature(Data, "25eace5393646842f0d0c3fb2ac7d3cfa15c052436ee86b5406a8433f54d24a5");
Data = "signed_body=" + Sig + "." + URLEncoder.encode(Data, "UTF-8") + "&ig_sig_key_version=4";
if (msCookieManager.getCookieStore()!= null)
{
msCookieManager.getCookieStore().removeAll();
}
//Login Request
String login = GetJSONStringAndPostData("https://instagram.com/api/v1/accounts/login/", Data,Agent);
JSONParser parser = new JSONParser();
Object obj = parser.parse(login);
JSONObject jsonObject = (JSONObject) obj;
if (((String) jsonObject.get("status")).equals("ok")) //Login SuccessFul
{
//Login Successful
System.out.println("Login Successful !");
//Post Image
String upload = "";
try {
final HttpMultipartHelper http = new HttpMultipartHelper(new URL("https://instagram.com/api/v1/media/upload/"));
http.addFormField("device_timestamp", Long.toString((new Date()).getTime()));
http.addFilePart("photo", ImageByteArray);
final byte[] bytes = http.finish();
upload = new String(bytes);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(upload);
obj = parser.parse(upload);
jsonObject = (JSONObject) obj;
if (((String) jsonObject.get("status")).equals("ok")) //Login SuccessFul
{
String mediaID = (String) jsonObject.get("media_id");
Data = "{\"device_id\":\"" + DeviceId + "\",\"guid\":\"" + Guid + "\",\"media_id\":\"" + mediaID + "\",\"caption\":\"" + Caption + "\",\"device_timestamp\":\"" + Long.toString((new Date()).getTime()).substring(0,10) + "\",\"source_type\":\"5\",\"filter_type\":\"0\",\"extra\":\"{}\",\"Content-Type\":\"application/x-www-form-urlencoded; charset=UTF-8\"}";
Sig = GenerateSignature(Data, "25eace5393646842f0d0c3fb2ac7d3cfa15c052436ee86b5406a8433f54d24a5");
Data = "signed_body=" + Sig + "." + URLEncoder.encode(Data, "UTF-8") + "&ig_sig_key_version=6";
//Login Request
System.out.println(Data);
String result = GetJSONStringAndPostData("https://instagram.com/api/v1/media/configure/", Data,Agent);
System.out.println(result);
}
}
else //Login UnsuccessFul
{
System.out.println("Login Unsuccessful !" + login);
}
}
}
https://gist.github.com/ecdundar/d5b6bdcc2035448fc9cd
It seems we're now able to do it, for more you can check official docs here
Try this
public void ShareInsta() {
File dir = new File(Environment.getExternalStorageDirectory(), "FolderName");
File imgFile = new File(dir, "0.png");
Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.setType("image/*");
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + imgFile));
sendIntent.putExtra(Intent.EXTRA_TEXT, "<---MY TEXT--->.");
sendIntent.setPackage("com.instagram.android");
sendIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
try {
startActivity(Intent.createChooser(sendIntent, "Share images..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(SaveAndShareActivity.this, "Please Install Instagram", Toast.LENGTH_LONG).show();
}
}

how to send audio file from android client to servlet server

I want to send an audio file .mp3 file from android client to servlet server and save it in a location. If I play that saved .mp3 file in that location it should play.
My question is there a way to send a .mp3 file directly from client to server and retrieve that mp3 file in servlet.
My client side code is as follows:
package com.android.audiorecord;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import org.apache.commons.io.FileUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import com.android.audiofileplayer.StreamingMp3Player;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
public class AudioRecordActivity extends Activity
{
private static final String LOG_TAG = "AudioRecordTest";
private static String mFileName = null;
private String url = "QRFileSaveServlet";
String result;
byte[] value;
String s;
byte[] filebyte,clientbyte;
String readString;
private RecordButton mRecordButton = null;
private MediaRecorder mRecorder = null;
private SubmitButton mSubmitButton = null;
private PlayButton mPlayButton = null;
private MediaPlayer mPlayer = null;
String fileresult = "";
HttpResponse response;
private void onRecord(boolean start) {
if (start) {
startRecording();
} else {
stopRecording();
}
}
private void onPlay(boolean start) {
if (start) {
startPlaying();
} else {
stopPlaying();
}
}
private void startPlaying() {
mPlayer = new MediaPlayer();
try {
mPlayer.setDataSource(mFileName);
mPlayer.prepare();
mPlayer.start();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
}
private void stopPlaying() {
mPlayer.release();
mPlayer = null;
}
private void startRecording() {
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
mRecorder.setOutputFile(mFileName);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try {
mRecorder.prepare();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
mRecorder.start();
}
/* public boolean saveas(int ressound){
byte[] buffer=null;
InputStream fIn = getBaseContext().getResources().openRawResource(ressound);
int size=0;
try {
size = fIn.available();
buffer = new byte[size];
fIn.read(buffer);
fIn.close();
} catch (IOException e) {
// TODO Auto-generated catch block
return false;
}
String path="/sdcard/media/audio/ringtones/";
String filename="examplefile"+".ogg";
boolean exists = (new File(path)).exists();
if (!exists){new File(path).mkdirs();}
FileOutputStream save;
try {
save = new FileOutputStream(path+filename);
save.write(buffer);
save.flush();
save.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
return false;
} catch (IOException e) {
// TODO Auto-generated catch block
return false;
}
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://"+path+filename)));
File k = new File(path, filename);
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, k.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, "exampletitle");
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/ogg");
values.put(MediaStore.Audio.Media.ARTIST, "cssounds ");
values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true);
values.put(MediaStore.Audio.Media.IS_ALARM, true);
values.put(MediaStore.Audio.Media.IS_MUSIC, false);
//Insert it into the database
this.getContentResolver().insert(MediaStore.Audio.Media.getContentUriForPath(k.getAbsolutePath()), values);
return true;
} */
private void stopRecording() {
mRecorder.stop();
mRecorder.release();
// mRecorder.reset();
mRecorder = null;
}
class RecordButton extends Button {
boolean mStartRecording = true;
OnClickListener clicker = new OnClickListener() {
public void onClick(View v) {
onRecord(mStartRecording);
if (mStartRecording) {
setText("Stop recording");
} else {
setText("Start recording");
}
mStartRecording = !mStartRecording;
}
};
public RecordButton(Context ctx) {
super(ctx);
setText("Start recording");
setOnClickListener(clicker);
}
}
class PlayButton extends Button {
boolean mStartPlaying = true;
OnClickListener clicker = new OnClickListener() {
public void onClick(View v) {
onPlay(mStartPlaying);
if (mStartPlaying) {
setText("Stop playing");
} else {
setText("Start playing");
}
mStartPlaying = !mStartPlaying;
}
};
public PlayButton(Context ctx) {
super(ctx);
setText("Start playing");
setOnClickListener(clicker);
}
}
class SubmitButton extends Button {
OnClickListener clicker = new OnClickListener() {
public void onClick(View v) {
File f = new File(Environment.getExternalStorageDirectory()+"/audiorecordtest.mp3");
//
//byte[] file = fileresult.getBytes();
try {
filebyte = FileUtils.readFileToByteArray(f);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("$$$$$$$$$$$" + filebyte);
clientbyte = Base64.encode(filebyte, MODE_APPEND);//(filebyte, MODE_APPEND);
s= new String(clientbyte);
System.out.println("**************" + s);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("Audiofile", s));
result = AudioServer.executePost(url, nameValuePairs);
result = result.trim();
System.out.println("response recieved " + result);
if(result!=null){
Bundle bundle = new Bundle();
Intent explicitIntent = new Intent(AudioRecordActivity.this,
StreamingMp3Player.class);
bundle.putString("result", result);
explicitIntent.putExtras(bundle);
startActivity(explicitIntent);
}
}
};
public SubmitButton(Context ctx) {
super(ctx);
setText("Save");
setOnClickListener(clicker);
}
}
public AudioRecordActivity() {
mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
mFileName += "/audiorecordtest.mp3";
}
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
LinearLayout ll = new LinearLayout(this);
mRecordButton = new RecordButton(this);
ll.addView(mRecordButton,
new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
0));
mPlayButton = new PlayButton(this);
ll.addView(mPlayButton,
new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
0));
mSubmitButton = new SubmitButton(this);
ll.addView(mSubmitButton, new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT, 0));
setContentView(ll);
}
#Override
public void onPause() {
super.onPause();
if (mRecorder != null) {
mRecorder.release();
mRecorder = null;
}
if (mPlayer != null) {
mPlayer.release();
mPlayer = null;
}
}
}
in this can i send audiorecordtest.mp3 file direcly to server without encoding to byte[] and send it in namevalue pair.
My server side code is as follows:
package com.gsr.qrbarcode;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import com.android.gsr.utils.AudioSampleReader;
import com.android.gsr.utils.AudioSampleWriter;
import com.android.gsr.utils.Base64;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
//import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFileFormat.Type;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;
import org.apache.commons.io.FileUtils;
/**
* Servlet implementation class QRFileSaveServlet
*/
//#WebServlet("/QRFileSaveServlet")
public class QRFileSaveServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
AudioInputStream ais;
/**
* Default constructor.
*/
public QRFileSaveServlet() {
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String qrfile= request.getParameter("Audiofile");
System.out.println("String Parameter \"" +qrfile );
byte[] audiofile=Base64.decode(qrfile);
String newStr = new String(audiofile);
// Display the contents of the byte array.
System.out.println("The new String equals \"" +newStr + "\"");
String filePath = this.getServletContext().getRealPath("/")+"";
System.out.println("Path of the file " + filePath);
String fileupload="AudioFileStorage";
//PrintWriter out = response.getWriter();
File f;
f= new File(filePath);
//int status = 0;
if(f.exists()) {
filePath += fileupload;
f = new File(filePath);
if(!f.exists()){
f.mkdir();
}
f = new File(filePath,"test.mp3");
if(!f.exists()) {
FileOutputStream fos = new FileOutputStream(f);
fos.write(audiofile);
fos.flush();
fos.close();
} else {
//out.println("failure");
ServletOutputStream stream = null;
BufferedInputStream buf = null;
try{
stream = response.getOutputStream();
// File mp3 = new File(mp3Dir + "/" + fileName);
response.setContentType("audio/mpeg");
response.addHeader("Content-Disposition","attachment; filename="+f );
response.setContentLength( (int) f.length() );
FileInputStream input = new FileInputStream(f);
buf = new BufferedInputStream(input);
int readBytes = 0;
while((readBytes = buf.read()) != -1)
stream.write(readBytes);
System.out.println("Response Stream"+stream);
} catch (IOException ioe){
throw new ServletException(ioe.getMessage());
} finally {
if(stream != null)
stream.close();
if(buf != null)
buf.close();
}
}
}
if (filePath == null || filePath.equals(""))
throw new ServletException(
"Invalid or non-existent mp3Dir context-param.");
URL url = null;
try{
url = f.toURL();
System.out.println("URL : "+ url);
System.out.println("Converting process Successfully");
}
catch (MalformedURLException me){
System.out.println("Converting process error");
}
//String rfilepath=this.getServletContext().getRealPath("/")+" AudioFileStorage/test.mp3";
//System.out.println("Path of the rfilepath " + rfilepath);
}
}
here can i get that audiorecordtest.mp3 file directly from client without decoding in server side and play it in this servlet
my server connection in local for client
executepost() is as follows:
package com.android.audio;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
public class AudioServer {
static InputStream is;
private static String API_URL = "http://192.168.15.71:8088/QRBarCodeServer/";
public static String executePost(String apiurl,
ArrayList<NameValuePair> urlParameters) {
try {
// Create connection
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(API_URL + apiurl);
httppost.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
// Get Response
// InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response1 = new StringBuffer();
while ((line = rd.readLine()) != null) {
response1.append(line);
response1.append('\r');
}
rd.close();
return response1.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static String executeHttpGet(String apiurl) throws Exception {
BufferedReader in = null;
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(API_URL + apiurl);
request.setURI(new URI(apiurl));
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity()
.getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
here is simple way to do that
1: from android side read that .mp3 file and create base64String from it.
2: At servier side read this base64String and convert it back to .mp3 file.
to convert any file to base64String following is the process
File file = new File(Environment.getExternalStorageDirectory() + "/hello-4.wav");
byte[] bytes = FileUtils.readFileToByteArray(file);
String encoded = Base64.encodeToString(bytes, 0);
You can reach it using apache MultipartEntity:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(BASE_URL);
MultipartEntity mpEntity = new MultipartEntity();
mpEntity.addPart("Audiofile", new FileBody(file, "audio/mpeg"));
post.setEntity(mpEntity);
HttpResponse res = client.execute(post);
Yea you can send this in Servlet there is Mime type mime means multimedia extension
I am sending code i can guarantee that it will work in Servlet in java and you should take
care for android by own
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class SendMp3Envious extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String fileName = (String) request.getParameter("file");
if (fileName == null || fileName.equals(""))
throw new ServletException(
"Invalid or non-existent file parameter in SendMp3 servlet.");
if (fileName.indexOf(".mp3") == -1)
fileName = fileName + ".mp3";
String mp3Dir = getServletContext().getInitParameter("mp3-dir");
if (mp3Dir == null || mp3Dir.equals(""))
throw new ServletException(
"Invalid or non-existent mp3Dir context-param.");
ServletOutputStream stream = null;
BufferedInputStream buf = null;
try {
stream = response.getOutputStream();
File mp3 = new File(mp3Dir + "/" + fileName);
//set response headers
response.setContentType("audio/mpeg");
response.addHeader("Content-Disposition", "attachment; filename="
+ fileName);
response.setContentLength((int) mp3.length());
FileInputStream input = new FileInputStream(mp3);
buf = new BufferedInputStream(input);
int readBytes = 0;
//read from the file; write to the ServletOutputStream
while ((readBytes = buf.read()) != -1)
stream.write(readBytes);
} catch (IOException ioe) {
throw new ServletException(ioe.getMessage());
} finally {
if (stream != null)
stream.close();
if (buf != null)
buf.close();
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}

Categories

Resources