List of usage examples for com.squareup.okhttp MediaType parse
public static MediaType parse(String string)
From source file:org.getlantern.firetweet.extension.streaming.util.OkHttpClientImpl.java
License:Open Source License
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)); }// w ww . j a v a 2 s. c om 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(); }
From source file:org.graylog2.radio.cluster.InputService.java
License:Open Source License
public RegisterInputResponse registerInCluster(MessageInput input) throws ExecutionException, InterruptedException, IOException { final URI uri = UriBuilder.fromUri(serverUrl).path("/system/radios/{radioId}/inputs") .build(nodeId.toString());/*from www. ja v a2s . c o m*/ final RegisterInputRequest rir = RegisterInputRequest.create(input.getId(), input.getTitle(), input.getType(), input.getConfiguration().getSource(), nodeId.toString(), input.getCreatorUserId()); final Request request = new Request.Builder() .post(RequestBody.create(MediaType.parse(APPLICATION_JSON), mapper.writeValueAsBytes(rir))) .url(uri.toString()).build(); final Response r = httpclient.newCall(request).execute(); final RegisterInputResponse registerInputResponse = mapper.readValue(r.body().byteStream(), RegisterInputResponse.class); // Set the ID that was generated in the server as persist ID of this input. input.setPersistId(registerInputResponse.persistId()); if (!r.isSuccessful()) { throw new RuntimeException( "Expected HTTP response [2xx] for input registration but got [" + r.code() + "]."); } return registerInputResponse; }
From source file:org.jboss.arquillian.ce.proxy.AbstractProxy.java
License:Open Source License
public <T> T post(String url, Class<T> returnType, Object requestObject) throws Exception { final OkHttpClient httpClient = getHttpClient(); Request.Builder builder = new Request.Builder(); builder.url(url);/*from ww w . jav a 2 s. c om*/ if (requestObject != null) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try (ObjectOutputStream oos = new ObjectOutputStream(baos)) { oos.writeObject(requestObject); oos.flush(); } catch (Exception e) { throw new RuntimeException("Error sending request Object, " + requestObject, e); } RequestBody body = RequestBody.create(MediaType.parse("application/octet-stream"), baos.toByteArray()); builder.post(body); } Request request = builder.build(); Response response = httpClient.newCall(request).execute(); int responseCode = response.code(); if (responseCode == HttpURLConnection.HTTP_OK) { Object o; try (ObjectInputStream ois = new ObjectInputStream(response.body().byteStream())) { o = ois.readObject(); } if (returnType.isInstance(o) == false) { throw new IllegalStateException( "Error reading results, expected a " + returnType.getName() + " but got " + o); } return returnType.cast(o); } else if (responseCode == HttpURLConnection.HTTP_NO_CONTENT) { return null; } else if (responseCode != HttpURLConnection.HTTP_NOT_FOUND) { throw new IllegalStateException( "Error launching test at " + url + ". Got " + responseCode + " (" + response.message() + ")"); } return null; // TODO }
From source file:org.kegbot.api.KegbotApiImpl.java
License:Open Source License
private static RequestBody formBody(Map<String, String> params) { return RequestBody.create(MediaType.parse("application/x-www-form-urlencoded"), getUrlParamsString(params).getBytes()); }
From source file:org.kegbot.api.KegbotApiImpl.java
License:Open Source License
/** Builds a multi-part form body. */ private static RequestBody formBody(Map<String, String> params, Map<String, File> files) throws KegbotApiException { final String boundary = getBoundary(); final byte[] boundaryBytes = boundary.getBytes(); final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final byte[] outputBytes; try {// w w w .jav a 2 s.c om // Form data. for (final Map.Entry<String, String> param : params.entrySet()) { bos.write(HYPHENS); bos.write(boundaryBytes); bos.write(CRLF); bos.write(String.format("Content-Disposition: form-data; name=\"%s\"", param.getKey()).getBytes()); bos.write(CRLF); bos.write(CRLF); bos.write(param.getValue().getBytes()); bos.write(CRLF); } // Files for (final Map.Entry<String, File> entry : files.entrySet()) { final String entityName = entry.getKey(); final File file = entry.getValue(); bos.write(HYPHENS); bos.write(boundaryBytes); bos.write(CRLF); bos.write(String.format("Content-Disposition: form-data; name=\"%s\"; filename=\"%s\"", entityName, file.getName()).getBytes()); bos.write(CRLF); bos.write(CRLF); final FileInputStream fis = new FileInputStream(file); try { ByteStreams.copy(fis, bos); } finally { fis.close(); } bos.write(CRLF); } bos.write(HYPHENS); bos.write(boundaryBytes); bos.write(HYPHENS); bos.write(CRLF); bos.flush(); outputBytes = bos.toByteArray(); } catch (IOException e) { throw new KegbotApiException(e); } return RequestBody.create(MediaType.parse("multipart/form-data;boundary=" + boundary), outputBytes); }
From source file:org.opensilk.music.library.drive.transport.OkLowLevelHttpRequest.java
License:Open Source License
@Override public LowLevelHttpResponse execute() throws IOException { if (getStreamingContent() != null) { String contentType = getContentType(); String contentEncoding = getContentEncoding(); if (contentEncoding != null) { addHeader("Content-Encoding", contentEncoding); }/*from ww w . j a v a 2s. c om*/ long contentLength = getContentLength(); //TODO handle upload properly ByteArrayOutputStream out = new ByteArrayOutputStream(contentLength > 0 ? (int) contentLength : 1024); try { getStreamingContent().writeTo(out); MediaType mediaType = MediaType.parse(contentType); RequestBody body = RequestBody.create(mediaType, out.toByteArray()); builder.method(method, body); } finally { out.close(); } } else { builder.method(method, null); } Response response = okClient.newCall(builder.build()).execute(); return new OkLowLevelHttpResponse(response); }
From source file:org.quantumbadger.redreader.http.okhttp.OKHTTPBackend.java
License:Open Source License
@Override public Request prepareRequest(final Context context, final RequestDetails details) { final com.squareup.okhttp.Request.Builder builder = new com.squareup.okhttp.Request.Builder(); builder.header("User-Agent", Constants.ua(context)); final List<PostField> postFields = details.getPostFields(); if (postFields != null) { builder.post(RequestBody.create(MediaType.parse("application/x-www-form-urlencoded"), PostField.encodeList(postFields))); } else {//from www.j a v a2 s. c o m builder.get(); } builder.url(details.getUrl().toString()); builder.cacheControl(CacheControl.FORCE_NETWORK); final AtomicReference<Call> callRef = new AtomicReference<>(); return new Request() { public void executeInThisThread(final Listener listener) { final Call call = mClient.newCall(builder.build()); callRef.set(call); try { final Response response; try { response = call.execute(); } catch (IOException e) { listener.onError(CacheRequest.REQUEST_FAILURE_CONNECTION, e, null); return; } final int status = response.code(); if (status == 200 || status == 202) { final ResponseBody body = response.body(); final InputStream bodyStream; final Long bodyBytes; if (body != null) { bodyStream = body.byteStream(); bodyBytes = body.contentLength(); } else { // TODO error bodyStream = null; bodyBytes = null; } final String contentType = response.header("Content-Type"); listener.onSuccess(contentType, bodyBytes, bodyStream); } else { listener.onError(CacheRequest.REQUEST_FAILURE_REQUEST, null, status); } } catch (Throwable t) { listener.onError(CacheRequest.REQUEST_FAILURE_CONNECTION, t, null); } } @Override public void cancel() { final Call call = callRef.getAndSet(null); if (call != null) { call.cancel(); } } @Override public void addHeader(final String name, final String value) { builder.addHeader(name, value); } }; }
From source file:org.sonarqube.ws.client.HttpConnector.java
License:Open Source License
private WsResponse post(PostRequest postRequest) { HttpUrl.Builder urlBuilder = prepareUrlBuilder(postRequest); Request.Builder okRequestBuilder = prepareOkRequestBuilder(postRequest, urlBuilder); Map<String, PostRequest.Part> parts = postRequest.getParts(); if (parts.isEmpty()) { okRequestBuilder.post(RequestBody.create(null, "")); } else {/* ww w.j av a 2s.c o m*/ MultipartBuilder body = new MultipartBuilder().type(MultipartBuilder.FORM); for (Map.Entry<String, PostRequest.Part> param : parts.entrySet()) { PostRequest.Part part = param.getValue(); body.addPart(Headers.of("Content-Disposition", format("form-data; name=\"%s\"", param.getKey())), RequestBody.create(MediaType.parse(part.getMediaType()), part.getFile())); } okRequestBuilder.post(body.build()); } return doCall(okRequestBuilder.build()); }
From source file:org.sufficientlysecure.keychain.keyimport.HkpKeyserver.java
License:Apache License
@Override public void add(String armoredKey) throws AddKeyException { try {// w w w. j a v a 2 s. c om String path = "/pks/add"; String params; try { params = "keytext=" + URLEncoder.encode(armoredKey, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new AddKeyException(); } URL url = new URL(getUrlPrefix() + mHost + ":" + mPort + path); Log.d(Constants.TAG, "hkp keyserver add: " + url); Log.d(Constants.TAG, "params: " + params); RequestBody body = RequestBody.create(MediaType.parse("application/x-www-form-urlencoded"), params); Request request = new Request.Builder().url(url) .addHeader("Content-Type", "application/x-www-form-urlencoded") .addHeader("Content-Length", Integer.toString(params.getBytes().length)).post(body).build(); Response response = getClient(url, mProxy).newCall(request).execute(); Log.d(Constants.TAG, "response code: " + response.code()); Log.d(Constants.TAG, "answer: " + response.body().string()); if (response.code() != 200) { throw new AddKeyException(); } } catch (IOException e) { Log.e(Constants.TAG, "IOException", e); throw new AddKeyException(); } }
From source file:org.whispersystems.signalservice.internal.push.PushServiceSocket.java
private Response getConnection(String urlFragment, String method, String body) throws PushNetworkException { try {/*w ww. j a v a 2 s .c o m*/ Log.w(TAG, "Push service URL: " + serviceUrl); Log.w(TAG, "Opening URL: " + String.format("%s%s", serviceUrl, urlFragment)); SSLContext context = SSLContext.getInstance("TLS"); context.init(null, trustManagers, null); OkHttpClient okHttpClient = new OkHttpClient(); okHttpClient.setSslSocketFactory(context.getSocketFactory()); okHttpClient.setHostnameVerifier(new StrictHostnameVerifier()); Request.Builder request = new Request.Builder(); request.url(String.format("%s%s", serviceUrl, urlFragment)); if (body != null) { request.method(method, RequestBody.create(MediaType.parse("application/json"), body)); } else { request.method(method, null); } if (credentialsProvider.getPassword() != null) { request.addHeader("Authorization", getAuthorizationHeader()); } if (userAgent != null) { request.addHeader("X-Signal-Agent", userAgent); } return okHttpClient.newCall(request.build()).execute(); } catch (IOException e) { throw new PushNetworkException(e); } catch (NoSuchAlgorithmException | KeyManagementException e) { throw new AssertionError(e); } }