Android: Simple way to upload a picture to an image host - android

I d like to upload a picture to a host like: http://imagerz.com/ .
Any sample for this? I can do a simple POST request, but how I can add the image content to my POST request?

Here is a tutorial that tells you how to send a file via FTP to a server. File upload and download using Java
It shouldn't be very hard to "port" that code into android. (You may have to change some of the classes/methods as some of them may not be implemented in Android's lightweight VM).
There are also other image hosting services that should have an api that you could follow.
EDIT:
As you stated, you wanted to do this with a post request.
I found this great tutorial with the following code:
package com.commonsbook.chap9;
import java.io.File;
import java.io.IOException;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.MultipartPostMethod;
public class HttpMultiPartFileUpload {
private static String url =
"http://localhost:8080/HttpServerSideApp/ProcessFileUpload.jsp";
public static void main(String[] args) throws IOException {
HttpClient client = new HttpClient();
MultipartPostMethod mPost = new MultipartPostMethod(url);
client.setConnectionTimeout(8000);
// Send any XML file as the body of the POST request
File f1 = new File("students.xml");
File f2 = new File("academy.xml");
File f3 = new File("academyRules.xml");
System.out.println("File1 Length = " + f1.length());
System.out.println("File2 Length = " + f2.length());
System.out.println("File3 Length = " + f3.length());
mPost.addParameter(f1.getName(), f1);
mPost.addParameter(f2.getName(), f2);
mPost.addParameter(f3.getName(), f3);
int statusCode1 = client.executeMethod(mPost);
System.out.println("statusLine>>>" + mPost.getStatusLine());
mPost.releaseConnection();
}
}
Source: http://www.theserverside.com/news/1365153/HttpClient-and-FileUpload
The same issues about porting this code to android as I stated above apply.

Related

create spreadsheet programmatically in android studio

I want to create a spreadsheet programmatically in android studio. how can I do that?
I used OAuth for signing in the user and now wants to create the spreadsheet in his drive folder.
I found the below code but don't know how to use it...
Spreadsheet spreadsheet = new Spreadsheet()
.setProperties(new SpreadsheetProperties()
.setTitle(title));
spreadsheet = service.spreadsheets().create(spreadsheet)
.setFields("spreadsheetId")
.execute();
System.out.println("Spreadsheet ID: " + spreadsheet.getSpreadsheetId());
For creating a Google Sheet in a programmatic way you should try to use Sheet API. More specifcally you need to use the create method.
If you are using the Google libraries for Java you could just try to follow the example in the create endpoint:
/*
* BEFORE RUNNING:
* ---------------
* 1. If not already done, enable the Google Sheets API
* and check the quota for your project at
* https://console.developers.google.com/apis/api/sheets
* 2. Install the Java client library on Maven or Gradle. Check installation
* instructions at https://github.com/google/google-api-java-client.
* On other build systems, you can add the jar files to your project from
* https://developers.google.com/resources/api-libraries/download/sheets/v4/java
*/
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.sheets.v4.Sheets;
import com.google.api.services.sheets.v4.model.Spreadsheet;
import java.io.IOException;
import java.security.GeneralSecurityException;
public class SheetsExample {
public static void main(String args[]) throws IOException, GeneralSecurityException {
// TODO: Assign values to desired fields of `requestBody`:
Spreadsheet requestBody = new Spreadsheet();
Sheets sheetsService = createSheetsService();
Sheets.Spreadsheets.Create request = sheetsService.spreadsheets().create(requestBody);
Spreadsheet response = request.execute();
// TODO: Change code below to process the `response` object:
System.out.println(response);
}
public static Sheets createSheetsService() throws IOException, GeneralSecurityException {
HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
// TODO: Change placeholder below to generate authentication credentials. See
// https://developers.google.com/sheets/quickstart/java#step_3_set_up_the_sample
//
// Authorize using one of the following scopes:
// "https://www.googleapis.com/auth/drive"
// "https://www.googleapis.com/auth/drive.file"
// "https://www.googleapis.com/auth/spreadsheets"
GoogleCredential credential = null;
return new Sheets.Builder(httpTransport, jsonFactory, credential)
.setApplicationName("Google-SheetsSample/0.1")
.build();
}
}
This example is not handling credentials and you will need to change this in order to work
In case you need more information in the libraries read through the Java Quickstart to work from there, also look at the java create method. And of course you can just do an HTTP request if you have already managed all the OAuth part.

