Java Examples for com.squareup.okhttp.MultipartBuilder
The following java examples will help you to understand the usage of com.squareup.okhttp.MultipartBuilder. These source code samples are taken from different open source projects.
Example 1
| Project: PocketHub-master File: ImageBinPoster.java View source code |
/**
* Post the image to ImageBin
*
* @param bytes Bytes of the image to post
* @param callback Request callback
*/
public static void post(byte[] bytes, Callback callback) {
RequestBody requestBody = new MultipartBuilder().type(MultipartBuilder.FORM).addFormDataPart("file", "test", RequestBody.create(MediaType.parse("image/*"), bytes)).build();
Request request = new Request.Builder().url("https://imagebin.ca/upload.php").post(requestBody).build();
OkHttpClient client = new OkHttpClient();
Call call = client.newCall(request);
call.enqueue(callback);
}Example 2
| Project: Android-Volley-Polished-master File: AbstractMultiPartRequest.java View source code |
private RequestBody buildMultipartEntity() {
if (requestBody == null) {
MultipartBuilder multipartBuilder = new MultipartBuilder().type(MultipartBuilder.FORM);
for (String key : stringUploads.keySet()) {
String value = stringUploads.get(key);
multipartBuilder.addFormDataPart(key, value);
}
for (String key : fileUploads.keySet()) {
File value = fileUploads.get(key);
String name = value.getName();
String contentType = URLConnection.guessContentTypeFromName(name);
multipartBuilder.addFormDataPart(key, name, RequestBody.create(MediaType.parse(contentType), value));
}
requestBody = multipartBuilder.build();
}
return requestBody;
}Example 3
| Project: criticalmaps-android-master File: ImageUploadHandler.java View source code |
@Override
protected ResultType doInBackground(Void... params) {
final OkHttpClient okHttpClient = App.components().okHttpClient();
final ProgressListener progressListener = new ProgressListener() {
@Override
public void update(long bytesRead, long contentLength) {
publishProgress((int) ((100 * bytesRead) / contentLength));
}
};
RequestBody requestBody = new MultipartBuilder().type(MultipartBuilder.FORM).addFormDataPart("data", ownLocationModel.getLocationJson().toString()).addFormDataPart("uploaded_file", imageFileToUpload.getName(), new ProgressRequestBody(RequestBody.create(MediaType.parse("image/jpeg"), imageFileToUpload), progressListener)).build();
Request request = new Request.Builder().url(Endpoints.IMAGE_POST).post(requestBody).build();
Response response = null;
try {
response = okHttpClient.newCall(request).execute();
if (response.isSuccessful() && response.body().string().equals("success")) {
return ResultType.SUCCEEDED;
}
} catch (Exception ignored) {
} finally {
if (response != null) {
try {
response.body().close();
} catch (IOException ignored) {
}
}
}
return ResultType.FAILED;
}Example 4
| Project: rxjava_for_android-master File: XgoHttpClient.java View source code |
/**
* �始化Body类型请求�数
* init Body type params
*/
private RequestBody initRequestBody(Map<String, Object> params) {
MultipartBuilder bodyBuilder = new MultipartBuilder().type(MultipartBuilder.FORM);
Set<Map.Entry<String, Object>> entries = params.entrySet();
for (Map.Entry<String, Object> entry : entries) {
String key = entry.getKey();
Object value = entry.getValue();
if (value instanceof File) {
File file = (File) value;
try {
FileNameMap fileNameMap = URLConnection.getFileNameMap();
String mimeType = fileNameMap.getContentTypeFor(file.getAbsolutePath());
XgoLog.w("mimeType::" + mimeType);
bodyBuilder.addFormDataPart(key, file.getName(), RequestBody.create(MediaType.parse(mimeType), file));
} catch (Exception e) {
e.printStackTrace();
XgoLog.e("mimeType is Error !");
}
} else {
XgoLog.w(key + "::" + value);
bodyBuilder.addFormDataPart(key, value.toString());
}
}
return bodyBuilder.build();
}Example 5
| Project: sonet-master File: PhotoUploadService.java View source code |
@Override
protected String doInBackground(String... params) {
if (params.length > 2) {
String filename = params[2];
String imageType = "jpg";
if (filename.endsWith("png")) {
imageType = "png";
} else if (filename.endsWith("bmp")) {
imageType = "bmp";
}
if (BuildConfig.DEBUG)
Log.d(TAG, "upload file: " + filename + ", type: " + imageType);
MultipartBuilder builder = new MultipartBuilder().type(MultipartBuilder.FORM).addFormDataPart(Ssource, filename, RequestBody.create(MediaType.parse("image/" + imageType), new File(filename))).addFormDataPart(Smessage, params[1]);
if (params.length > 3) {
if (!TextUtils.isEmpty(params[3])) {
builder.addFormDataPart(Splace, params[3]);
}
if (params.length > 4) {
if (!TextUtils.isEmpty(params[4])) {
builder.addFormDataPart(Stags, params[4]);
}
}
}
Request request = new Request.Builder().url(String.format(Facebook.FACEBOOK_PHOTOS, FACEBOOK_BASE_URL, Saccess_token, params[0])).post(builder.build()).build();
return SonetHttpClient.getResponse(request);
}
return null;
}Example 6
| Project: AisenForAndroid-master File: DefHttpUtility.java View source code |
@Override
public <T> T doPostFiles(HttpConfig config, Setting action, Params urlParams, Params bodyParams, MultipartFile[] files, Class<T> responseCls) throws TaskException {
String method = "doPostFiles";
Request.Builder builder = createRequestBuilder(config, action, urlParams, method);
MultipartBuilder multipartBuilder = new MultipartBuilder();
multipartBuilder.type(MultipartBuilder.FORM);
// 处�Body�数
if (bodyParams != null && bodyParams.getKeys().size() > 0) {
for (String key : bodyParams.getKeys()) {
String value = bodyParams.get(key);
multipartBuilder.addFormDataPart(key, value);
Logger.d(getTag(action, method), "BodyParam[%s, %s]", key, value);
}
}
// 处�文件数�
if (files != null && files.length > 0) {
for (MultipartFile file : files) {
// 普通å—节æµ?
if (file.getBytes() != null) {
multipartBuilder.addFormDataPart(file.getKey(), file.getKey(), createRequestBody(file));
Logger.d(getTag(action, method), "Multipart bytes, length = " + file.getBytes().length);
} else // 文件
if (file.getFile() != null) {
multipartBuilder.addFormDataPart(file.getKey(), file.getFile().getName(), createRequestBody(file));
Logger.d(getTag(action, method), "Multipart file, name = %s, path = %s", file.getFile().getName(), file.getFile().getAbsolutePath());
}
}
}
RequestBody requestBody = multipartBuilder.build();
builder.post(requestBody);
return executeRequest(builder.build(), responseCls, action, method);
}Example 7
| Project: firetweet-master File: OkHttpClientImpl.java View source code |
private RequestBody getRequestBody(HttpParameter[] params) throws IOException {
if (params == null)
return null;
if (!HttpParameter.containsFile(params)) {
return RequestBody.create(APPLICATION_FORM_URLENCODED, HttpParameter.encodeParameters(params));
}
final MultipartBuilder builder = new MultipartBuilder();
builder.type(MultipartBuilder.FORM);
for (final HttpParameter param : params) {
if (param.isFile()) {
RequestBody requestBody;
if (param.hasFileBody()) {
requestBody = new StreamRequestBody(MediaType.parse(param.getContentType()), param.getFileBody(), true);
} else {
requestBody = RequestBody.create(MediaType.parse(param.getContentType()), param.getFile());
}
builder.addFormDataPart(param.getName(), param.getFileName(), requestBody);
} else {
builder.addFormDataPart(param.getName(), param.getValue());
}
}
return builder.build();
}Example 8
| Project: PortalWaitingList-master File: GMailServiceUtil.java View source code |
/**
* Get messages by batch request
* @param messageIds the id list.
* @param start start index.
* @param count count.
* @return the parsed messages.
* @throws IOException the response has error.
*/
private ArrayList<Message> getBatchMessages(ArrayList<MessageList.MessageId> messageIds, int start, int count) throws IOException {
OkHttpClient client = new OkHttpClient();
ArrayList<Message> messages = new ArrayList<>();
MultipartBuilder builder = new MultipartBuilder();
builder.type(MultipartBuilder.MIXED);
// reverse the id to get a list i asc order by date.
for (int i = start + count - 1; i > start - 1; i--) {
byte[] request = (PART_REQUEST_BASE_PATH + messageIds.get(i).getId() + QUERY_MESSAGE_FORMAT + QUERY_MESSAGE_METADATA_DATE + QUERY_MESSAGE_METADATA_SUBJECT + "\n").getBytes();
RequestBody partRequest = RequestBody.create(HTTP, request);
builder.addPart(partRequest);
}
Request request = new Request.Builder().url(BATCH_REQUEST_URL).post(builder.build()).header("Authorization", "Bearer " + token).build();
Response response = client.newCall(request).execute();
String contentType = response.header("Content-Type");
String responseBody = response.body().string();
if (RegexUtil.getInstance().isFound(RegexUtil.FIND_BOUNDARY, contentType)) {
String boundary = RegexUtil.getInstance().getMatchedStr();
String[] eachResponses = responseBody.split("--" + boundary);
for (int i = 1; i < count + 1; i++) {
messages.add(parseEachInBatch(eachResponses[i]));
}
return messages;
} else
throw new IOException("Can not found the boundary, maybe request failed.");
}Example 9
| Project: triaina-master File: HttpRequestWorker.java View source code |
private RequestBody createMultipartRequestBody(NetHttpSendParams params) {
Bundle body = params.getBody();
if (body == null)
return null;
MultipartBuilder builder = new MultipartBuilder().type(MultipartBuilder.FORM);
Set<String> keys = body.keySet();
for (String key : keys) {
String rawBody = body.getString(key);
if (rawBody != null) {
builder.addFormDataPart(key, rawBody);
continue;
}
Bundle part = body.getBundle(key);
if (part != null) {
if (FILE_TYPE.equals(part.getString("type"))) {
File file = new File(part.getString("value"));
RequestBody requestBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);
builder.addFormDataPart(key, file.getName(), requestBody);
}
continue;
}
}
return builder.build();
}Example 10
| Project: CampusAssistant-master File: OkHttpUtils.java View source code |
public void uploadImg(Context ctx, String fileUri, final Handler handler) throws IOException {
Log.d("imgx", "ÕýÔÚÉÏ´«Í¼Æ¬");
String ip = PropetiesFileReaderUtil.get(ctx, "ip");
String port = PropetiesFileReaderUtil.get(ctx, "port");
// ´ÓsharePreferenceÖÐÈ¡³ö֮ǰ´æ´¢µÄ²ÎÊý
String token = (String) SPUtils.get(ctx, "token", "");
String singnature = (String) SPUtils.get(ctx, "singnature", "");
String st = (String) SPUtils.get(ctx, "st", "");
String fullUrl = "http://" + ip + ":" + port + "/contentFileUp/fileUp.do?token=" + token + "&singnature=" + singnature + "&st=" + st;
File file = new File(fileUri);
System.out.println("ÉÏ´«Í¼Æ¬µÄ´óСÊÇ£º" + file.length() + " byte");
MediaType MEDIA_TYPE_IMAGE = MediaType.parse("image/jpeg; charset=utf-8");
RequestBody requestBody = new MultipartBuilder().type(MultipartBuilder.FORM).addFormDataPart("upFile", file.getName(), RequestBody.create(MEDIA_TYPE_IMAGE, file)).build();
Request request = new Request.Builder().url(fullUrl).post(requestBody).build();
Call call = mOkHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Request arg0, IOException arg1) {
System.err.println("ÉÏ´«±¨´í£¡onFailure");
handler.sendEmptyMessage(HandlerOrder.UPLOAD_ERROR);
}
@Override
public void onResponse(Response response) throws IOException {
// ´òÓ¡³öresponse×Ö·û´®
System.out.println(response.code());
String body = response.body().string().trim();
if (// Èç¹û·þÎñÆ÷·µ»ØÕý³££¬ÄǾͽâÎö½á¹û
response.code() == 200) {
Message s = new Message();
s.what = HandlerOrder.UPLOAD_OK;
Bundle bd = new Bundle();
bd.putString("body", body);
s.setData(bd);
handler.sendMessage(s);
}
}
});
}Example 11
| Project: React-Native-Remote-Update-master File: NetworkingModule.java View source code |
@ReactMethod
public void sendRequest(String method, String url, int requestId, ReadableArray headers, ReadableMap data, final Callback callback) {
// We need to call the callback to avoid leaking memory on JS even when input for sending
// request is erroneous or insufficient. For non-http based failures we use code 0, which is
// interpreted as a transport error.
// Callback accepts following arguments: responseCode, headersString, responseBody
Request.Builder requestBuilder = new Request.Builder().url(url);
if (requestId != 0) {
requestBuilder.tag(requestId);
}
Headers requestHeaders = extractHeaders(headers, data);
if (requestHeaders == null) {
callback.invoke(0, null, "Unrecognized headers format");
return;
}
String contentType = requestHeaders.get(CONTENT_TYPE_HEADER_NAME);
String contentEncoding = requestHeaders.get(CONTENT_ENCODING_HEADER_NAME);
requestBuilder.headers(requestHeaders);
if (data == null) {
requestBuilder.method(method, null);
} else if (data.hasKey(REQUEST_BODY_KEY_STRING)) {
if (contentType == null) {
callback.invoke(0, null, "Payload is set but no content-type header specified");
return;
}
String body = data.getString(REQUEST_BODY_KEY_STRING);
MediaType contentMediaType = MediaType.parse(contentType);
if (RequestBodyUtil.isGzipEncoding(contentEncoding)) {
RequestBody requestBody = RequestBodyUtil.createGzip(contentMediaType, body);
if (requestBody == null) {
callback.invoke(0, null, "Failed to gzip request body");
return;
}
requestBuilder.method(method, requestBody);
} else {
requestBuilder.method(method, RequestBody.create(contentMediaType, body));
}
} else if (data.hasKey(REQUEST_BODY_KEY_URI)) {
if (contentType == null) {
callback.invoke(0, null, "Payload is set but no content-type header specified");
return;
}
String uri = data.getString(REQUEST_BODY_KEY_URI);
InputStream fileInputStream = RequestBodyUtil.getFileInputStream(getReactApplicationContext(), uri);
if (fileInputStream == null) {
callback.invoke(0, null, "Could not retrieve file for uri " + uri);
return;
}
requestBuilder.method(method, RequestBodyUtil.create(MediaType.parse(contentType), fileInputStream));
} else if (data.hasKey(REQUEST_BODY_KEY_FORMDATA)) {
if (contentType == null) {
contentType = "multipart/form-data";
}
ReadableArray parts = data.getArray(REQUEST_BODY_KEY_FORMDATA);
MultipartBuilder multipartBuilder = constructMultipartBody(parts, contentType, callback);
if (multipartBuilder == null) {
return;
}
requestBuilder.method(method, multipartBuilder.build());
} else {
// Nothing in data payload, at least nothing we could understand anyway.
// Ignore and treat it as if it were null.
requestBuilder.method(method, null);
}
mClient.newCall(requestBuilder.build()).enqueue(new com.squareup.okhttp.Callback() {
@Override
public void onFailure(Request request, IOException e) {
if (mShuttingDown) {
return;
}
// We need to call the callback to avoid leaking memory on JS even when input for
// sending request is erronous or insufficient. For non-http based failures we use
// code 0, which is interpreted as a transport error
callback.invoke(0, null, e.getMessage());
}
@Override
public void onResponse(Response response) throws IOException {
if (mShuttingDown) {
return;
}
// TODO(5472580) handle headers properly
String responseBody;
try {
responseBody = response.body().string();
} catch (IOException e) {
callback.invoke(0, null, e.getMessage());
return;
}
callback.invoke(response.code(), null, responseBody);
}
});
}Example 12
| Project: Android-IMSI-Catcher-Detector-master File: RequestTask.java View source code |
@Override
protected String doInBackground(String... commandString) {
// We need to create a separate case for UPLOADING to DBe (OCID, MLS etc)
switch(mType) {
// OCID upload request from "APPLICATION" drawer title
case DBE_UPLOAD_REQUEST:
try {
@Cleanup Realm realm = Realm.getDefaultInstance();
boolean prepared = mDbAdapter.prepareOpenCellUploadData(realm);
log.info("OCID upload data prepared - " + String.valueOf(prepared));
if (prepared) {
File file = new File((mAppContext.getExternalFilesDir(null) + File.separator) + "OpenCellID/aimsicd-ocid-data.csv");
publishProgress(25, 100);
RequestBody requestBody = new MultipartBuilder().type(MultipartBuilder.FORM).addFormDataPart("key", CellTracker.OCID_API_KEY).addFormDataPart("datafile", "aimsicd-ocid-data.csv", RequestBody.create(MediaType.parse("text/csv"), file)).build();
Request request = new Request.Builder().url("http://www.opencellid.org/measure/uploadCsv").post(requestBody).build();
publishProgress(60, 100);
Response response = okHttpClient.newCall(request).execute();
publishProgress(80, 100);
if (response != null) {
log.info("OCID Upload Response: " + response.code() + " - " + response.message());
if (response.code() == 200) {
Realm.Transaction transaction = mDbAdapter.ocidProcessed();
realm.executeTransaction(transaction);
}
publishProgress(95, 100);
}
return "Successful";
} else {
Helpers.msgLong(mAppContext, mAppContext.getString(R.string.no_data_for_publishing));
return null;
}
// all caused by httpclient.execute(httppost);
} catch (UnsupportedEncodingException e) {
log.error("Upload OpenCellID data Exception", e);
} catch (FileNotFoundException e) {
log.error("Upload OpenCellID data Exception", e);
} catch (IOException e) {
log.error("Upload OpenCellID data Exception", e);
} catch (Exception e) {
log.error("Upload OpenCellID data Exception", e);
}
// DOWNLOADING...
case // OCID download request from "APPLICATION" drawer title
DBE_DOWNLOAD_REQUEST:
mTimeOut = REQUEST_TIMEOUT_MENU;
case // OCID download request from "Antenna Map Viewer"
DBE_DOWNLOAD_REQUEST_FROM_MAP:
int count;
try {
long total;
int progress = 0;
String dirName = getOCDBDownloadDirectoryPath(mAppContext);
File dir = new File(dirName);
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(dir, OCDB_File_Name);
log.info("DBE_DOWNLOAD_REQUEST write to: " + dirName + OCDB_File_Name);
Request request = new Request.Builder().url(commandString[0]).get().build();
Response response;
try {
// OCID's API can be slow. Give it up to a minute to do its job. Since this
// is a backgrounded task, it's ok to wait for a while.
okHttpClient.setReadTimeout(60, TimeUnit.SECONDS);
response = okHttpClient.newCall(request).execute();
// Restore back to default
okHttpClient.setReadTimeout(10, TimeUnit.SECONDS);
} catch (SocketTimeoutException e) {
log.warn("Trying to talk to OCID timed out after 60 seconds. API is slammed? Throttled?");
return "Timeout";
}
if (response.code() != 200) {
try {
String error = response.body().string();
Helpers.msgLong(mAppContext, mAppContext.getString(R.string.download_error) + " " + error);
log.error("Download OCID data error: " + error);
} catch (Exception e) {
Helpers.msgLong(mAppContext, mAppContext.getString(R.string.download_error) + " " + e.getClass().getName() + " - " + e.getMessage());
log.error("Download OCID exception: ", e);
}
return "Error";
} else {
// This returns "-1" for streamed response (Chunked Transfer Encoding)
total = response.body().contentLength();
if (total == -1) {
log.debug("doInBackground DBE_DOWNLOAD_REQUEST total not returned!");
// Let's set it arbitrarily to something other than "-1"
total = 1024;
} else {
log.debug("doInBackground DBE_DOWNLOAD_REQUEST total: " + total);
// Let's show something!
publishProgress((int) (0.25 * total), (int) total);
}
FileOutputStream output = new FileOutputStream(file, false);
InputStream input = new BufferedInputStream(response.body().byteStream());
byte[] data = new byte[1024];
while ((count = input.read(data)) > 0) {
// writing data to file
output.write(data, 0, count);
progress += count;
publishProgress(progress, (int) total);
}
input.close();
// flushing output
output.flush();
output.close();
}
return "Successful";
} catch (IOException e) {
log.warn("Problem reading data from steam", e);
return null;
}
}
return null;
}Example 13
| Project: Purple-Robot-master File: DataUploadPlugin.java View source code |
@SuppressWarnings("deprecation")
protected int transmitPayload(SharedPreferences prefs, String payload) {
Context context = this.getContext();
if (prefs == null)
prefs = PreferenceManager.getDefaultSharedPreferences(context);
if (payload == null || payload.trim().length() == 0) {
LogManager.getInstance(context).log("null_or_empty_payload", null);
return DataUploadPlugin.RESULT_SUCCESS;
}
final DataUploadPlugin me = this;
try {
try {
if (DataUploadPlugin.restrictToWifi(prefs)) {
if (WiFiHelper.wifiAvailable(context) == false) {
me.broadcastMessage(context.getString(R.string.message_wifi_pending), false);
return DataUploadPlugin.RESULT_NO_CONNECTION;
}
}
if (DataUploadPlugin.restrictToCharging(prefs)) {
if (PowerHelper.isPluggedIn(context) == false) {
me.broadcastMessage(context.getString(R.string.message_charging_pending), false);
return DataUploadPlugin.RESULT_NO_POWER;
}
}
JSONObject jsonMessage = new JSONObject();
jsonMessage.put(OPERATION_KEY, "SubmitProbes");
payload = payload.replaceAll("\r", "");
payload = payload.replaceAll("\n", "");
jsonMessage.put(PAYLOAD_KEY, payload);
String userHash = EncryptionManager.getInstance().getUserHash(me.getContext());
jsonMessage.put(USER_HASH_KEY, userHash);
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] checksummed = (jsonMessage.get(USER_HASH_KEY).toString() + jsonMessage.get(OPERATION_KEY).toString() + jsonMessage.get(PAYLOAD_KEY).toString()).getBytes("UTF-8");
byte[] digest = md.digest(checksummed);
String checksum = (new BigInteger(1, digest)).toString(16);
while (checksum.length() < 32) checksum = "0" + checksum;
jsonMessage.put(CHECKSUM_KEY, checksum);
jsonMessage.put(CONTENT_LENGTH_KEY, checksummed.length);
// Liberal HTTPS setup:
// http://stackoverflow.com/questions/2012497/accepting-a-certificate-for-https-on-android
HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
if (prefs.getBoolean(DataUploadPlugin.ALLOW_ALL_SSL_CERTIFICATES, DataUploadPlugin.ALLOW_ALL_SSL_CERTIFICATES_DEFAULT)) {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null, null);
socketFactory = new LiberalSSLSocketFactory(trustStore);
}
registry.register(new Scheme("https", socketFactory, 443));
OkHttpClient client = new OkHttpClient();
client.setConnectTimeout(3, TimeUnit.MINUTES);
client.setReadTimeout(3, TimeUnit.MINUTES);
String title = me.getContext().getString(R.string.notify_upload_data);
PendingIntent contentIntent = PendingIntent.getActivity(me.getContext(), 0, new Intent(me.getContext(), StartActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder noteBuilder = new NotificationCompat.Builder(me.getContext());
noteBuilder.setContentTitle(title);
noteBuilder.setContentText(title);
noteBuilder.setContentIntent(contentIntent);
noteBuilder.setSmallIcon(R.drawable.ic_note_normal);
noteBuilder.setWhen(System.currentTimeMillis());
noteBuilder.setColor(0xff4e015c);
Notification note = noteBuilder.build();
note.flags = Notification.FLAG_ONGOING_EVENT;
String uriString = prefs.getString(DataUploadPlugin.UPLOAD_URI, context.getString(R.string.sensor_upload_url));
String jsonString = jsonMessage.toString();
String uploadMessage = String.format(context.getString(R.string.message_transmit_bytes), (jsonString.length() / 1024));
me.broadcastMessage(uploadMessage, false);
MultipartBuilder builder = new MultipartBuilder();
builder = builder.type(MultipartBuilder.FORM);
ArrayList<File> toDelete = new ArrayList<>();
if (payload.contains("\"" + Probe.PROBE_MEDIA_URL + "\":")) {
JSONArray payloadJson = new JSONArray(payload);
for (int i = 0; i < payloadJson.length(); i++) {
JSONObject reading = payloadJson.getJSONObject(i);
if (reading.has(Probe.PROBE_MEDIA_URL)) {
Uri u = Uri.parse(reading.getString(Probe.PROBE_MEDIA_URL));
String mimeType = "application/octet-stream";
if (reading.has(Probe.PROBE_MEDIA_CONTENT_TYPE))
mimeType = reading.getString(Probe.PROBE_MEDIA_CONTENT_TYPE);
String guid = reading.getString(Probe.PROBE_GUID);
File file = new File(u.getPath());
if (file.exists()) {
builder = builder.addFormDataPart(guid, file.getName(), RequestBody.create(MediaType.parse(mimeType), file));
toDelete.add(file);
}
}
}
}
builder = builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"json\""), RequestBody.create(null, jsonString));
String version = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
RequestBody requestBody = builder.build();
Request request = new Request.Builder().removeHeader("User-Agent").addHeader("User-Agent", "Purple Robot " + version).url(uriString).post(requestBody).build();
Response response = client.newCall(request).execute();
JSONObject json = new JSONObject(response.body().string());
String status = json.getString(STATUS_KEY);
String responsePayload = "";
if (json.has(PAYLOAD_KEY))
responsePayload = json.getString(PAYLOAD_KEY);
if (status.equals("error") == false) {
byte[] responseDigest = md.digest((status + responsePayload).getBytes("UTF-8"));
String responseChecksum = (new BigInteger(1, responseDigest)).toString(16);
while (responseChecksum.length() < 32) responseChecksum = "0" + responseChecksum;
if (responseChecksum.equals(json.getString(CHECKSUM_KEY))) {
String uploadedMessage = String.format(context.getString(R.string.message_upload_successful), (jsonString.length() / 1024));
me.broadcastMessage(uploadedMessage, false);
for (File f : toDelete) f.delete();
return DataUploadPlugin.RESULT_SUCCESS;
} else {
HashMap<String, Object> logPayload = new HashMap<>();
logPayload.put("remote_checksum", json.getString(CHECKSUM_KEY));
logPayload.put("local_checksum", responseChecksum);
LogManager.getInstance(context).log("null_or_empty_payload", logPayload);
me.broadcastMessage(context.getString(R.string.message_checksum_failed), true);
}
return DataUploadPlugin.RESULT_ERROR;
} else {
String errorMessage = String.format(context.getString(R.string.message_server_error), status);
me.broadcastMessage(errorMessage, true);
}
} catch (HttpHostConnectExceptionConnectTimeoutException | e) {
e.printStackTrace();
me.broadcastMessage(context.getString(R.string.message_http_connection_error), true);
LogManager.getInstance(context).logException(e);
} catch (SocketTimeoutException e) {
e.printStackTrace();
me.broadcastMessage(context.getString(R.string.message_socket_timeout_error), true);
LogManager.getInstance(me.getContext()).logException(e);
} catch (SocketException e) {
e.printStackTrace();
String errorMessage = String.format(context.getString(R.string.message_socket_error), e.getMessage());
me.broadcastMessage(errorMessage, true);
LogManager.getInstance(me.getContext()).logException(e);
} catch (UnknownHostException e) {
e.printStackTrace();
me.broadcastMessage(context.getString(R.string.message_unreachable_error), true);
LogManager.getInstance(me.getContext()).logException(e);
} catch (JSONException e) {
e.printStackTrace();
me.broadcastMessage(context.getString(R.string.message_response_error), true);
LogManager.getInstance(me.getContext()).logException(e);
} catch (SSLPeerUnverifiedException e) {
LogManager.getInstance(me.getContext()).logException(e);
me.broadcastMessage(context.getString(R.string.message_unverified_server), true);
LogManager.getInstance(context).logException(e);
} catch (Exception e) {
e.printStackTrace();
LogManager.getInstance(me.getContext()).logException(e);
me.broadcastMessage(context.getString(R.string.message_general_error, e.getMessage()), true);
LogManager.getInstance(context).logException(e);
}
} catch (OutOfMemoryError e) {
LogManager.getInstance(me.getContext()).logException(e);
me.broadcastMessage(context.getString(R.string.message_general_error, e.getMessage()), true);
LogManager.getInstance(context).logException(e);
}
return DataUploadPlugin.RESULT_ERROR;
}Example 14
| Project: Tank-master File: TankOkHttpClientTest.java View source code |
private String createMultiPartBody() throws IOException {
MultipartBuilder multipartBuilder = new MultipartBuilder().type(MultipartBuilder.FORM);
multipartBuilder.addFormDataPart("textPart", null, RequestBody.create(MediaType.parse("application/atom+xml"), "<xml>here is sample xml</xml>"));
RequestBody requestBodyEntity = multipartBuilder.build();
Buffer buffer = new Buffer();
requestBodyEntity.writeTo(buffer);
String ret = new String();
ret = toBase64(buffer.readByteArray());
return ret;
}Example 15
| Project: api-java-client-master File: RestClient.java View source code |
public Response multipartPost(final String url, final String bodyName, final String body, final String fileName, final File file) {
OkHttpClient multipartClient = client.clone();
try {
RequestBody jsonPart = RequestBody.create(MediaType.parse("text/plain; charset=UTF-8"), body);
RequestBody filePart = RequestBody.create(MediaType.parse("application/octet-stream; charset=ISO-8859-1"), file);
RequestBody requestBody = new MultipartBuilder().type(MultipartBuilder.FORM).addPart(Headers.of("Content-Disposition", "form-data; name=\"" + bodyName + "\""), //
jsonPart).addFormDataPart(fileName, file.getName(), //
filePart).build();
Request request = //
new Request.Builder().url(absolute(url)).post(requestBody).build();
Response response = multipartClient.newCall(request).execute();
checkResponse(request, response, response.body().string());
return response;
} catch (IOException ex) {
throw Throwables.propagate(ex);
}
}Example 16
| Project: Catroid-master File: ServerCalls.java View source code |
public void uploadProject(String projectName, String projectDescription, String zipFileString, String userEmail, String language, String token, String username, ResultReceiver receiver, Integer notificationId, Context context) throws WebconnectionException {
Preconditions.checkNotNull(context, "Context cannot be null!");
userEmail = emailForUiTests == null ? userEmail : emailForUiTests;
userEmail = userEmail == null ? "" : userEmail;
try {
String md5Checksum = Utils.md5Checksum(new File(zipFileString));
final String serverUrl = useTestUrl ? TEST_FILE_UPLOAD_URL_HTTP : FILE_UPLOAD_URL;
Log.v(TAG, "Url to upload: " + serverUrl);
File file = new File(zipFileString);
RequestBody requestBody = new MultipartBuilder().type(MultipartBuilder.FORM).addFormDataPart(FILE_UPLOAD_TAG, ProjectUploadService.UPLOAD_FILE_NAME, RequestBody.create(MEDIA_TYPE_ZIPFILE, file)).addFormDataPart(PROJECT_NAME_TAG, projectName).addFormDataPart(PROJECT_DESCRIPTION_TAG, projectDescription).addFormDataPart(USER_EMAIL, userEmail).addFormDataPart(PROJECT_CHECKSUM_TAG, md5Checksum).addFormDataPart(Constants.TOKEN, token).addFormDataPart(Constants.USERNAME, username).addFormDataPart(DEVICE_LANGUAGE, language).build();
Request request = new Request.Builder().url(serverUrl).post(requestBody).build();
Response response = okHttpClient.newCall(request).execute();
if (response.isSuccessful()) {
Log.v(TAG, "Upload successful");
StatusBarNotificationManager.getInstance().showOrUpdateNotification(notificationId, 100);
} else {
Log.v(TAG, "Upload not successful");
throw new WebconnectionException(response.code(), "Upload failed! HTTP Status code was " + response.code());
}
UploadResponse uploadResponse = gson.fromJson(response.body().string(), UploadResponse.class);
String newToken = uploadResponse.token;
String answer = uploadResponse.answer;
int status = uploadResponse.statusCode;
projectId = uploadResponse.projectId;
if (status != SERVER_RESPONSE_TOKEN_OK) {
throw new WebconnectionException(status, "Upload failed! JSON Response was " + status);
}
if (token.length() != TOKEN_LENGTH || token.isEmpty() || token.equals(TOKEN_CODE_INVALID)) {
throw new WebconnectionException(status, answer);
}
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
sharedPreferences.edit().putString(Constants.TOKEN, newToken).commit();
sharedPreferences.edit().putString(Constants.USERNAME, username).commit();
} catch (JsonSyntaxException jsonSyntaxException) {
Log.e(TAG, Log.getStackTraceString(jsonSyntaxException));
throw new WebconnectionException(WebconnectionException.ERROR_JSON, "JsonSyntaxException");
} catch (IOException ioException) {
Log.e(TAG, Log.getStackTraceString(ioException));
throw new WebconnectionException(WebconnectionException.ERROR_NETWORK, "I/O Exception");
}
}Example 17
| Project: Diary.Ru-Client-master File: MessageSenderFragment.java View source code |
@SuppressWarnings("unchecked")
public boolean handleMessage(Message message) {
try {
switch(message.what) {
case HANDLE_DO_POST:
case HANDLE_DO_COMMENT:
{
mHttpClient.postPageToString(postParams);
mUiHandler.sendEmptyMessage(message.what);
return true;
}
case HANDLE_DO_UMAIL:
{
String result = mHttpClient.postPageToString(postParams);
if (result.contains("ПиÑ?ьмо отправлено"))
mUiHandler.sendEmptyMessage(HANDLE_UMAIL_ACK);
else
mUiHandler.sendEmptyMessage(HANDLE_UMAIL_REJ);
return true;
}
case HANDLE_GET_SMILIES:
{
String url = message.obj != null ? (String) message.obj : "http://www.diary.ru/smile.php";
// не Ñ?одержащее недопуÑ?тимых Ñ?имволов длÑ? ФС имÑ?
String urlValid = url.replaceAll("[:/]", "_");
String result;
if (mCache.hasData(getActivity(), urlValid))
result = new String(mCache.retrieveData(getActivity(), urlValid));
else {
result = mHttpClient.getPageAsString(url);
if (result == null) {
mUiHandler.sendEmptyMessage(HANDLE_CONN_ERROR);
return true;
}
mCache.cacheData(getActivity(), result.getBytes(), urlValid);
}
Document rootNode = Jsoup.parse(result);
Elements smilies = rootNode.select("tr img");
Elements smileLinks = rootNode.select("ul a");
smileMap = new HashMap<>();
for (Element smilie : smilies) smileMap.put(smilie.attr("alt"), smilie.attr("src"));
// раÑ?параллеливаем получение Ñ?майликов
// в маÑ?Ñ?иве теперь будет хранитьÑ?Ñ? Ñ?трока вызова Ñ?майлика - задача загрузки аватара
ExecutorService executor = Executors.newFixedThreadPool(smileMap.size());
for (String id : smileMap.keySet()) {
final String smileUrl = (String) smileMap.get(id);
FutureTask<Drawable> future = new FutureTask<>(new Callable<Drawable>() {
@Override
public Drawable call() throws Exception {
String name = smileUrl.substring(smileUrl.lastIndexOf('/') + 1);
byte[] outputBytes;
if (mCache.hasData(getActivity(), name))
outputBytes = mCache.retrieveData(getActivity(), name);
else {
outputBytes = mHttpClient.getPageAsByteArray(smileUrl);
// caching image
mCache.cacheData(getActivity(), outputBytes, name);
}
return new GifDrawable(outputBytes);
}
});
smileMap.put(id, future);
executor.execute(future);
}
// хак длÑ? того, чтобы вÑ?Ñ‘ работало в одном потоке
while (true) {
int remaining = 0;
for (String id : smileMap.keySet()) if (smileMap.get(id) instanceof FutureTask) {
FutureTask<Drawable> future = (FutureTask<Drawable>) smileMap.get(id);
if (future.isDone())
smileMap.put(id, future.get());
else
remaining++;
}
if (remaining == 0)
break;
}
mUiHandler.sendMessage(mUiHandler.obtainMessage(HANDLE_GET_SMILIES, smileLinks));
return true;
}
case HANDLE_REQUEST_AVATARS:
{
String url = "http://www.diary.ru/options/member/?avatar";
String dataPage = mHttpClient.getPageAsString(url);
if (dataPage == null)
return false;
// Ñ?обираем пары ID аватара - url аватара
Elements avatardivs = Jsoup.parse(dataPage).select("div#avatarbit");
avatarMap = new SparseArray<>();
for (Element avatarbit : avatardivs) {
Integer avId = Integer.valueOf(avatarbit.select("input[name=use_avatar_id]").val());
String imageUrl = avatarbit.child(0).attr("style");
imageUrl = imageUrl.substring(imageUrl.lastIndexOf('(') + 1, imageUrl.lastIndexOf(')'));
avatarMap.put(avId, imageUrl);
}
// раÑ?параллеливаем получение аватарок
// в маÑ?Ñ?иве теперь будет хранитьÑ?Ñ? ID аватара - задача загрузки аватара
ExecutorService executor = Executors.newFixedThreadPool(avatarMap.size());
for (int i = 0; i < avatarMap.size(); i++) {
final String imageUrl = (String) avatarMap.valueAt(i);
FutureTask<Drawable> future = new FutureTask<>(new Callable<Drawable>() {
@Override
public Drawable call() throws Exception {
final byte[] imageBytes = mHttpClient.getPageAsByteArray(imageUrl);
Bitmap image = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
return new BitmapDrawable(getResources(), image);
}
});
avatarMap.setValueAt(i, future);
executor.execute(future);
}
// хак длÑ? того, чтобы вÑ?Ñ‘ работало в одном потоке
while (true) {
int remaining = 0;
for (int i = 0; i < avatarMap.size(); i++) if (avatarMap.valueAt(i) instanceof FutureTask) {
FutureTask<Drawable> future = (FutureTask<Drawable>) avatarMap.valueAt(i);
if (future.isDone())
avatarMap.setValueAt(i, future.get());
else
remaining++;
}
if (remaining == 0)
break;
}
mUiHandler.sendEmptyMessage(HANDLE_REQUEST_AVATARS);
return true;
}
case HANDLE_GET_DRAFTS:
{
String url = mHttpClient.getCurrentUrl() + "?draft";
String dataPage = mHttpClient.getPageAsString(url);
if (dataPage == null) {
// ошибка Ñ?оединениÑ?
mUiHandler.sendMessage(mUiHandler.obtainMessage(message.what, null));
return false;
}
Elements posts = Jsoup.parse(dataPage).select("#postsArea > [id~=post\\d+]");
List<Post> drafts = new ArrayList<>(posts.size());
if (posts.isEmpty()) {
// нет черновиков?
mUiHandler.sendMessage(mUiHandler.obtainMessage(message.what, drafts));
return false;
}
for (Element post : posts) {
Post draft = new Post();
draft.date = post.select(".postTitle > span").attr("title");
draft.title = post.select(".postTitle h2").text();
String fullContent = post.select(".postContent .postInner .paragraph").text();
draft.content = fullContent.substring(0, fullContent.length() > 100 ? 100 : fullContent.length());
// поÑ?ле post#####
draft.postID = post.id().substring(4);
draft.url = post.select(".postLinksBackg .urlLink a").attr("href");
drafts.add(draft);
}
mUiHandler.sendMessage(mUiHandler.obtainMessage(message.what, drafts));
return true;
}
case HANDLE_SET_AVATAR:
{
String URL = "http://www.diary.ru/options/member/?avatar";
mHttpClient.postPageToString(URL, postParams);
Toast.makeText(getActivity(), R.string.avatar_selected, Toast.LENGTH_SHORT).show();
return true;
}
case Utils.HANDLE_UPLOAD_MUSIC:
{
File file = new File((String) message.obj);
mHttpClient.getPage(URI.create("http://pleer.com/upload"));
long length = file.length();
final DiaryHttpClient.ProgressListener listener = new SendProgressListener(length);
MultipartBuilder mpEntityBuilder = new MultipartBuilder();
mpEntityBuilder.type(MultipartBuilder.FORM).addFormDataPart("module", "photolib").addFormDataPart("signature", mSignature).addFormDataPart("resulttype1", String.valueOf(message.arg1)).addFormDataPart("file", file.getName(), new DiaryHttpClient.CountingFileRequestBody(file, listener));
String progressId = "";
for (int i = 0; i < 8; ++i) {
progressId += (int) Math.ceil(Math.random() * 100000);
}
String str = mHttpClient.postPageToString("http://pleer.com/upload/send?X-Progress-ID=" + progressId, mpEntityBuilder.build());
if (str == null) {
Toast.makeText(getActivity(), getString(R.string.message_send_error), Toast.LENGTH_LONG).show();
pd.dismiss();
break;
}
Gson pleerGson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
// check if upload was success
PleerUploadAnswer uploadAnswer = pleerGson.fromJson(str, PleerUploadAnswer.class);
if (!uploadAnswer.isCorrectFile()) {
Toast.makeText(getActivity(), getString(R.string.pp_wrong_file), Toast.LENGTH_LONG).show();
pd.dismiss();
break;
}
if (!uploadAnswer.isCorrectName()) {
Toast.makeText(getActivity(), getString(R.string.pp_wrong_name), Toast.LENGTH_LONG).show();
pd.dismiss();
break;
}
MultipartBuilder embedBody = new MultipartBuilder().type(MultipartBuilder.FORM).addFormDataPart("id", uploadAnswer.getLink());
String embedStr = mHttpClient.postPageToString("http://pleer.com/site_api/embed/track", embedBody.build());
if (embedStr == null) {
Toast.makeText(getActivity(), getString(R.string.message_send_error), Toast.LENGTH_LONG).show();
pd.dismiss();
break;
}
PleerEmbedAnswer embedAnswer = pleerGson.fromJson(embedStr, PleerEmbedAnswer.class);
if (!embedAnswer.isSuccess()) {
Toast.makeText(getActivity(), getString(R.string.embed_error), Toast.LENGTH_LONG).show();
pd.dismiss();
break;
}
InputStream is = getResources().getAssets().open("plaintext/prostopleer_embed.html");
String htmlToEmbed = String.format(Utils.getStringFromInputStream(is), embedAnswer.getEmbedId(), message.arg1 == 2 ? "grey" : "black", embedAnswer.getEmbedId(), message.arg1 == 2 ? "grey" : "black", uploadAnswer.getLink(), embedAnswer.getName());
mUiHandler.sendMessage(mUiHandler.obtainMessage(Utils.HANDLE_UPLOAD_MUSIC, htmlToEmbed));
pd.dismiss();
break;
}
case Utils.HANDLE_UPLOAD_GIF:
{
File gifImage = new File((String) message.obj);
long length = gifImage.length();
final DiaryHttpClient.ProgressListener listener = new SendProgressListener(length);
Headers authHeaders = new Headers.Builder().add("Authorization", Utils.IMGUR_CLIENT_AUTH).build();
MultipartBuilder mpEntityBuilder = new MultipartBuilder();
mpEntityBuilder.type(MultipartBuilder.FORM).addFormDataPart("title", gifImage.getName()).addFormDataPart("type", "file").addFormDataPart("image", gifImage.getName(), new DiaryHttpClient.CountingFileRequestBody(gifImage, listener));
String result = mHttpClient.postPageToString(Utils.IMGUR_API_ENDPOINT + "image", mpEntityBuilder.build(), authHeaders);
ImgurImageResponse response = new Gson().fromJson(result, ImgurImageResponse.class);
if (!response.success) {
Toast.makeText(getActivity(), getString(R.string.message_send_error), Toast.LENGTH_LONG).show();
pd.dismiss();
break;
}
// 100 / 200 / 300
int width = message.arg1 * 100;
double rate = width / (float) response.data.width;
int height = (int) (response.data.height * rate);
String toPaste = String.format("<img width='%d' height='%d' src='%s' />", width, height, response.data.link);
mUiHandler.sendMessage(mUiHandler.obtainMessage(Utils.HANDLE_UPLOAD_GIF, toPaste));
pd.dismiss();
break;
}
case Utils.HANDLE_UPLOAD_FILE:
{
try {
File file = new File((String) message.obj);
long length = file.length();
final DiaryHttpClient.ProgressListener listener = new SendProgressListener(length);
MultipartBuilder mpEntityBuilder = new MultipartBuilder();
mpEntityBuilder.type(MultipartBuilder.FORM).addFormDataPart("module", "photolib").addFormDataPart("signature", mSignature).addFormDataPart("resulttype1", String.valueOf(message.arg1)).addFormDataPart("attachment1", URLEncoder.encode(file.getName(), "windows-1251"), new DiaryHttpClient.CountingFileRequestBody(file, listener));
String result = mHttpClient.postPageToString("http://www.diary.ru/diary.php?upload=1&js", mpEntityBuilder.build());
if (result != null) {
if (// ошибка отправки, Ñ?лишком большаÑ? картинка
result.contains("допуÑ?тимые:"))
Toast.makeText(getActivity(), getString(R.string.too_big_picture), Toast.LENGTH_LONG).show();
else {
result = result.substring(result.indexOf("'") + 1, result.indexOf("';"));
if (result.length() > 0)
mUiHandler.sendMessage(mUiHandler.obtainMessage(Utils.HANDLE_UPLOAD_FILE, result));
else
Toast.makeText(getActivity(), getString(R.string.message_send_error), Toast.LENGTH_LONG).show();
}
//resEntity.consumeContent();
} else {
Toast.makeText(getActivity(), getString(R.string.message_send_error), Toast.LENGTH_LONG).show();
}
pd.dismiss();
} catch (Exception e) {
Toast.makeText(getActivity(), getString(R.string.file_not_found), Toast.LENGTH_SHORT).show();
}
return true;
}
default:
break;
}
} catch (Exception ignored) {
mUiHandler.sendEmptyMessage(HANDLE_CONN_ERROR);
}
return false;
}