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();
}
}
Related
I have the following function to allow my android app to communicate with a web server. However the app shows a 'Please Wait' message when I call this code and only disappears if a new activity loads in or if I press the back button. Where is the Please wait coming from and how can I avoid it appearing? Thanks
package util.sapa.sapacontainermanager5;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
public class SimpleWebCalls {
public String executeHttpGet(String serverIP, String nvp) {
String lines="";
serverIP="???????????";
URL url = null;
try {
url = new URL("http://" + serverIP + "/WCF.aspx?" + nvp);
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) url.openConnection();
try {
conn.setRequestMethod("GET");
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
lines+=line;
}
in.close();
return lines;
} catch (IOException e) {
e.printStackTrace();
}
} catch (ProtocolException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
return "";
}
}
the above class is called from:
public String GetDataFromServer(String serverIP,String nvp) {
SimpleWebCalls tWebCall = new SimpleWebCalls();
String sReturn="";
sReturn= tWebCall.executeHttpGet(serverIP,nvp);
return sReturn;
}
the above function is called from:
String data="";
data="doAction=location&u=" + sess.getUserName()+
"&p=" + sess.getPwd() +
"&uid=" + sess.getUserID() +
"&lf=" + sess.encodeStr(editScannedCode.getText().toString());
result = sess.GetDataFromServer(serverIP,data);
follow this tutorial link it might be helpful to you.
add GetDataFromServer() method in to your doInBackground() method.
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
}
I want to do an App. It can realize to upload the phone picture to server. Now it can take the picture and save to the mobile phone. But it can not upload into server. How to deal with this? The server is using tomcat to setup.
Android upload code:
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class uploadActivity extends Activity
{
private Button uploadbutton;
private String uploadFile = Environment.getExternalStorageDirectory().getAbsolutePath()+"/Test.jpg";
private String srcPath = Environment.getExternalStorageDirectory().getAbsolutePath()+"/Test.jpg";
private String actionUrl = "http://192.168.1.105:8080/ATestInternetCameraServlet/";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_photo);
uploadbutton=(Button)findViewById(R.id.button2);
uploadbutton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
uploadFile();
}
});
}
private void uploadFile()
{ String uploadUrl = "http://192.168.1.105:8080/ATestInternetCameraServlet/CameraServlet";
String end = "\r\n";
String twoHyphens = "--";
String boundary = "******";
try
{
URL url = new URL(uploadUrl);
HttpURLConnection httpURLConnection = (HttpURLConnection) url
.openConnection();
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.setUseCaches(false);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
httpURLConnection.setRequestProperty("Charset", "UTF-8");
httpURLConnection.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
DataOutputStream dos = new DataOutputStream(httpURLConnection
.getOutputStream());
dos.writeBytes(twoHyphens + boundary + end);
dos
.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\""
+ srcPath.substring(srcPath.lastIndexOf("/") + 1)
+ "\"" + end);
dos.writeBytes(end);
FileInputStream fis = new FileInputStream(srcPath);
byte[] buffer = new byte[8192]; // 8k
int count = 0;
while ((count = fis.read(buffer)) != -1)
{
dos.write(buffer, 0, count);
}
fis.close();
dos.writeBytes(end);
dos.writeBytes(twoHyphens + boundary + twoHyphens + end);
dos.flush();
InputStream is = httpURLConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(is, "utf-8");
BufferedReader br = new BufferedReader(isr);
String result = br.readLine();
Toast.makeText(this, result, Toast.LENGTH_LONG).show();//
dos.close();
is.close();
} catch (Exception e)
{
e.printStackTrace();
setTitle(e.getMessage());
}
}
}
The server code:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class CameraServlet extends HttpServlet
{
protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
try
{
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out2 = response.getWriter();
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> items = upload.parseRequest(request);
String uploadPath = "d:\\cameraupload\\";
File file = new File(uploadPath);
if (!file.exists())
{
file.mkdir();
}
String filename = "";
InputStream is = null;
for (FileItem item : items)
{
if (item.isFormField())
{
if (item.getFieldName().equals("filename"))
{
if (!item.getString().equals(""))
filename = item.getString("UTF-8");
}
}
else if (item.getName() != null && !item.getName().equals(""))
{
filename = item.getName().substring(
item.getName().lastIndexOf("\\") + 1);
is = item.getInputStream(); // 得到上传文件的InputStream对象
}
}
filename = uploadPath + filename;
if (new File(filename).exists())
{
new File(filename).delete();
}
// Began to upload files
if (!filename.equals(""))
{
// use FileOutputStream to open the upload file in server
FileOutputStream fos2 = new FileOutputStream(filename);
byte[] buffer = new byte[8192];
int count = 0;
// Began to read the upload file in bytes,and input it to server's upload file output stream
while ((count = is.read(buffer)) > 0)
{
fos2.write(buffer, 0, count); // To write the byte stream server files
}
fos2.close(); // close FileOutputStream object
is.close(); // InputStream object
out2.println("file upload success!xii");
}
}
catch (Exception e)
{
}
}
}
Do you have any error tracing?? Our just happening nothing??
For using httpurlconnection, you need to change the policy at the beginning:
ThreadPolicy mThreadPolicy = new ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(mThreadPolicy);
Try this.
Isn't 192.168.1.105 an IP-adress on the local network? Are you sure it's reachable from your phone? Open your phone's browser and try to navigate to the URL, can you reach it?
At what end are you having problems with the upload? Client or server? If it's on the client, what error are you getting? Or is it silently failing? Have you tried to make a simple HTML form and do the upload from there? If that is working you know it's your Android code that is the problem?
Also, it hurts every time I see someone trying to implement file uploads on their own. I'm not saying that your code is wrong, but it's an awful lot of lines of code (thus more risk of errors) compared to if you'd use a 3rd party library to abstract away all of that code for you. A well known and popular library such as Android Asynchronous Http Client has good support for file uploads out of the box:
AsyncHttpClient client = new AsyncHttpClient();
String filename = "file.png";
File myFile = new File("/path/to/" + filename);
RequestParams params = new RequestParams();
try {
params.put("file", myFile);
params.put("filename", filename);
client.post("http://192.168.1.105:8080/ATestInternetCameraServlet/CameraServlet", params, responseHandler);
}
catch(FileNotFoundException e) {
// handle
}
Try this...add apache-mime4j-0.6.jar and httpmime-4.0.3.jar libs
File f=new File(exsistingFileName);
HttpClient http = new DefaultHttpClient();
HttpPost post = new HttpPost("http://192.168.1.105:8080/ATestInternetCameraServlet/CameraServlet");
MultipartEntity Mentity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
String url1=exsistingFileName;
String mime;
String extension = MimeTypeMap.getFileExtensionFromUrl(url1);
if (extension != ""&&extension!=null) {
MimeTypeMap mime1 = MimeTypeMap.getSingleton();
mime = mime1.getMimeTypeFromExtension(extension);
}
else
{
String ext = url1.substring((url1.lastIndexOf(".") + 1), url1.length());
MimeTypeMap mime1 = MimeTypeMap.getSingleton();
mime = mime1.getMimeTypeFromExtension(ext);
}
ContentBody cbFile;
if(mime!=null)
cbFile= new FileBody(f,mime);
else
cbFile=new FileBody(f);
Mentity.addPart("file",cbFile);
post.setEntity(Mentity);
HttpResponse response = null;
try {
response = http.execute(post);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
responseString = new BasicResponseHandler().
handleResponse(response);
} catch (HttpResponseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
}
One assumed using the Tumblr API to upload images would be easy. It isn't. (EDIT It is now, see Edit 2 at the end of this entry)
My app is supposed to upload an image to tumblr. I would prefer doing that from a service but for now I use an activity that closes itself as soon as its done uploading. In OnCreate() the user is authenticated:
consumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
// It uses this signature by default
// consumer.setMessageSigner(new HmacSha1MessageSigner());
provider = new CommonsHttpOAuthProvider(REQUEST_TOKEN_URL,ACCESS_TOKEN_URL,AUTH_URL);
String authUrl;
try
{
authUrl = provider.retrieveRequestToken(consumer, CALLBACK_URL);
Log.d(TAG, "Auth url:" + authUrl);
startActivity(new Intent("android.intent.action.VIEW", Uri.parse(authUrl)));
}
This opens a browser activity where the user can add username and passoword and then the app returns to the activity (this is also why I have to use an activity, I don't know how to do this from a service)
Returning from the browser the data is extracted:
Uri uri = context.getIntent().getData();
if (uri != null && uri.toString().startsWith(CALLBACK_URL))
{
Log.d(TAG, "uri!=null");
String verifier = uri.getQueryParameter("oauth_verifier");
Log.d(TAG, "verifier"+verifier);
try
{
provider.setOAuth10a(true);
provider.retrieveAccessToken(consumer, verifier);
Log.d(TAG, "try");
}
catch (Exception e)
{
Log.e(TAG, e.toString());
e.printStackTrace();
}
OAUTH_TOKEN = consumer.getToken();
OAUTH_SECRET = consumer.getTokenSecret();
Most of these two snippets I got from here and they work well.
With these tokens I can now try putting data on tumblr. When I try to add Text this works fine using this method:
private void createText()
{
if(!OAUTH_TOKEN.equals(""))
{
HttpContext context = new BasicHttpContext();
HttpPost request = new HttpPost("http://api.tumblr.com/v2/blog/" + blogname + ".tumblr.com/post");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("type", "text"));
nameValuePairs.add(new BasicNameValuePair("body", "this is just a test"));
try
{
request.setEntity(new UrlEncodedFormEntity(nameValuePairs));
}
catch (UnsupportedEncodingException e1)
{
Log.e(TAG, e1.toString());
e1.printStackTrace();
}
if (consumer == null)
{
consumer = new CommonsHttpOAuthConsumer(OAuthConstants.TUMBR_CONSUMERKEY, OAuthConstants.TUMBR_SECRETKEY);
}
if (OAUTH_TOKEN == null || OAUTH_SECRET == null)
{
Log.e(TAG, "Not logged in error");
}
consumer.setTokenWithSecret(OAUTH_TOKEN, OAUTH_SECRET);
try
{
consumer.sign(request);
}
catch (OAuthMessageSignerException e)
{
}
catch (OAuthExpectationFailedException e)
{
}
catch (OAuthCommunicationException e)
{
}
HttpClient client = new DefaultHttpClient();
//finally execute this request
try
{
HttpResponse response = client.execute(request, context);
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null)
{
Log.d(TAG, "responseEntety!=null");
try
{
Log.d(TAG, EntityUtils.toString(responseEntity));
}
catch (ParseException e)
{
e.printStackTrace();
Log.e(TAG, e.toString());
}
catch (IOException e)
{
e.printStackTrace();
Log.e(TAG, e.toString());
} // gives me {"meta":{"status":401,"msg":"Not Authorized"},"response":[]} when I try to upload a photo
}
else
{
Log.d(TAG, "responseEntety==null");
}
}
catch (ClientProtocolException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
PostToTumblr.this.finish();
}
As you can see here http://www.tumblr.com/blog/snapnowandroid (at least as of this time) the text "this is just a test" is posted.
However, when I try to post images, it gets strange. Now I have checked around and apparently this is a well known issue with the tumblr API, which has excessively been discussed here and some have solved it in other programming languages (for example here) but I have been unable to repeat those successes.
The method (in its entirety below) has the exact same structure to the above method (that works), the nameValuePairs are just different
The method is given a Bitmap variable called photo:
private void uploadToTumblr(Bitmap photo)
This bitmap is converted into an array:
ByteArrayOutputStream stream = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] bytes = stream.toByteArray();
The nameValuePairs are filled as follows:
nameValuePairs.add(new BasicNameValuePair(URLEncoder.encode("type", enc), URLEncoder.encode("photo", enc)));
nameValuePairs.add(new BasicNameValuePair(URLEncoder.encode("caption", enc), URLEncoder.encode(text, enc)));
nameValuePairs.add(new BasicNameValuePair("data", Base64.encodeToString(bytes, Base64.URL_SAFE)));
The result is a {"meta":{"status":400,"msg":"Bad Request"},"response":{"errors":["Error uploading photo."]}} from the tumblr api.
I have tries encoding the picture differently as discribed in this article but without any changes.
//http://www.coderanch.com/t/526487/java/java/Java-Byte-Hex-String
final char[] hexArray = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
char[] hexChars = new char[bytes.length * 3];
int v;
for ( int j = 0; j < bytes.length; j++ )
{
v = bytes[j] & 0xFF;
hexChars[j * 3] = '%';
hexChars[j * 3 + 1] = hexArray[v >>> 4];
hexChars[j * 3 + 2] = hexArray[v & 0x0F];
}
String s = new String(hexChars);
s = URLEncoder.encode(s, enc);
nameValuePairs.add(new BasicNameValuePair(URLEncoder.encode("data", enc), s));
Here the entire method (without the hex encoding):
private void uploadToTumblr(Bitmap photo)
{
if(!OAUTH_TOKEN.equals(""))
{
ByteArrayOutputStream stream = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] bytes = stream.toByteArray();
String text ="SNAP";
HttpContext context = new BasicHttpContext();
HttpPost request = new HttpPost("http://api.tumblr.com/v2/blog/" + blogname + ".tumblr.com/post");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
String enc = "UTF-8";
try
{
nameValuePairs.add(new BasicNameValuePair(URLEncoder.encode("type", enc), URLEncoder.encode("photo", enc)));
nameValuePairs.add(new BasicNameValuePair(URLEncoder.encode("caption", enc), URLEncoder.encode(text, enc)));
nameValuePairs.add(new BasicNameValuePair("data", Base64.encodeToString(bytes, Base64.URL_SAFE)));
}
catch (UnsupportedEncodingException e2)
{
Log.e(TAG, e2.toString());
e2.printStackTrace();
}
try
{
request.setEntity(new UrlEncodedFormEntity(nameValuePairs));
}
catch (UnsupportedEncodingException e1)
{
Log.e(TAG, e1.toString());
e1.printStackTrace();
}
if (consumer == null)
{
consumer = new CommonsHttpOAuthConsumer(OAuthConstants.TUMBR_CONSUMERKEY, OAuthConstants.TUMBR_SECRETKEY);
}
if (OAUTH_TOKEN == null || OAUTH_SECRET == null)
{
//throw new LoginErrorException(LoginErrorException.NOT_LOGGED_IN);
Log.e(TAG, "Not logged in error");
}
consumer.setTokenWithSecret(OAUTH_TOKEN, OAUTH_SECRET);
try
{
consumer.sign(request);
}
catch (OAuthMessageSignerException e)
{
}
catch (OAuthExpectationFailedException e)
{
}
catch (OAuthCommunicationException e)
{
}
HttpClient client = new DefaultHttpClient();
//finally execute this request
try
{
HttpResponse response = client.execute(request, context);
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null)
{
Log.d(TAG, "responseEntety!=null");
try
{
Log.d(TAG, EntityUtils.toString(responseEntity));
}
catch (ParseException e)
{
e.printStackTrace();
Log.e(TAG, e.toString());
}
catch (IOException e)
{
e.printStackTrace();
Log.e(TAG, e.toString());
}
}
else
{
Log.d(TAG, "responseEntety==null");
}
}
catch (ClientProtocolException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
Log.d(TAG, "upload imposble... Toklen not set");
}
PostToTumblr.this.finish();
}
Now, while there are several things I am unhappy with (for example that this is done using an activity instead of a service) the big issue here is clearly the problem of uploading images. I am by no means the first to have this problem, so has anyone been able to get this done in java?
Edit 1
Have not made any progress with the problem at hand but created a workaround that might be nice for people who have the same issue. Tumblr offers posting via mail and you can programm android to send emails in the background as shown here. This works very well but you need to ask users to provide their mail account data and the Tumblr-mail Adress to post.
Edit 2
Years have pased and using email is no longer the easy way to do it. With jumblr there is finally a good API for Java that will work on android. OAuth-Authentication is no fun (it never is) but once you get past this, its fantastic.
Now, technically the question of how to do the authentication does not belong here but It's my overly long question, so I'll just paste some code here and if it's not interesting to you just skip it.
This uses a jar called jumblr-0.0.10-jar-with-dependencies.jar
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import com.tumblr.jumblr.JumblrClient;
import com.tumblr.jumblr.request.RequestBuilder;
import com.tumblr.jumblr.types.Blog;
import com.tumblr.jumblr.types.User;
import org.scribe.builder.ServiceBuilder;
import org.scribe.builder.api.TumblrApi;
import org.scribe.model.Token;
import org.scribe.model.Verifier;
import org.scribe.oauth.OAuthService;
import java.io.File;
public class Tumblr
{
private static final String PROTECTED_RESOURCE_URL = "http://api.tumblr.com/v2/user/info";
static OAuthService service;
static Token requestToken=null;
public static void share(final Activity ctx, File file)
{
Thread tt = new Thread(new Runnable()
{
#Override
public void run()
{
JumblrClient client = new JumblrClient(Tumblr_Constants.CONSUMER_KEY, Tumblr_Constants.CONSUMER_SECRET);
RequestBuilder requestBuilder = client.getRequestBuilder();
requestBuilder.setConsumer(Tumblr_Constants.CONSUMER_KEY, Tumblr_Constants.CONSUMER_SECRET);
SharedPreferences settings = ctx.getSharedPreferences("TumblrData", 0);
String oauthToken=settings.getString("OauthToken", "");
String oauthTokenSecret=settings.getString("OauthSecret", "");
if(oauthToken.equals("") || oauthTokenSecret.equals(""))
{
authenticate(ctx);
while(WebViewFragment.verifier.equals(""))
{
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
String v = WebViewFragment.verifier;
Token accessToken = authenticatefurther(v);
SharedPreferences.Editor edit = settings.edit();
edit.putString("OauthToken", accessToken.getToken());
edit.putString("OauthSecret", accessToken.getSecret());
edit.commit();
oauthToken=settings.getString("OauthToken", "");
oauthTokenSecret=settings.getString("OauthSecret", "");
}
if(!oauthToken.equals("") && !oauthTokenSecret.equals(""))
{
client.setToken(oauthToken, oauthTokenSecret);
User user = client.user();
System.out.println(user.getName());
for (Blog blog : user.getBlogs()) {
Log.d("TUMBLR", blog.getTitle());
}
}
}
});
tt.start();
}
private static void authenticate(Context ctx) {
service = new ServiceBuilder()
.provider( TumblrApi.class )
.apiKey(Tumblr_Constants.CONSUMER_KEY)
.apiSecret(Tumblr_Constants.CONSUMER_SECRET)
.callback("snapnao://snapnao.de/ok") // OOB forbidden. We need an url and the better is on the tumblr website !
.build();
Log.d("TUMBLR", "=== Tumblr's OAuth Workflow ===" );
System.out.println();
// Obtain the Request Token
Log.d("TUMBLR", "Fetching the Request Token...");
requestToken = service.getRequestToken();
Log.d("TUMBLR", "Got the Request Token!");
Log.d("TUMBLR", "");
Log.d("TUMBLR", "Now go and authorize Scribe here:" );
Log.d("TUMBLR", service.getAuthorizationUrl( requestToken ) );
String url = service.getAuthorizationUrl(requestToken);
Intent i = new Intent(ctx, WebViewFragment.class);
i.putExtra("url", url);
ctx.startActivity(i);
}
private static Token authenticatefurther(String v)
{
Token accessToken = null;
Log.d("TUMBLR", "And paste the verifier here");
Log.d("TUMBLR", ">>");
Verifier verifier = new Verifier( v);
Log.d("TUMBLR", "");
// Trade the Request Token and Verfier for the Access Token
Log.d("TUMBLR", "Trading the Request Token for an Access Token...");
accessToken = service.getAccessToken( requestToken ,
verifier );
Log.d("TUMBLR", "Got the Access Token!");
Log.d("TUMBLR", "(if your curious it looks like this: " + accessToken + " )");
Log.d("TUMBLR", "");
return accessToken;
}
}
The WebViewFragement looks like this:
import android.app.Activity;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Bundle;
import android.util.Log;
import android.webkit.SslErrorHandler;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class WebViewFragment extends Activity
{
public static String verifier="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webviewfragment);
String url = getIntent().getStringExtra("url");
Log.d("TUMBLR", "webview-> "+url);
WebView view = (WebView) findViewById(R.id.webView);
view.setWebViewClient(
new SSLTolerentWebViewClient()
);
view.getSettings().setJavaScriptEnabled(true);
view.loadUrl(url);
}
// SSL Error Tolerant Web View Client
private class SSLTolerentWebViewClient extends WebViewClient {
#Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
handler.proceed(); // Ignore SSL certificate errors
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
Log.d("TUMBLR", "+++++"+url);
if(url.contains("oauth_verifier="))
{
String[] x = url.split("oauth_verifier=");
verifier=x[1].replace("#_=_", "");
WebViewFragment.this.finish();
}
}
}
}
Why don't you use Jumblr the official Java client for Tumblr.
Regards.
You can easily do this using jumblr - Tumblr java client
JumblrClient client = new JumblrClient(Constant.CONSUMER_KEY,Constant.CONSUMER_SECRET);
client.setToken(preferences.getString("token",null), preferences.getString("token_secret", null));
PhotoPost pp = client.newPost(client.user().getBlogs().get(0).getName(),PhotoPost.class);
pp.setCaption(caption);
// pp.setLinkUrl(link);
// pp.setSource(mImage); // String URL
pp.setPhoto(new Photo(imgFile));
pp.save();
This worked for me...
nameValuePairs.add(new BasicNameValuePair(URLEncoder
.encode("type", "UTF-8"),
URLEncoder.encode("photo", "UTF-8")));
Log.e("Tumblr", "Image shareing file path" + filePath);
nameValuePairs.add(new BasicNameValuePair("caption", caption));
nameValuePairs.add(new BasicNameValuePair("source", filePath));`
where filePath is http url.
I have use multipart
public class VideoUploader extends AsyncTask {
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
progressDialog = ProgressDialog.show(RecordingActivity.this, "",
"Uploading video.. ");
super.onPreExecute();
}
#Override
protected JSONObject doInBackground(String... params) {
JSONObject jsonObject = null;
StringBuilder builder = new StringBuilder();
try {
String url = UrlConst.VIDEO_URL;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
FileBody filebodyVideo = new FileBody(new File(params[0]));
StringBody title = new StringBody("uploadedfile: " + params[0]);
StringBody description = new StringBody(
"This is a video of the agent");
// StringBody code = new StringBody(realtorCodeStr);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("uploadedfile", filebodyVideo);
reqEntity.addPart("title", title);
reqEntity.addPart("description", description);
// reqEntity.adddPart("code", code);
httppost.setEntity(reqEntity);
// DEBUG
System.out.println("executing request "
+ httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
// DEBUG
StatusLine status = response.getStatusLine();
int statusCode = status.getStatusCode();
System.out.println(response.getStatusLine());
if (resEntity != null) {
System.out.println(EntityUtils.toString(resEntity));
} // end if
if (resEntity != null) {
resEntity.consumeContent();
} // end if
if (statusCode == 200) {
InputStream content = resEntity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
jsonObject = new JSONObject(builder.toString());
return jsonObject;
} else {
Log.e(LoginActivity.class.toString(),
"Failed to download file");
}
httpclient.getConnectionManager().shutdown();
} catch (Exception e) {
// TODO: handle exception
}
return null;
}
#Override
protected void onPostExecute(JSONObject result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
progressDialog.dismiss();
if (result != null) {
try {
JSONObject jsonObject = result
.getJSONObject(ParsingTagConst.COMMANDRESULT);
String strSuccess = jsonObject
.getString(ParsingTagConst.SUCCESS);
String responseString = jsonObject
.getString(ParsingTagConst.RESPONSE_STRING);
Toast.makeText(RecordingActivity.this, "" + responseString,
Toast.LENGTH_LONG).show();
if (strSuccess.equals("1")) {
// get here your response
}
} catch (Exception e) {
// TODO: handle exception
}
}
}
}
enter code here
I have done using following method. you can try this.
//paramString="text you want to put in caption"
private void postPhotoTumblr(String uploadedImagePhotoUrl, String paramString)
{
CommonsHttpOAuthConsumer localCommonsHttpOAuthConsumer = getTumblrConsumer();
String str1 = "logged in username";
String encodedImage = uploadedImagePhotoUrl;
DefaultHttpClient localDefaultHttpClient = new DefaultHttpClient();
HttpPost localHttpPost = new HttpPost("http://api.tumblr.com/v2/blog/" + str1 + ".tumblr.com/post");
try
{
ArrayList localArrayList = new ArrayList();
localArrayList.add(new BasicNameValuePair("type", "photo"));
BasicNameValuePair localBasicNameValuePair = new BasicNameValuePair("caption", paramString);
localArrayList.add(localBasicNameValuePair);
localArrayList.add(new BasicNameValuePair("data",encodedImage));
UrlEncodedFormEntity localUrlEncodedFormEntity = new UrlEncodedFormEntity(localArrayList);
localHttpPost.setEntity(localUrlEncodedFormEntity);
localCommonsHttpOAuthConsumer.sign(localHttpPost);
InputStream localInputStream = localDefaultHttpClient.execute(localHttpPost).getEntity().getContent();
InputStreamReader localInputStreamReader = new InputStreamReader(localInputStream);
BufferedReader localBufferedReader = new BufferedReader(localInputStreamReader);
StringBuilder localStringBuilder = new StringBuilder();
while (true)
{
String str2 = localBufferedReader.readLine();
if (str2 == null)
{
Log.i("DATA post resp", localStringBuilder.toString());
break;
}
localStringBuilder.append(str2);
}
}
catch (ClientProtocolException localClientProtocolException)
{
localClientProtocolException.printStackTrace();
}
catch (IOException localIOException)
{
localIOException.printStackTrace();
}
catch (OAuthMessageSignerException localOAuthMessageSignerException)
{
localOAuthMessageSignerException.printStackTrace();
}
catch (OAuthExpectationFailedException localOAuthExpectationFailedException)
{
localOAuthExpectationFailedException.printStackTrace();
}
catch (OAuthCommunicationException localOAuthCommunicationException)
{
localOAuthCommunicationException.printStackTrace();
}
}
EDIT : First Upload image to Web Server then get Url and try to Post with uploaded Url or File path. it will work fine sure... :)
I am fairly new to Android development, and am making a program to translate things using the Google translate API. The error is as follows: 'Syntax error on token(s), misplaced construct(s). Thank you. Here is my Java file:
package org.example.translate;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
import java.io.BufferedReader;
public class TranslateTask implements Runnable {
private static final String TAG = "TranslateTask";
private final Translate translate;
private final String original, from, to;
TranslateTask(Translate translate, String original, String from, String to) {
this.translate = translate;
this.original = original;
this.from = from;
this.to = to;
}
public void run() {
String trans = doTranslate(original, from, to);
translate.setTranslated(trans);
String retrans = doTranslate(trans, from, to);
translate.setRetranslated(retrans);
}
private String doTranslate (String original, String from, String to) {
String result = translate.getResources().getString(
R.string.translation_error);
HttpURLConnection con = null;
Log.d(TAG, "dotranslate(" + original + ", " + from + ", " + to + ")");
//*This is where the error occours*// try {
if (Thread.interrupted())
throw new InterruptedException();
// Build RESTful query for Google API
String q = URLEncoder.encode(original, "utf-8");
URL url = new URL(
"http://ajax.googleapis.com/ajax/services/language/translate"
+ "?v=1.0" + "&q=" + q + "&langpair=" + from
+ "%7C" + to);
con = (HttpURLConnection) url.openConnection();
con.setReadTimeout(10000);
con.setConnectTimeout(15000);
con.setRequestMethod("GET");
con.addRequestProperty("referer",
"http://www.pragprog.com/titles/eband3/hello-android");
con.setDoInput(true);
con.connect();
if (Thread.interrupted())
throw new InterruptedException();
BufferedReader reader = new BufferedReader(
new InputStreamReader(con.getInputStream(), "utf-8"));
String payload = reader.readLine();
reader.close();
JSONObject jsonObject = new JSONObject(payload);
result = jsonObject.getJSONObject("responseData")
.getString("translatedText")
.replace("'", "'")
.replace("&", "&");
if (Thread.interrupted())finally
throw new InterruptedException();
} catch ("IOException", e) {
Log.e(TAG, "IOException" e);
}
catch ("JSONException", e) {
Log.e(TAG, "JSONException", e);
}
catch (InterruptedEception e) {
Log.d(TAG, "InterruptedException", e);
result = translate.getResources().getString(
R.string.translation_interrupted);
}
finally {
if (con!= null) {
con.disconnect();
}
};
};
}
Please help me! Clear answers are appreciated
The only thing that I can see (and it might have been a mistake from copy/pasting) is that you have a random finally floating on one of your lines:
JSONObject jsonObject = new JSONObject(payload);
result = jsonObject.getJSONObject("responseData")
.getString("translatedText")
.replace("'", "'")
.replace("&", "&");
if (Thread.interrupted())finally // <-- this doesn't belong :)
throw new InterruptedException();
} catch ("IOException", e) {
Log.e(TAG, "IOException" e);
}