AWS Android SDK not able to access s3 in "sub-directory"

I'm using the android sdk generated by AWS API Gateway to get a pre-signed URL for objects in s3 (lambda behind API gateway).
My s3 bucket looks like this:
* module_a
|\
| * file_a
| * subdir_a
| \
| * file_sa
* module_b
This works perfectly for file_a, but for file_sa it doesn't. At least not when I use the android SDK, there I get an URL where the slash is replaced with %25252F.
However, when I test the api in the console, I get the correct URL.
Is there anything I can do with the SDK to fix this?
Update
Here's the chain of code snippets involved in this problem.
Android code to download file (exception happens in last line)
fileName = "css/style.css"; // file in s3
moduleName = "main"; // folder in s3
[...]
ApiClientFactory factory = new ApiClientFactory().credentialsProvider(
aws.credentialsProvider);
apiClient = factory.build(myAPIClient.class);
apiClient.modulesModuleFileGet(fileName.replace("/", "%2F"), moduleName);
URL url = new URL(url_path.getUrl());
URLConnection connection = url.openConnection();
connection.connect();
InputStream in = new BufferedInputStream(connection.getInputStream());
API Gateway
The api endpoint used above is configured with two path parameters (module name and file name). The body mapping template for the call to lambda looks like this:
#set($inputRoot = $input.path('$'))
{
"module" : "$input.params('module')",
"file": "$input.params('file')"
}
Lambda
from __future__ import print_function
import json
import urllib
import boto3
s3 = boto3.client('s3')
def lambda_handler(event, context):
key = event['module'] + "/" + event['file'].replace("%2F", "/")
url = s3.generate_presigned_url(
"get_object",
Params={'Bucket':"mybucket",
'Key': key},
ExpiresIn=60)
return {"url": url}
I've got it to work after following the comments. However I still somehow get double quoted slashes. Here's the working code
Android
public Url modulesModuleFileGet(String fileName, String moduleName) {
try {
String fileNameEnc = URLEncoder.encode(fileName, "UTF-8");
Url ret = getApiClient().modulesModuleFileGet(fileNameEnc, moduleName);
return ret;
} catch (UnsupportedEncodingException e){
Log.e(TAG, "> modulesModuleFileGet(", e);
return null;
}
}
Lambda
def lambda_handler(event, context):
key = event['module'] + "/" + urllib.unquote_plus(urllib.unquote_plus(event['file']))
url = s3.generate_presigned_url(
"get_object",
Params={'Bucket':"my",
'Key': key},
ExpiresIn=60)
return {"url": url}
I'd still welcome further suggestions on how to improve this, but for now it is working. Thanks for the comments pointing me in the right direction.

run jetty and display a folder content

I have made a working web server with jetty on an android device, but it only displays a static website, does any one know how to display a folder content of the android device? can it be done with a web page or there is a simpler way to do it? I want it similar to when you connect to a tcp server
Serving static content with Jetty can be done using a ResourceHandler.
A simple example
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.server.handler.ResourceHandler;
public class FolderContents {
public static void main(String[] args) throws Exception {
Server server = new Server(8080);
ContextHandler requestContext = new ContextHandler("/filelist");
ResourceHandler resourceHandler = new ResourceHandler();
resourceHandler.setResourceBase("/path/to/directory/");
resourceHandler.setDirectoriesListed(true);
requestContext.setHandler(resourceHandler);
server.setHandler(requestContext);
server.start();
server.join();
}
}
So, on a request to /filelist/, the directory contents will be printed.

How to use POST method to upload file in google-api-java-client?

