Last active
December 18, 2015 03:19
-
-
Save damianflannery/5717329 to your computer and use it in GitHub Desktop.
android square okhttp, mimecraft & cookies
This file contains 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 static int okSubmitAttachment(Context ctx, String filePath, String mimeType, String uuid) throws IOException, URISyntaxException, MalformedURLException { | |
int responseCode = 0; | |
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx); | |
String baseUrl = prefs.getString("server_preference", Constants.DEFAULT_BASE_URL); | |
if (!(baseUrl.charAt(baseUrl.length() - 1) == '/')) { | |
baseUrl += "/"; | |
} | |
Cookie cookie = Utils.retrieveCookie(prefs); | |
HttpCookie httpCookie = new HttpCookie(cookie.getName(), cookie.getValue()); | |
httpCookie.setPath(cookie.getPath()); | |
httpCookie.setDomain(cookie.getDomain()); | |
CookieManager man = new CookieManager(); | |
man.getCookieStore() | |
.add(new URI(baseUrl), httpCookie); | |
OkHttpClient client = new OkHttpClient(); | |
client.setCookieHandler(man); | |
File file = new File(filePath); | |
Multipart m = new Multipart.Builder() | |
.addPart(new Part.Builder() | |
.contentType(mimeType).body(file) | |
.contentDisposition("form-data; name=\"file\"; filename=\"" + file.getName() + "\"") | |
.contentEncoding("binary") | |
.build()) | |
.addPart(new Part.Builder() | |
.contentType("text/plain; charset=UTF-8") | |
.body(uuid).contentDisposition("form-data; name=\"uuid\";") | |
.contentEncoding("8bit") | |
.build()) | |
.build(); | |
HttpURLConnection connection = client.open(new URL(baseUrl + Constants.URL_IMAGE_UPLOAD)); | |
OutputStream out = null; | |
InputStream in = null; | |
try { | |
for (Map.Entry<String, String> entry : m.getHeaders().entrySet()) { | |
connection.addRequestProperty(entry.getKey(), entry.getValue()); | |
} | |
// Write the request. | |
connection.setRequestMethod("POST"); | |
out = connection.getOutputStream(); | |
m.writeBodyTo(out); | |
out.close(); | |
Log.d(TAG, connection.getResponseCode() + " " + connection.getResponseMessage()); | |
responseCode = connection.getResponseCode(); | |
} finally { | |
// Clean up. | |
if (out != null) | |
out.close(); | |
if (in != null) | |
in.close(); | |
} | |
return responseCode; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment