List of usage examples for com.squareup.okhttp RequestBody create
public static RequestBody create(final MediaType contentType, final File file)
From source file:com.groupon.odo.bmp.BrowserMobProxyHandler.java
License:Apache License
protected long proxyPlainTextRequest(final URL url, String pathInContext, String pathParams, HttpRequest request, final HttpResponse response) throws IOException { try {/*from w w w . j a va2 s . com*/ String urlStr = url.toString(); if (urlStr.toLowerCase().startsWith(Constants.ODO_INTERNAL_WEBAPP_URL)) { urlStr = "http://localhost:" + com.groupon.odo.proxylib.Utils.getSystemPort(Constants.SYS_HTTP_PORT) + "/odo"; } // setup okhttp to ignore ssl issues OkHttpClient okHttpClient = getUnsafeOkHttpClient(); okHttpClient.setFollowRedirects(false); okHttpClient.setFollowSslRedirects(false); Request.Builder okRequestBuilder = new Request.Builder(); /* * urlStr.indexOf(":") == urlStr.lastIndexOf(":") verifies that the url does not have a port * by checking it only has a : as part of http:// */ if (urlStr.startsWith("http://") && urlStr.indexOf(":") == urlStr.lastIndexOf(":")) { int httpPort = com.groupon.odo.proxylib.Utils.getSystemPort(Constants.SYS_HTTP_PORT); urlStr = urlStr.replace(getHostNameFromURL(urlStr), localIP + ":" + httpPort); } okRequestBuilder = okRequestBuilder.url(urlStr); // copy request headers Enumeration<?> enm = request.getFieldNames(); boolean isGet = "GET".equals(request.getMethod()); boolean hasContent = false; boolean usedContentLength = false; long contentLength = 0; while (enm.hasMoreElements()) { String hdr = (String) enm.nextElement(); if (!isGet && HttpFields.__ContentType.equals(hdr)) { hasContent = true; } if (!isGet && HttpFields.__ContentLength.equals(hdr)) { contentLength = Long.parseLong(request.getField(hdr)); usedContentLength = true; } Enumeration<?> vals = request.getFieldValues(hdr); while (vals.hasMoreElements()) { String val = (String) vals.nextElement(); if (val != null) { if (!isGet && HttpFields.__ContentLength.equals(hdr) && Integer.parseInt(val) > 0) { hasContent = true; } if (!_DontProxyHeaders.containsKey(hdr)) { okRequestBuilder = okRequestBuilder.addHeader(hdr, val); //httpReq.addRequestHeader(hdr, val); } } } } if ("GET".equals(request.getMethod())) { // don't need to do anything else } else if ("POST".equals(request.getMethod()) || "PUT".equals(request.getMethod()) || "DELETE".equals(request.getMethod())) { RequestBody okRequestBody = null; if (hasContent) { final String contentType = request.getContentType(); final byte[] bytes = IOUtils.toByteArray(request.getInputStream()); okRequestBody = new RequestBody() { @Override public MediaType contentType() { MediaType.parse(contentType); return null; } @Override public void writeTo(BufferedSink bufferedSink) throws IOException { bufferedSink.write(bytes); } }; // we need to add some ODO specific headers to give ODO a hint for content-length vs transfer-encoding // since okHTTP will automatically chunk even if the request was not chunked // this allows Odo to set the appropriate headers when the server request is made if (usedContentLength) { okRequestBuilder = okRequestBuilder.addHeader("ODO-POST-TYPE", "content-length:" + contentLength); } } else { okRequestBody = RequestBody.create(null, new byte[0]); } if ("POST".equals(request.getMethod())) { okRequestBuilder = okRequestBuilder.post(okRequestBody); } else if ("PUT".equals(request.getMethod())) { okRequestBuilder = okRequestBuilder.put(okRequestBody); } else if ("DELETE".equals(request.getMethod())) { okRequestBuilder = okRequestBuilder.delete(okRequestBody); } } else if ("OPTIONS".equals(request.getMethod())) { // NOT SUPPORTED } else if ("HEAD".equals(request.getMethod())) { okRequestBuilder = okRequestBuilder.head(); } else { LOG.warn("Unexpected request method %s, giving up", request.getMethod()); request.setHandled(true); return -1; } Request okRequest = okRequestBuilder.build(); Response okResponse = okHttpClient.newCall(okRequest).execute(); // Set status and response message response.setStatus(okResponse.code()); response.setReason(okResponse.message()); // copy response headers for (int headerNum = 0; headerNum < okResponse.headers().size(); headerNum++) { String headerName = okResponse.headers().name(headerNum); if (!_DontProxyHeaders.containsKey(headerName) && !_ProxyAuthHeaders.containsKey(headerName)) { response.addField(headerName, okResponse.headers().value(headerNum)); } } // write output to response output stream try { IOUtils.copy(okResponse.body().byteStream(), response.getOutputStream()); } catch (Exception e) { // ignoring this until we refactor the proxy // The copy occasionally fails due to an issue where okResponse has more data in the body than it's supposed to // The client still gets all of the data it was expecting } request.setHandled(true); return okResponse.body().contentLength(); } catch (Exception e) { LOG.warn("Caught exception proxying: ", e); reportError(e, url, response); request.setHandled(true); return -1; } }
From source file:com.he5ed.lib.cloudprovider.apis.BoxApi.java
License:Apache License
@Override public synchronized CFile uploadFile(@NonNull File file, @Nullable CFolder parent) throws RequestFailException { if (TextUtils.isEmpty(mAccessToken)) { throw new RequestFailException("Access token not available"); }//from ww w . j a v a 2s .c o m // create parameter as json final JSONObject params = new JSONObject(); try { params.put("name", file.getName()); params.put("parent", new JSONObject().put("id", parent != null ? parent.getId() : getRoot().getId())); } catch (JSONException e) { e.printStackTrace(); throw new RequestFailException(e.getMessage()); } // create multipart body MediaType fileType = MediaType.parse(FilesUtils.getFileType(file)); RequestBody multipart = new MultipartBuilder().type(MultipartBuilder.FORM) .addFormDataPart("attributes", params.toString()) .addFormDataPart("file", file.getName(), RequestBody.create(fileType, file)).build(); Request request = new Request.Builder().url(API_UPLOAD_URL + "/files/content") .header("Authorization", String.format("Bearer %s", mAccessToken)).post(multipart).build(); try { Response response = mHttpClient.newCall(request).execute(); if (response.isSuccessful()) { // new file created JSONObject jsonObject = new JSONObject(response.body().string()); JSONArray entries = jsonObject.getJSONArray("entries"); return buildFile(entries.getJSONObject(0)); } 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.BoxApi.java
License:Apache License
@Override public synchronized CFile updateFile(@NonNull CFile file, File content) throws RequestFailException { if (TextUtils.isEmpty(mAccessToken)) { throw new RequestFailException("Access token not available"); }/* w w w .j a va2s . com*/ // create multipart body MediaType fileType = MediaType.parse(FilesUtils.getFileType(content)); RequestBody multipart = new MultipartBuilder().type(MultipartBuilder.FORM) .addFormDataPart("file", content.getName(), RequestBody.create(fileType, content)).build(); Request request = new Request.Builder().url(API_UPLOAD_URL + "/files/" + file.getId() + "/content") .header("Authorization", String.format("Bearer %s", mAccessToken)).post(multipart).build(); try { Response response = mHttpClient.newCall(request).execute(); if (response.isSuccessful()) { // new file created JSONObject jsonObject = new JSONObject(response.body().string()); JSONArray entries = jsonObject.getJSONArray("entries"); return buildFile(entries.getJSONObject(0)); } 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.CloudDriveApi.java
License:Apache License
@Override public CFile uploadFile(@NonNull File file, @Nullable CFolder parent) throws RequestFailException { if (TextUtils.isEmpty(mAccessToken)) { throw new RequestFailException("Access token not available"); }/* w ww.j a va 2 s.c om*/ Uri uri = Uri.parse(mContentUrl); String url = uri.buildUpon().appendEncodedPath("nodes").build().toString(); // create parameter as json final JSONObject params = new JSONObject(); try { params.put("name", file.getName()); params.put("kind", "FILE"); ArrayList<String> parentList = new ArrayList<>(); parentList.add(parent != null ? parent.getId() : getRoot().getId()); params.put("parents", new JSONArray(parentList)); } catch (JSONException e) { e.printStackTrace(); throw new RequestFailException(e.getMessage()); } // create multipart body MediaType fileType = MediaType.parse(FilesUtils.getFileType(file)); RequestBody multipart = new MultipartBuilder().type(MultipartBuilder.FORM) .addFormDataPart("metadata", params.toString()) .addFormDataPart("content", file.getName(), RequestBody.create(fileType, file)).build(); Request request = new Request.Builder().url(url) .header("Authorization", String.format("Bearer %s", mAccessToken)).post(multipart).build(); try { Response response = mHttpClient.newCall(request).execute(); if (response.isSuccessful()) { 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.CloudDriveApi.java
License:Apache License
@Override public CFile updateFile(@NonNull CFile file, File content) throws RequestFailException { if (TextUtils.isEmpty(mAccessToken)) { throw new RequestFailException("Access token not available"); }//from www. j a v a 2 s .c om Uri uri = Uri.parse(mContentUrl); String url = uri.buildUpon().appendEncodedPath("nodes/" + file.getId() + "/content").build().toString(); // create multipart body MediaType fileType = MediaType.parse(FilesUtils.getFileType(content)); RequestBody multipart = new MultipartBuilder().type(MultipartBuilder.FORM) .addFormDataPart("content", file.getName(), RequestBody.create(fileType, content)).build(); Request request = new Request.Builder().url(url) .header("Authorization", String.format("Bearer %s", mAccessToken)).put(multipart).build(); try { Response response = mHttpClient.newCall(request).execute(); if (response.isSuccessful()) { 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.heroiclabs.sdk.android.HttpClient.java
License:Apache License
/** {@inheritDoc} */ public <T> Deferred<Response<T>> execute(final @NonNull Request<T> request) { final Deferred<Response<T>> deferred = new Deferred<>(); // Select the host, implicitly only allow HTTPS. HttpUrl.Builder urlBuilder = new HttpUrl.Builder().scheme("https") .host(getServer(request.getDestination())); // Encode and add the path elements. for (final String p : getPath(request.getRequestType(), request.getIdentifiers())) { urlBuilder = urlBuilder.addPathSegment(p); }//from w ww . j a v a2s .com // Encode and add the query parameters, toString() values as we go. for (final Map.Entry<String, ?> e : request.getParameters().entrySet()) { urlBuilder = urlBuilder.addQueryParameter(e.getKey(), e.getValue().toString()); } final HttpUrl url = urlBuilder.build(); final String token = request.getSession() == null ? "" : request.getSession().getToken(); final String authorization = "Basic " + ByteString.of((apiKey + ":" + token).getBytes()).base64(); final String contentType = "application/json"; final String body = getBody(request.getRequestType(), request.getEntity()); // Construct the HTTP request. final com.squareup.okhttp.Request httpRequest = new com.squareup.okhttp.Request.Builder().url(url) .method(getMethod(request.getRequestType()), body == null ? null : RequestBody.create(MediaType.parse(contentType), body)) .header("User-Agent", USER_AGENT).header("Content-Type", contentType).header("Accept", contentType) .header("Authorization", authorization).build(); // Prepare a HTTP client instance to execute against. final OkHttpClient client = this.client.clone(); // Interceptors fire in the order they're declared. // Note: Compress first, so we don't re-compress for retried requests. if (this.compressRequests) { client.interceptors().add(GzipRequestInterceptor.INSTANCE); } final int maxAttempts = request.getMaxAttempts() < 1 ? this.maxAttempts : request.getMaxAttempts(); client.interceptors().add(new RetryInterceptor(maxAttempts)); // Log the outgoing request. if (log.isDebugEnabled()) { log.debug("Request: Method{" + httpRequest.method() + "} URL{" + httpRequest.urlString() + "} Headers{" + httpRequest.headers().toString() + "} Body{" + body + "}"); } // Send the request and retrieve a response. client.newCall(httpRequest).enqueue(new Callback() { @Override public void onFailure(final com.squareup.okhttp.Request httpRequest, final IOException e) { // Log the request failure reason. if (log.isDebugEnabled()) { log.debug("Request Failed", e); } deferred.callback(new ErrorResponse(e.getMessage(), e, request)); } @Override public void onResponse(final @NonNull com.squareup.okhttp.Response httpResponse) throws IOException { switch (httpResponse.code()) { // Good response with body. case HttpURLConnection.HTTP_OK: final String responseBody = httpResponse.body().string(); // Log the incoming response. if (log.isDebugEnabled()) { log.debug("Response Success: Method{" + httpResponse.request().method() + "} URL{" + httpResponse.request().urlString() + "} Code{" + httpResponse.code() + "} Message{" + httpResponse.message() + "} Headers:{" + httpResponse.headers().toString() + "} Body{" + responseBody + "}"); } final T entity = codec.deserialize(responseBody, request.getResponseType()); deferred.callback(new SuccessResponse<>(request, httpResponse.code(), responseBody, entity)); break; // Good response, no body. case HttpURLConnection.HTTP_NO_CONTENT: case HttpURLConnection.HTTP_CREATED: // Log the incoming response. if (log.isDebugEnabled()) { log.debug("Response Success: Method{" + httpResponse.request().method() + "} URL{" + httpResponse.request().urlString() + "} Code{" + httpResponse.code() + "} Message{" + httpResponse.message() + "} Headers:{" + httpResponse.headers().toString() + "}"); } deferred.callback(new SuccessResponse<>(request, httpResponse.code(), null, null)); break; // Error response. default: final String errorBody = httpResponse.body().string(); // Log the incoming response. if (log.isDebugEnabled()) { log.debug("Response Error: Method{" + httpResponse.request().method() + "} URL{" + httpResponse.request().urlString() + "} Code{" + httpResponse.code() + "} Message{" + httpResponse.message() + "} Headers:{" + httpResponse.headers().toString() + "} Body{" + errorBody + "}"); } @SuppressWarnings("ThrowableResultOfMethodCallIgnored") final ErrorDetails error = errorBody.isEmpty() ? new ErrorDetails(httpResponse.code(), httpResponse.message() == null ? "unknown" : httpResponse.message(), null) : codec.deserialize(errorBody, ErrorDetails.class); deferred.callback(new ErrorResponse(error.getMessage(), error, request)); } // Indicate that application-layer response processing is complete. httpResponse.body().close(); } }); return deferred; }
From source file:com.hileone.restretrofit.request.RequestBuilder.java
License:Apache License
Request build() { HttpUrl url;//from w ww. j a va2s. c o m HttpUrl.Builder urlBuilder = this.urlBuilder; if (urlBuilder != null) { url = urlBuilder.build(); } else { // No query parameters triggered builder creation, just combine the relative URL and base URL. url = baseUrl.resolve(relativeUrl); } RequestBody body = this.body; if (body == null) { // Try to pull from one of the builders. if (formEncodingBuilder != null) { body = formEncodingBuilder.build(); } else if (multipartBuilder != null) { body = multipartBuilder.build(); } else if (hasBody) { // Body is absent, make an empty body. body = RequestBody.create(null, new byte[0]); } } MediaType contentType = this.contentType; if (contentType != null) { if (body != null) { body = new ContentTypeOverridingRequestBody(body, contentType); } else { requestBuilder.addHeader("Content-Type", contentType.toString()); } } return requestBuilder.url(url).method(method, body).build(); }
From source file:com.hippo.nimingban.client.ac.ACEngine.java
License:Apache License
public static Call prepareReply(OkHttpClient okHttpClient, ACReplyStruct struct) throws Exception { MultipartBuilder builder = new MultipartBuilder(); builder.type(MultipartBuilder.FORM); builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"name\""), RequestBody.create(null, StringUtils.avoidNull(struct.name))); builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"email\""), RequestBody.create(null, StringUtils.avoidNull(struct.email))); builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"title\""), RequestBody.create(null, StringUtils.avoidNull(struct.title))); builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"content\""), RequestBody.create(null, StringUtils.avoidNull(struct.content))); builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"resto\""), RequestBody.create(null, StringUtils.avoidNull(struct.resto))); if (struct.water) { builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"water\""), RequestBody.create(null, "true")); }/*w w w . j a v a 2 s .co m*/ InputStreamPipe isPipe = struct.image; if (isPipe != null) { String filename; MediaType mediaType; byte[] bytes; File file = compressBitmap(isPipe, struct.imageType); if (file == null) { String extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(struct.imageType); if (TextUtils.isEmpty(extension)) { extension = "jpg"; } filename = "a." + extension; mediaType = MediaType.parse(struct.imageType); if (mediaType == null) { mediaType = MEDIA_TYPE_IMAGE_ALL; } try { isPipe.obtain(); bytes = IOUtils.getAllByte(isPipe.open()); } finally { isPipe.close(); isPipe.release(); } } else { filename = "a.jpg"; mediaType = MEDIA_TYPE_IMAGE_JPEG; InputStream is = null; try { is = new FileInputStream(file); bytes = IOUtils.getAllByte(is); } finally { IOUtils.closeQuietly(is); file.delete(); } } builder.addPart( Headers.of("Content-Disposition", "form-data; name=\"image\"; filename=\"" + filename + "\""), RequestBody.create(mediaType, bytes)); } String url = ACUrl.API_REPLY; Log.d(TAG, url); Request request = new GoodRequestBuilder(url).post(builder.build()).build(); return okHttpClient.newCall(request); }
From source file:com.hippo.nimingban.client.ac.ACEngine.java
License:Apache License
public static Call prepareCreatePost(OkHttpClient okHttpClient, ACPostStruct struct) throws Exception { MultipartBuilder builder = new MultipartBuilder(); builder.type(MultipartBuilder.FORM); builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"name\""), RequestBody.create(null, StringUtils.avoidNull(struct.name))); builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"email\""), RequestBody.create(null, StringUtils.avoidNull(struct.email))); builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"title\""), RequestBody.create(null, StringUtils.avoidNull(struct.title))); builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"content\""), RequestBody.create(null, StringUtils.avoidNull(struct.content))); builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"fid\""), RequestBody.create(null, StringUtils.avoidNull(struct.fid))); if (struct.water) { builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"water\""), RequestBody.create(null, "true")); }// ww w . ja v a2s . c o m InputStreamPipe isPipe = struct.image; if (isPipe != null) { String filename; MediaType mediaType; byte[] bytes; File file = compressBitmap(isPipe, struct.imageType); if (file == null) { String extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(struct.imageType); if (TextUtils.isEmpty(extension)) { extension = "jpg"; } filename = "a." + extension; mediaType = MediaType.parse(struct.imageType); if (mediaType == null) { mediaType = MEDIA_TYPE_IMAGE_ALL; } try { isPipe.obtain(); bytes = IOUtils.getAllByte(isPipe.open()); } finally { isPipe.close(); isPipe.release(); } } else { filename = "a.jpg"; mediaType = MEDIA_TYPE_IMAGE_JPEG; InputStream is = null; try { is = new FileInputStream(file); bytes = IOUtils.getAllByte(is); } finally { IOUtils.closeQuietly(is); file.delete(); } } builder.addPart( Headers.of("Content-Disposition", "form-data; name=\"image\"; filename=\"" + filename + "\""), RequestBody.create(mediaType, bytes)); } String url = ACUrl.API_CREATE_POST; Log.d(TAG, url); Request request = new GoodRequestBuilder(url).post(builder.build()).build(); return okHttpClient.newCall(request); }
From source file:com.hitkoDev.chemApp.rest.SendJSONDataTask.java
@Override protected String doInBackground(String... urls) { if (checkNetwork()) { String data = urls[0];// www .ja v a 2s . c om String url = buildURL(urls); OkHttpClient client = ChemApp.client; RequestBody body = RequestBody.create(IOLib.JSON, data); Request request = new Request.Builder().url(url).post(body).build(); try { Response response = client.newCall(request).execute(); return response.body().string(); } catch (Exception e) { return "Unable to retrieve web page. URL may be invalid."; } } else { return "No network or cached files"; } }