List of usage examples for com.squareup.okhttp RequestBody RequestBody
RequestBody
From source file:com.he5ed.lib.cloudprovider.apis.OneDriveApi.java
License:Apache License
@Override public CFile uploadFile(@NonNull final File file, @Nullable CFolder parent) throws RequestFailException { if (TextUtils.isEmpty(mAccessToken)) { throw new RequestFailException("Access token not available"); }/* w ww . ja v a2 s . c o m*/ Uri uri = Uri.parse(API_BASE_URL); String url = uri.buildUpon() .appendEncodedPath("drive/items/" + (parent != null ? parent.getId() : getRoot().getId()) + "/children/" + file.getName() + "/content") .appendQueryParameter("@name.conflictBehavior", "fail").build().toString(); RequestBody fileBody = new RequestBody() { @Override public MediaType contentType() { return null; } @Override public void writeTo(BufferedSink sink) throws IOException { // copy file into RequestBody FilesUtils.copyFile(new FileInputStream(file), sink.outputStream()); } }; Request request = new Request.Builder().url(url) .header("Authorization", String.format("Bearer %s", mAccessToken)).put(fileBody).build(); try { Response response = mHttpClient.newCall(request).execute(); if (response.isSuccessful()) { // new file created JSONObject jsonObject = new JSONObject(response.body().string()); return buildFile(jsonObject); } else { throw new RequestFailException(response.message(), response.code()); } } catch (JSONException e) { e.printStackTrace(); throw new RequestFailException(e.getMessage()); } catch (IOException e) { e.printStackTrace(); throw new RequestFailException(e.getMessage()); } }
From source file:com.he5ed.lib.cloudprovider.apis.OneDriveApi.java
License:Apache License
@Override public CFile updateFile(@NonNull CFile file, final File content) throws RequestFailException { if (TextUtils.isEmpty(mAccessToken)) { throw new RequestFailException("Access token not available"); }//from w w w. j a va2s . co m Uri uri = Uri.parse(API_BASE_URL); String url = uri.buildUpon().appendEncodedPath("drive/items/" + file.getId() + "/content") .appendQueryParameter("@name.conflictBehavior", "replace").build().toString(); RequestBody fileBody = new RequestBody() { @Override public MediaType contentType() { return null; } @Override public void writeTo(BufferedSink sink) throws IOException { // copy file into RequestBody FilesUtils.copyFile(new FileInputStream(content), sink.outputStream()); } }; Request request = new Request.Builder().url(url) .header("Authorization", String.format("Bearer %s", mAccessToken)).put(fileBody).build(); try { Response response = mHttpClient.newCall(request).execute(); if (response.isSuccessful()) { // new file created JSONObject jsonObject = new JSONObject(response.body().string()); return buildFile(jsonObject); } else { throw new RequestFailException(response.message(), response.code()); } } catch (JSONException e) { e.printStackTrace(); throw new RequestFailException(e.getMessage()); } catch (IOException e) { e.printStackTrace(); throw new RequestFailException(e.getMessage()); } }
From source file:com.he5ed.lib.cloudprovider.apis.OneDriveApi.java
License:Apache License
@Override public CFile renameFile(@NonNull CFile file, String name) throws RequestFailException { if (TextUtils.isEmpty(mAccessToken)) { throw new RequestFailException("Access token not available"); }/* ww w.j a v a 2 s. c om*/ // exist if same filename if (file.getName().equals(name)) return file; // create parameter as json final JSONObject params = new JSONObject(); try { params.put("name", name); } catch (JSONException e) { e.printStackTrace(); throw new RequestFailException(e.getMessage()); } RequestBody body = new RequestBody() { @Override public MediaType contentType() { return JSON; } @Override public void writeTo(BufferedSink sink) throws IOException { sink.writeUtf8(params.toString()); } }; Request request = new Request.Builder().url(API_BASE_URL + "/drive/items/" + file.getId()) .header("Authorization", String.format("Bearer %s", mAccessToken)).patch(body).build(); try { Response response = mHttpClient.newCall(request).execute(); if (response.isSuccessful()) { // return file object return buildFile(new JSONObject(response.body().string())); } else { throw new RequestFailException(response.message(), response.code()); } } catch (JSONException e) { e.printStackTrace(); throw new RequestFailException(e.getMessage()); } catch (IOException e) { e.printStackTrace(); throw new RequestFailException(e.getMessage()); } }
From source file:com.he5ed.lib.cloudprovider.apis.OneDriveApi.java
License:Apache License
@Override public CFile moveFile(@NonNull CFile file, @Nullable CFolder folder) throws RequestFailException { if (TextUtils.isEmpty(mAccessToken)) { throw new RequestFailException("Access token not available"); }/*from ww w . j av a2 s .c o m*/ // create parameter as json final JSONObject params = new JSONObject(); try { params.put("parentReference", new JSONObject().put("id", folder != null ? folder.getId() : getRoot().getId())); } catch (JSONException e) { e.printStackTrace(); throw new RequestFailException(e.getMessage()); } RequestBody body = new RequestBody() { @Override public MediaType contentType() { return JSON; } @Override public void writeTo(BufferedSink sink) throws IOException { sink.writeUtf8(params.toString()); } }; Request request = new Request.Builder().url(API_BASE_URL + "/drive/items/" + file.getId()) .header("Authorization", String.format("Bearer %s", mAccessToken)).patch(body).build(); try { Response response = mHttpClient.newCall(request).execute(); if (response.isSuccessful()) { // return file object return buildFile(new JSONObject(response.body().string())); } else { throw new RequestFailException(response.message(), response.code()); } } catch (JSONException e) { e.printStackTrace(); throw new RequestFailException(e.getMessage()); } catch (IOException e) { e.printStackTrace(); throw new RequestFailException(e.getMessage()); } }
From source file:com.heroiclabs.sdk.android.util.http.GzipRequestInterceptor.java
License:Apache License
/** * Force the content length for a given RequestBody that may not have calculated it correctly. * * @param requestBody The RequestBody to force content length for. * @return A new RequestBody with the correct contentLength set. * @throws IOException if writing to buffer fails. */// w ww.j a v a 2 s. co m private static RequestBody forceContentLength(final RequestBody requestBody) throws IOException { final Buffer buffer = new Buffer(); requestBody.writeTo(buffer); return new RequestBody() { @Override public MediaType contentType() { return requestBody.contentType(); } @Override public long contentLength() { return buffer.size(); } @Override public void writeTo(final BufferedSink sink) throws IOException { sink.write(buffer.snapshot()); } }; }
From source file:com.heroiclabs.sdk.android.util.http.GzipRequestInterceptor.java
License:Apache License
/** * Compress the contents of the given RequestBody into a new one. * * @param body The RequestBody to compress. * @return A new RequestBody with compressed content. *///from w w w. jav a2 s . co m private static RequestBody gzip(final RequestBody body) { return new RequestBody() { @Override public MediaType contentType() { return body.contentType(); } @Override public long contentLength() { return -1; // We don't know the compressed length in advance! } @Override public void writeTo(final BufferedSink sink) throws IOException { final BufferedSink gzipSink = Okio.buffer(new GzipSink(sink)); body.writeTo(gzipSink); gzipSink.close(); } }; }
From source file:com.tinspx.util.net.okhttp.OkHttpContext.java
License:Open Source License
static @Nullable RequestBody createRequestBody(Request request) throws IOException { if (!request.hasBody()) { return null; }/*from w w w . j a v a 2s .com*/ final com.tinspx.util.net.RequestBody body = request.body().get(); String contentType = null; long len = -1; for (Map.Entry<String, String> header : body.headers().entries()) { String normalized = notNullTrimLower.apply(header.getKey()); if (CONTENT_TYPE.equals(normalized)) { contentType = header.getValue().trim(); } else if (CONTENT_LENGTH.equals(normalized)) { //invalid length will throw NumberFormatException //TODO: ignore this header and just use the body.size()? //maybe only use the header if hasKnownSize is false len = Long.parseLong(header.getValue().trim()); checkState(len >= 0, "%s has an invalid Content-Length (%s)", body, len); } else { request.addHeader(header.getKey(), header.getValue()); } } //content-type is not required final MediaType mediaType; if (contentType != null) { mediaType = MediaType.parse(contentType); checkState(mediaType != null, "%s has an invalid Content-Type (%s)", body, contentType); } else { mediaType = null; } final long contentLength = len; return new RequestBody() { final Object lock = new Object(); /** * saving the exception is a hack that should work until okhttp * fixes RequestBody. */ @GuardedBy("lock") IOException last; @Override public long contentLength() { if (contentLength >= 0) { return contentLength; } try { if (body.hasKnownSize()) { return body.size(); } } catch (IOException ex) { log.error("polling size of {}", body, ex); synchronized (lock) { last = ex; } } return -1; } @Override public MediaType contentType() { return mediaType; } @Override public void writeTo(BufferedSink sink) throws IOException { synchronized (lock) { if (last != null) { IOException ex = last; last = null; throw ex; } } body.copyTo(sink.outputStream()); } }; }
From source file:com.yandex.disk.rest.RequestBodyProgress.java
License:Apache License
/** * Returns a new request body that transmits the content of {@code file}. * <br/>/*from w w w .ja va 2 s . c om*/ * Based on {@link RequestBody#create(com.squareup.okhttp.MediaType, File)} * * @see RequestBody#create(com.squareup.okhttp.MediaType, File) */ /* package */ static RequestBody create(final MediaType contentType, final File file, final long startOffset, final ProgressListener listener) { if (file == null) { throw new NullPointerException("content == null"); } if (listener == null && startOffset == 0) { return RequestBody.create(contentType, file); } return new RequestBody() { private void updateProgress(long loaded) throws CancelledUploadingException { if (listener != null) { if (listener.hasCancelled()) { throw new CancelledUploadingException(); } listener.updateProgress(loaded + startOffset, file.length()); } } @Override public MediaType contentType() { return contentType; } @Override public long contentLength() { return file.length() - startOffset; } @Override public void writeTo(BufferedSink sink) throws IOException { Source source = null; InputStream inputStream = new FileInputStream(file); try { if (startOffset > 0) { long skipped = inputStream.skip(startOffset); if (skipped != startOffset) { throw new IOException("RequestBodyProgress: inputStream.skip() failed"); } } long loaded = 0; updateProgress(loaded); source = Okio.source(inputStream); Buffer buffer = new Buffer(); for (long readCount; (readCount = source.read(buffer, SIZE)) != -1;) { sink.write(buffer, readCount); loaded += readCount; updateProgress(loaded); } logger.debug("loaded: " + loaded); } finally { Util.closeQuietly(source); Util.closeQuietly(inputStream); } } }; }
From source file:es.upv.grycap.coreutils.fiber.http.Http2Client.java
License:Apache License
/** * Posts the content of a buffer of bytes to a server via a HTTP POST request. * @param url - URL target of this request * @param mediaType - Content-Type header for this request * @param supplier - supplies the content of this request * @param callback - is called back when the response is readable *///from www. j a v a 2 s . com public void asyncPostBytes(final String url, final String mediaType, final Supplier<byte[]> supplier, final Callback callback) { final String url2 = requireNonNull(trimToNull(url), "A non-empty URL expected"); final String mediaType2 = requireNonNull(trimToNull(mediaType), "A non-empty media type expected"); requireNonNull(supplier, "A valid supplier expected"); requireNonNull(callback, "A valid callback expected"); // prepare request final Request request = new Request.Builder().url(url2).post(new RequestBody() { @Override public MediaType contentType() { return MediaType.parse(mediaType2 + "; charset=utf-8"); } @Override public void writeTo(final BufferedSink sink) throws IOException { sink.write(supplier.get()); } }).build(); // submit request client.newCall(request).enqueue(callback); }
From source file:es.upv.grycap.coreutils.fiber.http.Http2Client.java
License:Apache License
/** * Puts the content of a buffer of bytes to a server via a HTTP PUT request. * @param url - URL target of this request * @param mediaType - Content-Type header for this request * @param supplier - supplies the content of this request * @param callback - is called back when the response is readable */// w w w .jav a 2 s .c o m public void asyncPutBytes(final String url, final String mediaType, final Supplier<byte[]> supplier, final Callback callback) { final String url2 = requireNonNull(trimToNull(url), "A non-empty URL expected"); final String mediaType2 = requireNonNull(trimToNull(mediaType), "A non-empty media type expected"); requireNonNull(supplier, "A valid supplier expected"); requireNonNull(callback, "A valid callback expected"); // prepare request final Request request = new Request.Builder().url(url2).put(new RequestBody() { @Override public MediaType contentType() { return MediaType.parse(mediaType2 + "; charset=utf-8"); } @Override public void writeTo(final BufferedSink sink) throws IOException { sink.write(supplier.get()); } }).build(); // submit request client.newCall(request).enqueue(callback); }