I need to upload photo on checkin using FourSquare.If anybody has done it,Please help me in passing parameters.I have referred FourSquare Offical Document :
https://developer.foursquare.com/docs/photos/add. I am facing issue in Last three parameters.
Please Help me if you have done it.Thank You in Advance...
The parameters postUrl, postContentId, and postText are optional, so you do not need to provide them. postUrl and postContentId are used to provide a link that your photo can link to for more information. postText is a short comment about the photo.
/*
* put foursquare sdk file into projects libs folder and the later code into the Activity file
*/
todaydate = Latest Date;
venueId = The Venue Id is important.
URL = The image url from which the image will be downloaded to sd card;
foursquare = new Foursquare(
"Your Client Id", //*client id
"Your Client Secret", //*client secret
"Callback Url");
foursquare.authorize(ActivityName.this, new FoursquareAuthenDialogListener());
// Creates Bitmap from InputStream and returns it
private Bitmap downloadImage(String url) {
Bitmap bitmap = null;
InputStream stream = null;
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
try {
stream = getHttpConnection(url);
bitmap = BitmapFactory.decodeStream(stream, null, bmOptions);
stream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
return bitmap;
}
// Makes HttpURLConnection and returns InputStream
private InputStream getHttpConnection(String urlString)
throws IOException {
InputStream stream = null;
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
try {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
stream = httpConnection.getInputStream();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return stream;
}
#SuppressLint("SdCardPath")
private class FoursquareAuthenDialogListener implements DialogListener {
#Override
public void onComplete(Bundle values) {
foursquareAccessToken = Foursquare.mAccessToken;
//Toast.makeText(getApplicationContext(), "TOKEN: " + foursquareAccessToken, Toast.LENGTH_LONG).show();
new downloadUploadedImage().execute();
}
#Override
public void onFoursquareError(FoursquareError e) {
// TODO Auto-generated method stub
}
#Override
public void onError(DialogError e) {
// TODO Auto-generated method stub
}
#Override
public void onCancel() {
// TODO Auto-generated method stub
}
}
/*
* downloadUploadedImage Class will download image from url and convert to bitmap image,
* using that bitmap image then convert it to file and get the file path from sd card
* to upload image to fs from sdcard.
*/
public class downloadUploadedImage extends AsyncTask<String, Void, String>{
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = ProgressDialog.show(MyActivityName.this, "", "Posting Image to Foursquare...", true);
}
#Override
protected String doInBackground(String... params) {
bitMapImage = downloadImage(URL);
writeExternalToCache(bitMapImage, file);
return null;
}
#Override
protected void onPostExecute(String result){
super.onPostExecute(result);
if(file.exists()){
//Toast.makeText(getApplicationContext(), "PIC PATH: " + file.toString(), Toast.LENGTH_LONG).show();
//Toast.makeText(getApplicationContext(), "PIC PATH: " + picPATH, Toast.LENGTH_LONG).show();
picturePath = file.toString();
BitmapFactory.Options options=new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(picturePath,options);
final int REQUIRED_SIZE=200;
//Find the correct scale value. It should be the power of 2.
int scale=1;
while(options.outWidth/scale/2>=REQUIRED_SIZE && options.outHeight/scale/2>=REQUIRED_SIZE)
scale*=2;
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=scale;
preview_bitmap = BitmapFactory.decodeFile(picturePath,o2);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
preview_bitmap.compress(CompressFormat.JPEG, 75, bos);
fileContent = bos.toByteArray(); //byte array static byte[] fileContent;
new UploadImageToFsProfile().execute();
} else {
//Toast.makeText(getApplicationContext(), "Image not exist in sdcard.", Toast.LENGTH_LONG).show();
}
}
}
public class UploadImageToFsProfile extends AsyncTask<String, Void, String>{//params,progress,result
#Override
protected void onPreExecute(){
super.onPreExecute();
}
#SuppressWarnings("deprecation")
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("https://api.foursquare.com/v2/photos/add");
try
{
#SuppressWarnings("deprecation")
/*
* To use MultipartEntity class use httpclient-X.x.jar , httpcore-X.x.jar ,httpmime-X.x.jar
* and apachemime4jcore-X.x.jar
*/
MultipartEntity entity = new MultipartEntity();
entity.addPart("v", new StringBody(todaydate));
entity.addPart("venueId", new StringBody(venueId));
entity.addPart("public", new StringBody("1"));
entity.addPart("oauth_token", new StringBody(foursquareAccessToken));
ByteArrayBody imgBody = new ByteArrayBody(ChFsLogin.fileContent, "image/jpeg", "FS_image");
entity.addPart("image",imgBody);
httppost.setEntity(entity);
HttpResponse response = httpclient.execute(httppost);
responseResult = inputStreamToString(response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e)
{ }
catch (IOException e)
{ }
return responseResult;
}
#Override
protected void onPostExecute(String result){
super.onPostExecute(result);
dialog.dismiss();
System.out.println("RES"+responseResult);
JSONObject obj;
try {
obj = new JSONObject(result);
//JSONArray meta =
obj = obj.getJSONObject("meta");
code = obj.getInt("code");
if(obj.has("errorDetail")){
Toast.makeText(getApplicationContext(), obj.getString("errorDetail"), Toast.LENGTH_LONG).show();
}
//Toast.makeText(getApplicationContext(), "code:"+code, Toast.LENGTH_LONG).show();
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if (code ==200) {
Toast.makeText(getApplicationContext(), "Your Image Has Successfully Posted to FourSquare.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Unable to Post Image to FourSquare.", Toast.LENGTH_LONG).show();
}
File fileToDelete = new File(file.toString());
boolean deleted = fileToDelete.delete();
if (deleted) {
} else {
}
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
e.printStackTrace();
}
return answer;
}
}
I successfully uploaded the images to Foursquare via the code below:
mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] bitmapdata = stream.toByteArray();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("https://api.foursquare.com/v2/photos/add");
try
{
MultipartEntity entity = new MultipartEntity();
entity.addPart("v", new StringBody("20121210"));
entity.addPart("venueId", new StringBody(venue.getId()));
entity.addPart("public", new StringBody("1"));
entity.addPart("oauth_token", new StringBody(mAccessToken));
ByteArrayBody imgBody = new ByteArrayBody(bitmapdata, "image/jpeg", "FS_image");
entity.addPart("image",imgBody);
httppost.setEntity(entity);
HttpResponse response = httpclient.execute(httppost);
Log.v("response","" +response);
responseResult = inputStreamToString(response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e)
{
Log.d(TAG, "Opening URL " +e);
}
Related
I am using .net Web services in my app. I have to upload image and put it on server but when I am getting socketTimeOutException each time.
// code to upload image
private void onCaptureImageResult(Intent data) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
ivImage.setImageBitmap(thumbnail);
imageFlag = true;
//get the current timeStamp and strore that in the time Variable
Long tsLong = System.currentTimeMillis() / 1000;
timestamp = tsLong.toString();
Bitmap image1 = ((BitmapDrawable) ivImage.getDrawable()).getBitmap();
new PaymentSlips(image1).execute();
}
// code for asynk task
private class PaymentSlips extends AsyncTask<String, Void, Void> {
ProgressDialog progressDialog;
String ResposeFromPaymentRequestApi;
private Bitmap userfile;
public PaymentSlips(Bitmap image) {
this.userfile = image;
}
#Override
protected Void doInBackground(String... params) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
//compress the image to jpg format
if (!(userfile == null))
userfile.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
/*
* encode image to base64 so that it can be picked by saveImage.php file
* */
String encodeImage = Base64.encodeToString(byteArrayOutputStream.toByteArray(), Base64.DEFAULT);
//generate hashMap to store encodedImage and the name
HashMap<String, String> detail = new HashMap<>();
detail.put("image", encodeImage);
try {
String dataToSend = hashMapToUrl(detail);
WebService wsc = new WebService();
ResposeFromPaymentRequestApi = wsc.PaymentSlips("1", dataToSend, "reqSlip", serviceToken, "PaymentSlips");
return null;
/*String response = Request.post(new Config().updateProfilePic, dataToSend);
//return the response
return response;*/
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(Void result) {
//Set response
try {
Log.e("TAG", "getimageupload" + ResposeFromPaymentRequestApi);
} catch (Exception e) {
e.printStackTrace();
}
progressDialog.dismiss();
}
#Override
protected void onPreExecute() {
//Make ProgressBar invisible
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Please wait.......");
progressDialog.show();
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
private String hashMapToUrl(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for (Map.Entry<String, String> entry : params.entrySet()) {
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
// code for .net web service
public static String PaymentSlips(String installmentid,String image,String slipStatus,String serviceToken, String webMethName) {
String resTxt = null;
SoapObject request = new SoapObject(NAMESPACE, webMethName);
PropertyInfo loginUserPI = new PropertyInfo();
// Adding firstname
loginUserPI.setName("installmentid");
loginUserPI.setValue(installmentid);
loginUserPI.setType(String.class);
request.addProperty(loginUserPI);
request.addProperty("image",""+image);
request.addProperty("slipStatus",""+slipStatus);
request.addProperty("serviceToken", "" + serviceToken);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try {
androidHttpTransport.call(SOAP_ACTION + webMethName, envelope);
SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
resTxt = response.toString();
} catch (Exception e) {
e.printStackTrace();
resTxt = "Error occured";
}
return resTxt;
}
I want to send the multiple images to server.I have created the bitmap for each selected images.But the last bitmap image are send to the server.How to send all bit map images at once in android.I have tried like this
class ImageUploadTask extends AsyncTask<String, Void, String> {
String sResponse = null;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialog = ProgressDialog.show(Room_addroom1.this, "Uploading",
"Please wait...", true);
dialog.show();
}
#Override
protected String doInBackground(String... params) {
try {
String url ="http://airbnb.abservetech.com/demo/public/mobile/hotel/roomsadd";
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
int i=0;
mImageIds = new ArrayList<String>();
ByteArrayBody mImageByteArray = null;
for ( i = 0; i < ImgData.size(); i++) {
Log.d("ImgData(i)--", String.valueOf(ImgData.get(i)));
Bitmap bitmap = decodeFile(ImgData.get(i));
String image = getStringImage(bitmap);
mImageIds.add(image);
Log.d("Image--", image);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byteArray = stream.toByteArray();
mImageByteArray = new ByteArrayBody(byteArray, Long.toString(System.currentTimeMillis()) + ".jpg");
entity.addPart("room_images", mImageByteArray);
Log.d("ByteArray--", String.valueOf(mImageByteArray));
// entity.addPart("room_images", mImageByteArray);
}
Log.d("ByteArray-out--", String.valueOf(mImageByteArray));
/* entity.addPart("room_images", new ByteArrayBody(byteArray,
"image/jpeg", params[1]));*/
entity.addPart("user_id", new StringBody("52"));
entity.addPart("room_type",new StringBody( "premium"));
entity.addPart("room_prize", new StringBody("2356"));
httpPost.setEntity(entity);
// String entityContentAsString = new String(bos.toByteArray());
// Log.e("multipartEntitty:", "" + entityContentAsString);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
entity.writeTo(bytes);
String content = bytes.toString();
String content1 = entity.toString();
/* Log.e("MultiPartEntityRequest:",content);
Log.e("MultiPartEntity---11:",content1);*/
HttpResponse response = httpClient.execute(httpPost,
localContext);
sResponse = EntityUtils.getContentCharSet(response.getEntity());
System.out.println("sResponse : " + sResponse);
} catch (Exception e) {
if (dialog.isShowing())
dialog.dismiss();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
return sResponse;
}
#Override
protected void onPostExecute(String sResponse) {
try {
if (dialog.isShowing())
dialog.dismiss();
if (sResponse != null) {
count++;
if (count <ImgData.size()) {
Toast.makeText(getApplicationContext(),
sResponse + " Photo uploaded successfully",
Toast.LENGTH_SHORT).show();
// new ImageUploadTask().execute(count + "", "hm" + count
// + ".jpg");
}
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage(),
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
}
}
First you can create bitmap to base64.
then create jsonstring of these all base64 String of bitmap and send JsonString to post the server.
That's easy wat to send multiple image to server.
Another way,
When you select first image then you create base64 of these image at a time you send base64 to server, then select another image and convert to base64 and send another base64 to server. That method also use for one by one image store to server.
try this :
mImageIds = new ArrayList<String>();
for ( i = 0; i < ImgData.size(); i++) {
Log.d("ImgData(i)--", String.valueOf(ImgData.get(i)));
Bitmap bitmap = decodeFile(ImgData.get(i));
String image = getStringImage(bitmap);
mImageIds.add(image);
Log.d("Image--", image);
entity.addPart("images", new StringBody(image));
}
The only thing you were doing wrong was you were intializing a new object of the ArrayList for every iteration of the for loop. So, only the last element was being added to the ArrayList. Moving it outside will solve your problem.
I want to check progress of uploading file by HttpUrlConnection. How I can do this? I've tried to calculate bytes when writing data in OutputStream but it's wrong, cause real uploading happens only when I call conn.getInputStream(), so I need somehow to check inputStream. Here is my code:
public static void uploadMovie(final HashMap<String, String> dataSource, final OnLoadFinishedListener finishedListener, final ProgressListener progressListener) {
if (finishedListener != null) {
new Thread(new Runnable() {
public void run() {
try {
String boundary = getMD5(dataSource.size()+String.valueOf(System.currentTimeMillis()));
MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();
multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
multipartEntity.setCharset(Charset.forName("UTF-8"));
for (String key : dataSource.keySet()) {
if (key.equals(MoviesFragmentAdd.USERFILE)) {
FileBody userFile = new FileBody(new File(dataSource.get(key)));
multipartEntity.addPart(key, userFile);
continue;
}
multipartEntity.addPart(key, new StringBody(dataSource.get(key),ContentType.APPLICATION_JSON));
}
HttpEntity entity = multipartEntity.build();
HttpURLConnection conn = (HttpsURLConnection) new URL(URL_API + "/video/addForm/").openConnection();
conn.setUseCaches(false);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept-Charset", "UTF-8");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Cache-Control", "no-cache");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("Content-length", entity.getContentLength() + "");
conn.setRequestProperty(entity.getContentType().getName(),entity.getContentType().getValue());
OutputStream os = conn.getOutputStream();
entity.writeTo(os);
os.close();
//Real upload starting here -->>
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
//<<--
JsonObject request = (JsonObject) gparser.parse(in.readLine());
if (!request.get("error").getAsBoolean()) {
//do something
}
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
}
Because you have to deal with upload, I'd suppose most time is taken when doing entity.writeTo(os);. Maybe the first contact to the server takes some time as well (DNS resolution, SSL-handshake, ...). The markers you set for "the real upload" are not correct IMO.
Now it depends on your Multipart-library, whether you can intercept writeTo. If it is clever and resource-efficient, it's iterating over the parts and streams the content one-by-one to the output stream. If not, and the .build() operation is creating a big fat byte[], then you could take this array, stream it in chunks to the server and tell your user how many percent of the upload is already done.
From a resource perspective I'd prefer not really knowing what happens. But if feedback is that important and if the movies are only a few megabytes in size, you could stream the Multipart-Entity first to a ByteArrayOutputStream and then write little chunks of the created byte-array to the server while notifying your user about progress. The following code is not validated or tested (you can see it as pseudo-code):
ByteArrayOutputStream baos = new ByteArrayOutputStream();
entity.writeTo(baos);
baos.close();
byte[] payload = baos.toByteArray();
baos = null;
OutputStream os = conn.getOutputStream();
int totalSize = payload.length;
int bytesTransferred = 0;
int chunkSize = 2000;
while (bytesTransferred < totalSize) {
int nextChunkSize = totalSize - bytesTransferred;
if (nextChunkSize > chunkSize) {
nextChunkSize = chunkSize;
}
os.write(payload, bytesTransferred, nextChunkSize); // TODO check outcome!
bytesTransferred += nextChunkSize;
// Here you can call the method which updates progress
// be sure to wrap it so UI-updates are done on the main thread!
updateProgressInfo(100 * bytesTransferred / totalSize);
}
os.close();
A more elegant way would be to write an intercepting OutputStream which registers progress and delegates the real write-operations to the underlaying "real" OutputStream.
Edit
#whizzzkey wrote:
I've re-checked it many times - entity.writeTo(os) DOESN'T do a real upload, it does conn.getResponseCode() or conn.getInputStream()
Now it's clear. HttpURLConnection is buffering your upload data, because it doesn't know the content-length. You've set the header 'Content-length', but oviously this is ignored by HUC. You have to call
conn.setFixedLengthStreamingMode(entity.getContentLength());
Then you should better remove the call to conn.setRequestProperty("Content-length", entity.getContentLength() + "");
In this case, HUC can write the headers and entity.writeTo(os) can really stream the data to the server. Otherwise the buffered data is sent when HUC knows how many bytes will be transferred. So in fact, getInputStream() tells HUC that you're finished, but before really reading the response, all the collected data has to be sent to the server.
I wouldn't recommend changing your code, but for those of you who don't know the exact size of the transferred data (in bytes, not characters!!), you can tell HUC that it should transfer the data in chunks without setting the exact content-length:
conn.setChunkedStreamingMode(-1); // use default chunk size
Right this code in your activity...
public class PublishPostToServer extends AsyncTask implements
ProgressListenerForPost {
public Context pContext;
public long totalSize;
private String response;
public PublishPostToServer(Context context) {
pContext = context;
}
protected void onPreExecute() {
showProgressDialog();
}
#Override
protected Boolean doInBackground(Void... params) {
boolean success = true;
try {
response = NetworkAdaptor.getInstance()
.upLoadMultipartImageToServer(
"",
"",
"", this, this); // Add file path, Authkey, caption
} catch (Exception e) {
success = false;
}
return success;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
//validateResponse(result, response);
}
#Override
protected void onProgressUpdate(Integer... values) {
try {
if (mProgressDialog != null) {
mProgressDialog.setProgress(values[0]);
}
} catch (Exception exception) {
}
}
#Override
public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));
}
}
private void showProgressDialog() {
try {
String dialogMsg = "Uploading Image...";
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage(dialogMsg);
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
} catch (Exception exception) {
}
}
Now, Make a NetworkAdapter Class
public String upLoadMultipartImageToServer(String sourceFileUri,
String auth_key, String caption, ProgressListenerForPost listiner,
PublishPostToServer asyncListiner) {
String upLoadServerUri = "" + "upload_image";
HttpPost httppost = new HttpPost(upLoadServerUri);
File file = new File(sourceFileUri);
if (file.exists()) {
FileBody filebodyVideo = new FileBody(file);
CustomMultiPartEntity multipartEntity = new CustomMultiPartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE, listiner);
try {
multipartEntity.addPart("auth_key", new StringBody(auth_key));
multipartEntity.addPart("caption", new StringBody(caption));
multipartEntity.addPart("image", filebodyVideo);
asyncListiner.totalSize = multipartEntity.getContentLength();
httppost.setEntity(multipartEntity);
}
catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
DefaultHttpClient mHttpClient = new DefaultHttpClient();
String response = "";
try {
response = mHttpClient.execute(httppost,
new MovieUploadResponseHandler());
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return response;
} else {
return null;
}
}
#SuppressWarnings("rawtypes")
private class MovieUploadResponseHandler implements ResponseHandler {
#Override
public Object handleResponse(HttpResponse response)
throws ClientProtocolException, IOException {
HttpEntity r_entity = response.getEntity();
String responseString = EntityUtils.toString(r_entity);
// DebugHelper.printData("UPLOAD", responseString);
return responseString;
}
}
public static boolean isValidResponse(String resultData) {
try {
} catch (Exception exception) {
//DebugHelper.printException(exception);
}
return true;
}
public String upLoadVideoToServer(String currentFilePath, String string,
PublishPostToServer publishPostToServer,
PublishPostToServer publishPostToServer2) {
// TODO Auto-generated method stub
return null;
}
I used this code to post image to facebook. But there is no response from this code. please help me.
//I had created onCreate() method as :
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
facebook = new Facebook(APP_ID);
restoreCredentials(facebook);
//requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
postToWall();
}
//used this code for postToWall(): In this method I gave path of a image to post //and this method is calling in onCreate().
private void postToWall() {
FileInputStream fis = null;
try {
fis = new FileInputStream("/mnt/sdcard/Blue_Dock_by_dimage.jpg");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;
Bitmap bm = BitmapFactory.decodeStream(fis);
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, stream); // where bm is bitmap from Sdcard
byte[] byteArray = stream.toByteArray();
Bundle param = new Bundle();
param = new Bundle();
param.putString("message", "All");
param.putString("filename", "TEst");
param.putByteArray("image", byteArray);
mAsyncRunner.request("me/photos", param, "POST", new fbRequestListener(), null);
}
//used this code for fbRequestListener() class:
public class fbRequestListener implements RequestListener {
public void onComplete(String response, Object state) {
// TODO Auto-generated method stub
Log.d("RESPONSE",""+response);
}
public void onIOException(IOException e, Object state) {
// TODO Auto-generated method stub
Log.d("RESPONSE",""+e);
showToast("Authentication with Facebook failed!");
finish();
}
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
// TODO Auto-generated method stub
Log.d("RESPONSE",""+e);
showToast("Authentication with onFileNotFoundException failed!");
finish();
}
public void onMalformedURLException(MalformedURLException e,
Object state) {
// TODO Auto-generated method stub
showToast("Authentication with onMalformedURLException!");
finish();
}
public void onFacebookError(FacebookError e, Object state) {
// TODO Auto-generated method stub
Log.d("RESPONSE",""+e);
showToast("Authentication with onFacebookError failed!");
finish();
}
}
you have to use GRAPH API for this or HACKBOOK Example
this is easy way...
download code from here
check below code..
replace below code in that example.
public static void postToWall1(String message, Context con, String url,
String Product) {
facebook1 = new Facebook(APP_ID);
Bundle parameters = new Bundle();
parameters.putString("caption", Product);
parameters.putString("description", "Share photo!");
parameters.putString("picture", "" + url);
parameters.putString("message", "" + message);
try {
facebook1.request("me");
String response = facebook1.request("me/feed", parameters, "POST");
if (response != null
|| !response.equals("")
|| !response.equals("false")
)
showToast("Message posted to your facebook wall!", con);
}
} catch (Exception e) {
showToast("Failed to post to wall!", con);
e.printStackTrace();
}
}
Try this code:
try {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(
"https://graph.facebook.com/me/photos?access_token="+ acess_token);
URL url = new URL("image_url");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap bi = BitmapFactory.decodeStream(input);
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bi.compress(CompressFormat.PNG,100, bos);
byte[] data = bos.toByteArray();
entity.addPart("source",new ByteArrayBody(data,"testimage.png"));
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost,localContext);
Log.v("response ", response+ "");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
I am developing an app for upload video to a Apache/PHP Server. In this moment I already can upload videos. I need show a progress bar while the file is being uploaded. I have the next code using AsyncTask and HTTP 4.1.1 Libraries for emulate the FORM.
class uploadVideo extends AsyncTask<Void,Void,String>{
#Override
protected String doInBackground(Void... params) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.youtouch.cl/videoloader/index.php");
try {
// Add your data
File input=new File(fileName);
MultipartEntity multi=new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
multi.addPart("video", new FileBody(input));
httppost.setEntity(multi);
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
BufferedReader reader = new BufferedReader(
new InputStreamReader(
entity.getContent(), "UTF-8"));
String sResponse = reader.readLine();
return sResponse;
} catch (ClientProtocolException e) {
Log.v("Uri Galeria", e.toString());
e.printStackTrace();
} catch (IOException e) {
Log.v("Uri Galeria", e.toString());
e.printStackTrace();
}
return "error";
}
#Override
protected void onProgressUpdate(Void... unsued) {
//Here I do should update the progress bar
}
#Override
protected void onPostExecute(String sResponse) {
try {
if (pd.isShowing())
pd.dismiss();
if (sResponse != null) {
JSONObject JResponse = new JSONObject(sResponse);
int success = JResponse.getInt("SUCCESS");
String message = JResponse.getString("MESSAGE");
if (success == 0) {
Toast.makeText(getApplicationContext(), message,
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"Video uploaded successfully",
Toast.LENGTH_SHORT).show();
}
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
e.getMessage(),
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
}
I need know where I can get how much bytes has been uploaded. File.length is the total size.
Have you tried extending FileBody? Presumably the POST will either call getInputStream() or writeTo() in order to actually send the file data to the server. You could extend either of these (including the InputStream returned by getInputStream()) and keep track of how much data has been sent.
thank to cyngus's idea I have resolved this issue. I have added the next code for tracking the uploaded bytes:
Listener on upload button:
btnSubir.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//pd = ProgressDialog.show(VideoAndroidActivity.this, "", "Subiendo Video", true, false);
pd = new ProgressDialog(VideoAndroidActivity.this);
pd.setMessage("Uploading Video");
pd.setIndeterminate(false);
pd.setMax(100);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.show();
//Thread thread=new Thread(new threadUploadVideo());
//thread.start();
new UploadVideo().execute();
}
});
Asynctask for run the upload:
class UploadVideo extends AsyncTask<Void,Integer,String> {
private FileBody fb;
#Override
protected String doInBackground(Void... params) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.youtouch.cl/videoloader/index.php");
int count;
try {
// Add your data
File input=new File(fileName);
// I created a Filebody Object
fb=new FileBody(input);
MultipartEntity multi=new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
multi.addPart("video",fb);
httppost.setEntity(multi);
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
//get the InputStream
InputStream is=fb.getInputStream();
//create a buffer
byte data[] = new byte[1024];//1024
//this var updates the progress bar
long total=0;
while((count=is.read(data))!=-1){
total+=count;
publishProgress((int)(total*100/input.length()));
}
is.close();
HttpEntity entity = response.getEntity();
BufferedReader reader = new BufferedReader(
new InputStreamReader(
entity.getContent(), "UTF-8"));
String sResponse = reader.readLine();
return sResponse;
} catch (ClientProtocolException e) {
Log.v("Uri Galeria", e.toString());
e.printStackTrace();
} catch (IOException e) {
Log.v("Uri Galeria", e.toString());
e.printStackTrace();
}
return "error";
}
#Override
protected void onProgressUpdate(Integer... unsued) {
pd.setProgress(unsued[0]);
}
#Override
protected void onPostExecute(String sResponse) {
try {
if (pd.isShowing())
pd.dismiss();
if (sResponse != null) {
Toast.makeText(getApplicationContext(),sResponse,Toast.LENGTH_SHORT).show();
Log.i("Splash", sResponse);
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
e.getMessage(),
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
}
}
The progress bar load is bit slow (in starting seems be freeze and then load of 1 to 100 very fast), but works.
Sorry, my english is regular :(.
Check my answer here, I guess it answers your question:
But update the file path of the image to your to be uploaded video
https://stackoverflow.com/questions/15572747/progressbar-in-asynctask-is-not-showing-on-upload
What I used to do is to extends org.apache.http.entity.ByteArrayEntity and override the writeTo function like below, while bytes output it will pass though writeTo(), so you can count current output bytes:
#Override
public void writeTo(final OutputStream outstream) throws IOException
{
if (outstream == null) {
throw new IllegalArgumentException("Output stream may not be null");
}
InputStream instream = new ByteArrayInputStream(this.content);
try {
byte[] tmp = new byte[512];
int total = (int) this.content.length;
int progress = 0;
int increment = 0;
int l;
int percent;
// read file and write to http output stream
while ((l = instream.read(tmp)) != -1) {
// check progress
progress = progress + l;
percent = Math.round(((float) progress / (float) total) * 100);
// if percent exceeds increment update status notification
// and adjust increment
if (percent > increment) {
increment += 10;
// update percentage here !!
}
// write to output stream
outstream.write(tmp, 0, l);
}
// flush output stream
outstream.flush();
} finally {
// close input stream
instream.close();
}
}