google-api-java-client is a good web service api client on Android, however I mean a problem and spend lots of time on it.
I want to upload a file via POST method, so I study the google-drive API source code, but it uses the media uploader to upload file to google drive.
so how to upload a file via POST method in google-api-java-client?
for example Imgur upload API method has two require parameter.
suppose a upload file API written in google-api-java-client like this, but i have no idea how should I fill in the 'image' field which marked ???
public class ImgurImage extends GenericJson {
#com.google.api.client.util.Key("key")
private String mKey;
#com.google.api.client.util.Key("image")
private ??? mImage
}
public class Upload extends JsonHttpRequest {
private static final String REST_PATH = "/2/upload.json"
private Upload(ImgurImage content) {
super(ImgurClient.this, HttpMethod.POST, REST_PATH, content);
}
public void execute() throws IOException {
executeUnparsed();
}
}
I recommend taking a look at our Drive API sample at http://samples.google-api-java-client.googlecode.com/hg/drive-cmdline-sample/instructions.html
Here's a code snippet:
private static final java.io.File UPLOAD_FILE = new java.io.File(UPLOAD_FILE_PATH);
/** Uploads a file using either resumable or direct media upload. */
private static File uploadFile(boolean useDirectUpload) throws IOException {
File fileMetadata = new File();
fileMetadata.setTitle(UPLOAD_FILE.getName());
InputStreamContent mediaContent = new InputStreamContent("image/jpeg", new BufferedInputStream(
new FileInputStream(UPLOAD_FILE)));
mediaContent.setLength(UPLOAD_FILE.length());
Drive.Files.Insert insert = drive.files().insert(fileMetadata, mediaContent);
MediaHttpUploader uploader = insert.getMediaHttpUploader();
uploader.setDirectUploadEnabled(useDirectUpload);
uploader.setProgressListener(new FileUploadProgressListener());
return insert.execute();
}
I use httpClient and I use FileBody to send a file to a server, as part of a MultiPartEntity. This works for Picasa, Flickr, etc.
it looks like you adopted a sample that was uploading text (json in content, json in the REST URL endpoint) and used it to attempt image upload ( upload(ImgurImage) ).
So, look at the source for the 'GenericJson.upload(ImgurImage)'...
See what this method does when it sets the 'content' field prior to calling 'exec' on the POST.
Understand that these frameworks will allow either strings and text in content or allow bitmaps ( bytes ) for images and audio type uploads.
Look for a handler that sets the 'content' and understand how it handles both bytes and strings for the json sample.
that should help you use the framework you have chosen.

How to access share folder in windows through android and read files

I need to connect from my Android phone to a Windows PC share and access files. I saw some sample apps in Android market that access share folders using smb/samba. But I have no idea about how to create an app like that. Thanks a lot.
You need to get JCIFS and use SmbFile class to interact with files over the network,
http://lists.samba.org/archive/jcifs/2007-September/007465.html
that is a quick example of how to list files, of coarse you need internet permission on. So Far though everytime I try to call SmbFile.listFiles(); I get an UnknownHostException, However others seam to be able to do it with no problem, this might work for you, try it!
Google has released a simple, free Samba client. It is on github so you can have a look and use whatever you need out of that: https://github.com/google/samba-documents-provider
The other option is JCIFS: https://jcifs.samba.org/. There you can find the library and examples on how to use it.
I used JCIFS. Here is an example from my code which reads files from a folder in a windows share:
TreeMap<Date, String> filesInfo = new TreeMap<Date, String>();
NtlmPasswordAuthentication auth = null;
UniAddress dc = UniAddress.getByName(m_dataHostIp);
if(m_userName.length() > 0 && m_password.length() > 0)
auth = new NtlmPasswordAuthentication(m_domain + ";" + m_userName + ":" + m_password);
else
auth = new NtlmPasswordAuthentication(m_domain, null, null);
SmbSession.logon(dc, auth);
SmbFile file = new SmbFile(m_foldername, auth);
SmbFile[] files = file.listFiles();
for (int i = 0; i < files.length; i++)
{
String fileName = files[i].getName();
String extension=fileName.substring(fileName.lastIndexOf(".") + 1);
logInfo(TAG + " " + fileName + "\n");
Date fileTime = new Date(files[i].getDate());
if(m_fileExtension.contains(extension))
filesInfo.put(fileTime, fileName);
}
The code posted above works. It allows you to connect to the share, authenticate (username and password that you know) and get the list of the files. At the root of jcif file access is the SmbFile which has all the info you need to access files in the share. All you need is in your build.gradle for the app add:
dependencies {
implementation files('libs/jcifs-1.3.19.jar')
}
and in your implementation file:
import jcifs.smb.NtlmPasswordAuthentication;
import jcifs.smb.SmbFile;
import static jcifs.smb.SmbFile.FILE_SHARE_DELETE;
import static jcifs.smb.SmbFile.FILE_SHARE_READ;
import static jcifs.smb.SmbFile.FILE_SHARE_WRITE;

Categories

Resources