List of usage examples for com.squareup.okhttp RequestBody create
public static RequestBody create(final MediaType contentType, final File file)
From source file:org.apache.hadoop.hdfs.web.oauth2.CredentialBasedAccessTokenProvider.java
License:Apache License
void refresh() throws IOException { try {//from w w w . j a v a 2 s . c o m OkHttpClient client = new OkHttpClient(); client.setConnectTimeout(URLConnectionFactory.DEFAULT_SOCKET_TIMEOUT, TimeUnit.MILLISECONDS); client.setReadTimeout(URLConnectionFactory.DEFAULT_SOCKET_TIMEOUT, TimeUnit.MILLISECONDS); String bodyString = Utils.postBody(CLIENT_SECRET, getCredential(), GRANT_TYPE, CLIENT_CREDENTIALS, CLIENT_ID, clientId); RequestBody body = RequestBody.create(URLENCODED, bodyString); Request request = new Request.Builder().url(refreshURL).post(body).build(); Response responseBody = client.newCall(request).execute(); if (responseBody.code() != HttpStatus.SC_OK) { throw new IllegalArgumentException("Received invalid http response: " + responseBody.code() + ", text = " + responseBody.toString()); } Map<?, ?> response = READER.readValue(responseBody.body().string()); String newExpiresIn = response.get(EXPIRES_IN).toString(); timer.setExpiresIn(newExpiresIn); accessToken = response.get(ACCESS_TOKEN).toString(); } catch (Exception e) { throw new IOException("Unable to obtain access token from credential", e); } }
From source file:org.apache.ignite.stream.camel.IgniteCamelStreamerTest.java
License:Apache License
/** * @throws IOException/* w ww .j ava2 s . c om*/ * @return HTTP response payloads. */ private List<String> sendMessages(int fromIdx, int cnt, boolean singleMessage) throws IOException { List<String> responses = Lists.newArrayList(); if (singleMessage) { StringBuilder sb = new StringBuilder(); for (int i = fromIdx; i < fromIdx + cnt; i++) sb.append(i).append(",").append(TEST_DATA.get(i)).append("\n"); Request request = new Request.Builder().url(url).post(RequestBody.create(TEXT_PLAIN, sb.toString())) .build(); Response response = httpClient.newCall(request).execute(); responses.add(response.body().string()); } else { for (int i = fromIdx; i < fromIdx + cnt; i++) { String payload = i + "," + TEST_DATA.get(i); Request request = new Request.Builder().url(url).post(RequestBody.create(TEXT_PLAIN, payload)) .build(); Response response = httpClient.newCall(request).execute(); responses.add(response.body().string()); } } return responses; }
From source file:org.apache.nifi.processors.att.m2x.PutM2XStream.java
License:Apache License
@Override public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException { final FlowFile flowFile = session.get(); if (flowFile == null) { return;//w w w.j a v a 2s. co m } final ProcessorLog logger = getLogger(); final OkHttpClient httpClient = getHttpClient(); final StateManager stateManager = context.getStateManager(); final String apiKey = context.getProperty(M2X_API_KEY).getValue(); final String apiUrl = context.getProperty(M2X_API_URL).getValue(); final String deviceId = context.getProperty(M2X_DEVICE_ID).getValue(); final String streamName = context.getProperty(M2X_STREAM_NAME).getValue(); final String streamType = context.getProperty(M2X_STREAM_TYPE).getValue(); final String streamUrl = new StringBuilder().append(apiUrl.replaceAll("/*$", "")).append("/devices/") .append(deviceId).append("/streams/").append(streamName).append("/value").toString(); try { final AtomicReference<String> postBodyRef = new AtomicReference<>(); session.read(flowFile, new InputStreamCallback() { @Override public void process(InputStream is) { try { String timestamp = flowFile.getAttribute("m2x.stream.value.timestamp"); if (StringUtils.isEmpty(timestamp)) { timestamp = ISODateTimeFormat.dateTime().print(flowFile.getEntryDate()); } final String value = IOUtils.toString(is, StandardCharsets.UTF_8); final M2XStreamValue m2xValue = new M2XStreamValue(); m2xValue.setValue(value); m2xValue.setTimestamp(timestamp); final ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new JodaModule()); mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); final String postBody = mapper.writeValueAsString(m2xValue); logger.warn("POST body is {}", new Object[] { postBody }); postBodyRef.set(postBody); } catch (Exception e) { logger.error(e.getMessage(), e); } } }); final String postBody = postBodyRef.get(); if (StringUtils.isEmpty(postBody)) { logger.error("FlowFile {} contents didn't produce a valid M2X stream value", new Object[] { flowFile }); session.transfer(flowFile, REL_FAILURE); return; } final Request request = new Request.Builder().url(streamUrl).addHeader("X-M2X-KEY", apiKey) .put(RequestBody.create(MEDIA_TYPE_JSON, postBody)).build(); final Response response = httpClient.newCall(request).execute(); if (!response.isSuccessful()) { logger.error(response.message()); context.yield(); session.penalize(flowFile); return; } } catch (IOException e) { logger.error(e.getMessage(), e); context.yield(); session.penalize(flowFile); return; } session.transfer(flowFile, REL_SUCCESS); }
From source file:org.apache.nifi.processors.standard.InvokeHTTP.java
License:Apache License
private RequestBody getRequestBodyToSend(final ProcessSession session, final ProcessContext context, final FlowFile requestFlowFile) { if (context.getProperty(PROP_SEND_BODY).asBoolean()) { return new RequestBody() { @Override//from w ww . j a v a 2 s .c om public MediaType contentType() { String contentType = context.getProperty(PROP_CONTENT_TYPE) .evaluateAttributeExpressions(requestFlowFile).getValue(); contentType = StringUtils.isBlank(contentType) ? DEFAULT_CONTENT_TYPE : contentType; return MediaType.parse(contentType); } @Override public void writeTo(BufferedSink sink) throws IOException { session.exportTo(requestFlowFile, sink.outputStream()); } @Override public long contentLength() { return useChunked ? -1 : requestFlowFile.getSize(); } }; } else { return RequestBody.create(null, new byte[0]); } }
From source file:org.bitbucket.ddmytrenko.android.retrofit.converter.msgpack.MsgPackRequestBodyConverter.java
License:Open Source License
@Override public RequestBody convert(final T value) throws IOException { final ByteArrayOutputStream out = new ByteArrayOutputStream(); messagePack.createPacker(out).write(value); return RequestBody.create(MEDIA_TYPE, out.toByteArray()); }
From source file:org.catrobat.catroid.web.ServerCalls.java
License:Open Source License
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 {/*from ww w. ja va 2 s. c o m*/ 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"); } }
From source file:org.chromium.cronet_sample_apk.CronetSampleActivity.java
License:Open Source License
private void makeOKHttpRequest(String url, String postData) { Log.d(TAG, "okhttp request starts"); OKHttpFinishFlag = false;/*from www .jav a2 s. c om*/ if (postData.length() > 0) { Request request = new Request.Builder().url(url).build(); makeRequest(request); } else { RequestBody body = RequestBody.create(JSON, postData); Request request = new Request.Builder().url(url).post(body).build(); makeRequest(request); } }
From source file:org.eyeseetea.malariacare.network.NetworkUtils.java
License:Open Source License
/** * Pushes data to DHIS Server//from www .java2 s . c o m * @param data */ public JSONObject pushData(JSONObject data) throws Exception { Response response = null; final String DHIS_URL = getDhisURL() + DHIS_PUSH_API; OkHttpClient client = UnsafeOkHttpsClientFactory.getUnsafeOkHttpClient(); client.setConnectTimeout(30, TimeUnit.SECONDS); // connect timeout client.setReadTimeout(30, TimeUnit.SECONDS); // socket timeout client.setWriteTimeout(30, TimeUnit.SECONDS); // write timeout client.setRetryOnConnectionFailure(false); // Cancel retry on failure BasicAuthenticator basicAuthenticator = new BasicAuthenticator(); client.setAuthenticator(basicAuthenticator); Log.d(TAG, "Url" + DHIS_URL + ""); RequestBody body = RequestBody.create(JSON, data.toString()); Request request = new Request.Builder() .header(basicAuthenticator.AUTHORIZATION_HEADER, basicAuthenticator.getCredentials()).url(DHIS_URL) .post(body).build(); response = client.newCall(request).execute(); if (!response.isSuccessful()) { Log.e(TAG, "pushData (" + response.code() + "): " + response.body().string()); throw new IOException(response.message()); } return parseResponse(response.body().string()); }
From source file:org.eyeseetea.malariacare.network.NetworkUtils.java
License:Open Source License
/** * Call to DHIS Server// w ww. ja v a 2s. c o m * @param data * @param url */ public Response executeCall(JSONObject data, String url, String method) throws IOException { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(applicationContext); final String DHIS_URL = sharedPreferences.getString(applicationContext.getString(R.string.dhis_url), applicationContext.getString(R.string.login_info_dhis_default_server_url)) + url; OkHttpClient client = UnsafeOkHttpsClientFactory.getUnsafeOkHttpClient(); client.setConnectTimeout(30, TimeUnit.SECONDS); // connect timeout client.setReadTimeout(30, TimeUnit.SECONDS); // socket timeout client.setWriteTimeout(30, TimeUnit.SECONDS); // write timeout client.setRetryOnConnectionFailure(false); // Cancel retry on failure BasicAuthenticator basicAuthenticator = new BasicAuthenticator(); client.setAuthenticator(basicAuthenticator); Request.Builder builder = new Request.Builder() .header(basicAuthenticator.AUTHORIZATION_HEADER, basicAuthenticator.getCredentials()).url(DHIS_URL); switch (method) { case "POST": RequestBody postBody = RequestBody.create(JSON, data.toString()); builder.post(postBody); break; case "PUT": RequestBody putBody = RequestBody.create(JSON, data.toString()); builder.put(putBody); break; case "PATCH": RequestBody patchBody = RequestBody.create(JSON, data.toString()); builder.patch(patchBody); break; case "GET": builder.get(); break; } Request request = builder.build(); return client.newCall(request).execute(); }
From source file:org.eyeseetea.malariacare.network.PushClient.java
License:Open Source License
/** * Pushes data to DHIS Server//from w w w . j ava 2 s . co m * @param data */ private JSONObject pushData(JSONObject data) throws Exception { Response response = null; final String DHIS_URL = getDhisURL(); OkHttpClient client = UnsafeOkHttpsClientFactory.getUnsafeOkHttpClient(); BasicAuthenticator basicAuthenticator = new BasicAuthenticator(); client.setAuthenticator(basicAuthenticator); RequestBody body = RequestBody.create(JSON, data.toString()); Request request = new Request.Builder() .header(basicAuthenticator.AUTHORIZATION_HEADER, basicAuthenticator.getCredentials()).url(DHIS_URL) .post(body).build(); response = client.newCall(request).execute(); if (!response.isSuccessful()) { Log.e(TAG, "pushData (" + response.code() + "): " + response.body().string()); throw new IOException(response.message()); } return parseResponse(response.body().string()); }