Created
November 1, 2013 03:10
-
-
Save chzyer/7260499 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public byte[] readFully(InputStream in) throws IOException { | |
ByteArrayOutputStream out = new ByteArrayOutputStream(); | |
byte[] buffer = new byte[1024]; //you can configure the buffer size | |
while (true) { | |
int r = in.read(buffer); | |
if (r == -1) break; | |
out.write(buffer, 0, r); | |
} | |
return out.toByteArray(); | |
} | |
public byte[] upload(MultipartEntity me) throws IOException { | |
String uploadUrl = "http://up.qiniu.com/"; | |
URL url = new URL(uploadUrl); | |
HttpURLConnection c = (HttpURLConnection) url.openConnection(); | |
c.setRequestMethod("POST"); | |
c.setRequestProperty("Content-Type", me.getContentType().getValue()); | |
c.setDoInput(true); | |
c.setDoOutput(true); | |
c.connect(); | |
me.writeTo(c.getOutputStream()); | |
int code = c.getResponseCode(); | |
if (code == 200) { | |
return readFully(c.getInputStream()); | |
} | |
throw new IOException(new String(readFully(c.getErrorStream()))); | |
} | |
public MultipartEntity makeMultipart(Context mContext, String token, Uri uri) throws FileNotFoundException { | |
MultipartEntity me = new MultipartEntity(); | |
me.addField("token", token); | |
InputStreamAt in = InputStreamAt.fromInputStream(mContext, mContext.getContentResolver().openInputStream(uri)); | |
me.addFile("file", "application/octet-stream", "filename", in); | |
return me; | |
} | |
public void main() { | |
String token = "<token>"; | |
Uri uri = Uri.parse("content://media/external/images/media/99"); | |
try { | |
byte[] ret = upload(makeMultipart(this, token, uri)); | |
// print new String(ret) | |
} catch (FileNotFoundException e) { | |
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. | |
} catch (IOException e) { | |
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment