List of usage examples for com.squareup.okhttp RequestBody create
public static RequestBody create(final MediaType contentType, final File file)
From source file:com.github.arven.rest.AccountServiceTests.java
@Test public void updateAccount() throws Exception { server = new MockWebServer(); server.enqueue(new MockResponse().setHeader("Content-Type", JSON) .setBody(map.writeValueAsString(new ServiceResponse(ServiceResponse.Type.SUCCESS, 200)))); server.enqueue(new MockResponse().setHeader("Content-Type", JSON) .setBody(map.writeValueAsString(new AccountInformation("trfields", "Tom")))); server.play();//from w w w.j a v a 2 s .com URL url = server.getUrl("/users/trfields"); Patch.Builder patch = new Patch.Builder(); patch.test("/username", "trfields"); patch.replace("/nickname", "Tom"); RequestBody patchBody = RequestBody.create(JSON_PATCH, patch.toString()); Request request1 = new Request.Builder().url(url).patch(patchBody).build(); Response response1 = client.newCall(request1).execute(); ServiceResponse body1 = map.readValue(response1.body().string(), ServiceResponse.class); Assert.assertEquals(body1.code, 200); Assert.assertEquals(body1.type, ServiceResponse.Type.SUCCESS); Request request2 = new Request.Builder().url(url).get().build(); Response response2 = client.newCall(request2).execute(); AccountInformation body2 = map.readValue(response2.body().string(), AccountInformation.class); Assert.assertEquals(body2.nickname, "Tom"); Assert.assertEquals(body2.username, "trfields"); RecordedRequest recorded1 = server.takeRequest(); Assert.assertEquals(recorded1.getPath(), "/users/trfields"); Assert.assertEquals(recorded1.getMethod(), "PATCH"); RecordedRequest recorded2 = server.takeRequest(); Assert.assertEquals(recorded2.getPath(), "/users/trfields"); Assert.assertEquals(recorded2.getMethod(), "GET"); server.shutdown(); }
From source file:com.github.automately.sdk.Automately.java
License:Mozilla Public License
public static JsonObject getAutomatelyCloudPlan() { try {/*from w ww . ja va 2s. c om*/ JsonObject requestData = new JsonObject(); requestData.putString("username", getApiUsername()); requestData.putString("apiKey", getApiKey()); Request request = new Request.Builder() .url(USER_API_ENDPOINT + "/getPlan").post(RequestBody .create(MediaType.parse("application/json"), requestData.toString().getBytes())) .build(); Response response = httpClient.newCall(request).execute(); if (response != null) { String responseEntity = response.body().string(); try { return new JsonObject(responseEntity); } catch (DecodeException ignored) { getFormattedError("Decode Exception", "There was an issue decoding the response."); } } } catch (IOException ignored) { } return null; }
From source file:com.github.automately.sdk.Automately.java
License:Mozilla Public License
public static JsonObject setAutomatelyCloudPlan(String planId) { try {/*from w w w . j av a2s.c o m*/ JsonObject requestData = new JsonObject(); requestData.putString("planId", planId); requestData.putString("username", getApiUsername()); requestData.putString("apiKey", getApiKey()); Request request = new Request.Builder() .url(USER_API_ENDPOINT + "/changePlan").post(RequestBody .create(MediaType.parse("application/json"), requestData.toString().getBytes())) .build(); Response response = httpClient.newCall(request).execute(); if (response != null) { String responseEntity = response.body().string(); try { return new JsonObject(responseEntity); } catch (DecodeException ignored) { getFormattedError("Decode Exception", "There was an issue decoding the response."); } } } catch (IOException ignored) { } return null; }
From source file:com.github.automately.sdk.Automately.java
License:Mozilla Public License
public static JsonObject registerModule(JsonObject manifest) { try {//from w w w . j ava2s .c o m JsonObject requestData = new JsonObject(); // The module register requires authentication requestData.putObject("manifest", manifest); requestData.putString("username", getApiUsername()); requestData.putString("apiKey", getApiKey()); Request request = new Request.Builder().url(REGISTRY_ENDPOINT + "/submit").post( RequestBody.create(MediaType.parse("application/json"), requestData.toString().getBytes())) .build(); Response response = httpClient.newCall(request).execute(); if (response != null) { String responseEntity = response.body().string(); try { checkAuthorized(responseEntity); return new JsonObject(responseEntity); } catch (DecodeException ignored) { getFormattedError("Decode Exception", "There was an issue decoding the response."); } } } catch (IOException ignored) { } return null; }
From source file:com.github.kskelm.baringo.ImageService.java
License:Open Source License
/** * Upload an image to Imgur by pointing at a Url on the internet. * Must be available openly without authentication. * <p>/*from ww w . j ava2s . c o m*/ * <b>ACCESS: ANONYMOUS</b> or <b>AUTHENTICATED USER</b> * @param Url the full URL of the image. * @param fileName original of the file being uploaded (pick something) * @param albumId the name of the album, the album's deleteHash if it's anonymous, or null if none * @param title title of image or null if none * @param description description of image or null if none * @return The new Image object. If this is anonymous, <i>hang on to the delete hash</i> or you won't be able to manipulate it in the future! * @throws BaringoApiException something terrible happened to Stuart! */ public Image uploadUrlImage(String Url, String fileName, String albumId, String title, String description) throws BaringoApiException { RequestBody body = RequestBody.create(MediaType.parse("text/plain"), Url); Call<ImgurResponseWrapper<Image>> call = client.getApi().uploadUrlImage(albumId, "URL", title, description, body); try { Response<ImgurResponseWrapper<Image>> res = call.execute(); ImgurResponseWrapper<Image> out = res.body(); client.throwOnWrapperError(res); return out.getData(); } catch (IOException e) { throw new BaringoApiException(e.getMessage()); } // try-catch }
From source file:com.github.kskelm.baringo.ImageService.java
License:Open Source License
/** * Upload an image to Imgur as a stream from the local filesystem. * Use a buffered stream wherever possible! * <p>//from ww w. j a v a2 s. c o m * <b>ACCESS: ANONYMOUS</b> or <b>AUTHENTICATED USER</b> * @param mimeType mime type like image/png. If null, Baringo will try to infer this from the fileName. * @param fileName name of the file being uploaded * @param albumId the name of the album, the album's deleteHash if it's anonymous, or null if none * @param title title of image or null if none * @param description description of image or null if none * @return The new Image object. If this is anonymous, <i>hang on to the delete hash</i> or you won't be able to manipulate it in the future! * @throws IOException Something was wrong with the file or streaming didn't work * @throws BaringoApiException que sera sera */ public Image uploadLocalImage(String mimeType, String fileName, String albumId, String title, String description) throws IOException, BaringoApiException { // can be null File file = new File(fileName); if (!file.exists()) { throw new FileNotFoundException("File not found: " + fileName); } // if if (!file.canRead()) { throw new IOException("Cannot access file " + fileName); } // if if (mimeType == null) { // infer from file prefix int dotAt = fileName.lastIndexOf('.'); if (dotAt == -1) { throw new BaringoApiException("Could not infer mime type" + " from file name; no extension"); } // if String ext = fileName.substring(dotAt + 1).toLowerCase(); mimeType = extensionToMimeType.get(ext); if (mimeType == null) { throw new BaringoApiException("Could not infer mime type" + " from extension '" + ext + "'"); } // if } // if // strip the directory hierarchy off the filename. Path path = Paths.get(fileName); fileName = path.getFileName().toString(); RequestBody body = RequestBody.create(MediaType.parse(mimeType), file); Call<ImgurResponseWrapper<Image>> call = client.getApi().uploadLocalImage(albumId, "file", title, description, fileName, body); try { Response<ImgurResponseWrapper<Image>> res = call.execute(); ImgurResponseWrapper<Image> out = res.body(); client.throwOnWrapperError(res); return out.getData(); } catch (IOException e) { throw new BaringoApiException(e.getMessage()); } // try-catch }
From source file:com.github.leonardoxh.temporeal.app.service.AbstractService.java
License:Apache License
/** * Este metodo vai fazer as requisicoes HTTP para nos * enviando o modelo se necessario/*from w ww . j av a2 s. co m*/ * @param endPoint a URL da requisicao * @param model o modelo para enviar note que se este modelo for null iremos fazer um GET * por que temos um padrao no servidor :) * @param <T> o tipo do modelo (qualquer um que derive de Model) * @return a resposta da URL ou null em caso de falha */ protected <T extends Model> Response makeRequest(String endPoint, T model) { try { Request.Builder requestBuilder = new Request.Builder(); requestBuilder.url(endPoint); if (model == null) { requestBuilder.get(); } else { requestBuilder.post(RequestBody.create(Constants.JSON_MEDIA_TYPE, JsonUtils.toJson(model))); } return mClient.newCall(requestBuilder.build()).execute(); } catch (IOException e) { /* Essa exception sera lancada caso uma falha na * comunicacao aconteca, entao iremos retornar null */ e.printStackTrace(); } return null; }
From source file:com.github.leonardoxh.temporeal.model.listeners.PushSender.java
License:Apache License
public static void send(String entity) { Request.Builder requestBuilder = new Request.Builder(); requestBuilder.url(ApplicationConfiguration.PUSH_SERVICE_URL); requestBuilder/*from ww w. j av a2 s .c o m*/ .post(RequestBody.create(MediaType.parse("application/json"), getJsonOfRegistrationsId(entity))); requestBuilder.header("Authorization", ApplicationConfiguration.GCM_PROJECT_ID); OkHttpClient okHttp = new OkHttpClient(); try { Response response = okHttp.newCall(requestBuilder.build()).execute(); System.out.println("Response code: " + response.code()); } catch (IOException e) { e.printStackTrace(); } }
From source file:com.google.android.exoplayer.ext.okhttp.OkHttpDataSource.java
License:Apache License
/** * Establishes a connection./*ww w . ja v a 2 s . c om*/ */ private Request makeRequest(DataSpec dataSpec) { long position = dataSpec.position; long length = dataSpec.length; boolean allowGzip = (dataSpec.flags & DataSpec.FLAG_ALLOW_GZIP) != 0; HttpUrl url = HttpUrl.parse(dataSpec.uri.toString()); Request.Builder builder = new Request.Builder().url(url); if (cacheControl != null) { builder.cacheControl(cacheControl); } synchronized (requestProperties) { for (Map.Entry<String, String> property : requestProperties.entrySet()) { builder.addHeader(property.getKey(), property.getValue()); } } if (!(position == 0 && length == C.LENGTH_UNBOUNDED)) { String rangeRequest = "bytes=" + position + "-"; if (length != C.LENGTH_UNBOUNDED) { rangeRequest += (position + length - 1); } builder.addHeader("Range", rangeRequest); } builder.addHeader("User-Agent", userAgent); if (!allowGzip) { builder.addHeader("Accept-Encoding", "identity"); } if (dataSpec.postBody != null) { builder.post(RequestBody.create(null, dataSpec.postBody)); } return builder.build(); }
From source file:com.google.caliper.runner.resultprocessor.OkHttpUploadHandler.java
License:Apache License
@Override public boolean upload(URI uri, String content, String mediaType, Optional<UUID> apiKey, Trial trial) { HttpUrl url = HttpUrl.get(uri);// w ww . java 2s . c om if (apiKey.isPresent()) { url = url.newBuilder().addQueryParameter("key", apiKey.get().toString()).build(); } RequestBody body = RequestBody.create(MediaType.parse(mediaType), content); Request request = new Request.Builder().url(url).post(body).build(); try { Response response = client.newCall(request).execute(); if (response.isSuccessful()) { return true; } else { ResultsUploader.logger.fine("Failed upload response: " + response.code()); } } catch (IOException e) { ResultsUploader.logUploadFailure(trial, e); } return false; }