Skip to content

Instantly share code, notes, and snippets.

@r9software
Created April 20, 2018 03:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save r9software/260bebfd888c1ac8e7c004b5c8986778 to your computer and use it in GitHub Desktop.
Save r9software/260bebfd888c1ac8e7c004b5c8986778 to your computer and use it in GitHub Desktop.
protected String uploadFileOkHttp(String requestUrl, final String fileName) {
final File file = new File(fileName);
MultipartBody.Builder builder = new MultipartBody.Builder();
builder.setType(MultipartBody.FORM);
// using imageName because file name may be XXX.tmp, not XXX.jpg
builder.addFormDataPart("file", fileName, new RequestBody() {
@Override
public MediaType contentType() {
return MediaType.parse("application/octet-stream");
}
@Override
public long contentLength() {
return file.length();
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
try {
Source source = Okio.source(file);
Buffer buf = new Buffer();
long totalRead = 0;
long totalSize = contentLength();
long remaining = totalSize;
for (long readCount; (readCount = source.read(buf, 32000)) != -1; ) {
totalRead += readCount;
remaining -= readCount;
sink.write(buf, readCount);
sink.flush();
// if (onEventListener != null) {
// onEventListener.publishProgress((int) ((totalRead / (float) totalSize) * 100));
// }
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
RequestBody requestBody = builder.build();
Request httpRequest = new Request.Builder()
.url(requestUrl)
.post(requestBody)
.build();
String responseBody = null;
try {
OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();
clientBuilder.connectTimeout(10, TimeUnit.SECONDS);
clientBuilder.readTimeout(10, TimeUnit.SECONDS);
OkHttpClient client = clientBuilder.build();
okhttp3.Response httpResponse;
try {
Log.d(Constants.LOG_TAG, "REQUEST-1: " + requestUrl);
httpResponse = client.newCall(httpRequest).execute();
} catch (SSLException e) {
requestUrl = requestUrl.replace("https://", "http://");
httpRequest = new Request.Builder()
.url(requestUrl)
.post(requestBody)
.build();
Log.d(Constants.LOG_TAG, "REQUEST-2: " + requestUrl);
httpResponse = client.newCall(httpRequest).execute();
}
responseBody = httpResponse.body().string();
if (TextUtils.isEmpty(responseBody)) {
Log.d(Constants.LOG_TAG, "RESPONSE: NULL");
} else {
Log.d(Constants.LOG_TAG, "RESPONSE: " + responseBody);
}
} catch (IOException e) {
e.printStackTrace();
}
return responseBody;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment