List of usage examples for com.squareup.okhttp MediaType parse
public static MediaType parse(String string)
From source file:BenchMarkTest.java
License:Open Source License
void doOkHttpRequest() { ++okhttp_task_cnt;// ww w. j a v a 2 s . c om try { OkHttpClient client = new OkHttpClient(); Main.HelloRequest req = new Main.HelloRequest(); req.user = "okhttp"; req.text = Integer.toString((int) okhttp_task_cnt); //Benchmark 64KB/128KB /*req.dumpContent = new byte[64*1024]; Random rand = new Random(); rand.nextBytes(req.dumpContent);*/ final byte[] flatArray = new byte[req.getSerializedSize()]; final CodedOutputByteBufferNano output = CodedOutputByteBufferNano.newInstance(flatArray); req.writeTo(output); RequestBody reqBody = RequestBody.create(MediaType.parse("application/octet-stream"), flatArray); //normal request Request request = new Request.Builder().url("http://118.89.24.72:8080/mars/hello2") .addHeader("Cache-Control", "no-cache").addHeader("Content-Type", "application/octet-stream") .addHeader("Connection", "close").addHeader("Accept", "*/*").post(reqBody).build(); okhttp_task_time = System.currentTimeMillis(); // Execute the request and retrieve the response. Response response = client.newCall(request).execute(); ResponseBody body = response.body(); Main.HelloResponse helloResp = Main.HelloResponse.parseFrom(body.bytes()); body.close(); long curr = System.currentTimeMillis(); okhttp_suc_time += curr - okhttp_task_time; ++okhttp_task_suc; //Log.i(TAG, "http type:" + type + ", suc cost:" + (curr - okhttp_task_time) + ", count:" + okhttp_task_cnt + ", suc count:" + okhttp_task_suc + ", ctn:" + helloResp.errmsg); } catch (Exception e) { Log.e(TAG, "http fail cost:" + (System.currentTimeMillis() - okhttp_task_time) + ", count:" + okhttp_task_cnt); } }
From source file:abtlibrary.utils.as24ApiClient.ApiClient.java
License:Apache License
/** * Serialize the given Java object into request body according to the object's * class and the request Content-Type./*w ww .j a va 2 s . co m*/ * * @param obj The Java object * @param contentType The request Content-Type * @return The serialized request body * @throws ApiException If fail to serialize the given object */ public RequestBody serialize(Object obj, String contentType) throws ApiException { if (obj instanceof byte[]) { // Binary (byte array) body parameter support. return RequestBody.create(MediaType.parse(contentType), (byte[]) obj); } else if (obj instanceof File) { // File body parameter support. return RequestBody.create(MediaType.parse(contentType), (File) obj); } else if (isJsonMime(contentType)) { String content; if (obj != null) { content = json.serialize(obj); } else { content = null; } return RequestBody.create(MediaType.parse(contentType), content); } else { throw new ApiException("Content type \"" + contentType + "\" is not supported"); } }
From source file:abtlibrary.utils.as24ApiClient.ApiClient.java
License:Apache License
/** * Build HTTP call with the given options. * * @param path The sub-path of the HTTP URL * @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE" * @param queryParams The query parameters * @param body The request body object/*from w w w . j a va 2 s .c o m*/ * @param headerParams The header parameters * @param formParams The form parameters * @param authNames The authentications to apply * @param progressRequestListener Progress request listener * @return The HTTP call * @throws ApiException If fail to serialize the request body object */ public Call buildCall(String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, Object> formParams, String[] authNames, ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { updateParamsForAuth(authNames, queryParams, headerParams); final String url = buildUrl(path, queryParams); final Request.Builder reqBuilder = new Request.Builder().url(url); processHeaderParams(headerParams, reqBuilder); String contentType = (String) headerParams.get("Content-Type"); // ensuring a default content type if (contentType == null) { contentType = "application/json"; } RequestBody reqBody; if (!HttpMethod.permitsRequestBody(method)) { reqBody = null; } else if ("application/x-www-form-urlencoded".equals(contentType)) { reqBody = buildRequestBodyFormEncoding(formParams); } else if ("multipart/form-data".equals(contentType)) { reqBody = buildRequestBodyMultipart(formParams); } else if (body == null) { if ("DELETE".equals(method)) { // allow calling DELETE without sending a request body reqBody = null; } else { // use an empty request body (for POST, PUT and PATCH) reqBody = RequestBody.create(MediaType.parse(contentType), ""); } } else { reqBody = serialize(body, contentType); } Request request = null; if (progressRequestListener != null && reqBody != null) { ProgressRequestBody progressRequestBody = new ProgressRequestBody(reqBody, progressRequestListener); request = reqBuilder.method(method, progressRequestBody).build(); } else { request = reqBuilder.method(method, reqBody).build(); } return httpClient.newCall(request); }
From source file:abtlibrary.utils.as24ApiClient.ApiClient.java
License:Apache License
/** * Build a multipart (file uploading) request body with the given form parameters, * which could contain text fields and file fields. * * @param formParams Form parameters in the form of Map * @return RequestBody// w w w .j av a 2 s. com */ public RequestBody buildRequestBodyMultipart(Map<String, Object> formParams) { MultipartBuilder mpBuilder = new MultipartBuilder().type(MultipartBuilder.FORM); for (Entry<String, Object> param : formParams.entrySet()) { if (param.getValue() instanceof File) { File file = (File) param.getValue(); Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + param.getKey() + "\"; filename=\"" + file.getName() + "\""); MediaType mediaType = MediaType.parse(guessContentTypeFromFile(file)); mpBuilder.addPart(partHeaders, RequestBody.create(mediaType, file)); } else { Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + param.getKey() + "\""); mpBuilder.addPart(partHeaders, RequestBody.create(null, parameterToString(param.getValue()))); } } return mpBuilder.build(); }
From source file:alfio.manager.system.MailgunMailer.java
License:Open Source License
private RequestBody prepareBody(Event event, String to, String subject, String text, Optional<String> html, Attachment... attachments) throws IOException { String from = event.getDisplayName() + " <" + configurationManager .getRequiredValue(Configuration.from(event.getOrganizationId(), event.getId(), MAILGUN_FROM)) + ">"; if (ArrayUtils.isEmpty(attachments)) { FormEncodingBuilder builder = new FormEncodingBuilder().add("from", from).add("to", to) .add("subject", subject).add("text", text); String replyTo = configurationManager.getStringConfigValue( Configuration.from(event.getOrganizationId(), event.getId(), MAIL_REPLY_TO), ""); if (StringUtils.isNotBlank(replyTo)) { builder.add("h:Reply-To", replyTo); }/*w ww .java 2 s . c om*/ html.ifPresent((htmlContent) -> builder.add("html", htmlContent)); return builder.build(); } else { // https://github.com/square/okhttp/blob/parent-2.1.0/samples/guide/src/main/java/com/squareup/okhttp/recipes/PostMultipart.java MultipartBuilder multipartBuilder = new MultipartBuilder().type(MultipartBuilder.FORM); multipartBuilder.addFormDataPart("from", from).addFormDataPart("to", to) .addFormDataPart("subject", subject).addFormDataPart("text", text); html.ifPresent((htmlContent) -> multipartBuilder.addFormDataPart("html", htmlContent)); for (Attachment attachment : attachments) { byte[] data = attachment.getSource(); multipartBuilder.addFormDataPart("attachment", attachment.getFilename(), RequestBody .create(MediaType.parse(attachment.getContentType()), Arrays.copyOf(data, data.length))); } return multipartBuilder.build(); } }
From source file:alfio.manager.system.MailjetMailer.java
License:Open Source License
@Override public void send(Event event, String to, String subject, String text, Optional<String> html, Attachment... attachment) {/* w w w . ja v a 2 s. com*/ String apiKeyPublic = configurationManager.getRequiredValue(Configuration.from(event.getOrganizationId(), event.getId(), ConfigurationKeys.MAILJET_APIKEY_PUBLIC)); String apiKeyPrivate = configurationManager.getRequiredValue(Configuration.from(event.getOrganizationId(), event.getId(), ConfigurationKeys.MAILJET_APIKEY_PRIVATE)); String fromEmail = configurationManager.getRequiredValue( Configuration.from(event.getOrganizationId(), event.getId(), ConfigurationKeys.MAILJET_FROM)); //https://dev.mailjet.com/guides/?shell#sending-with-attached-files Map<String, Object> mailPayload = new HashMap<>(); mailPayload.put("FromEmail", fromEmail); mailPayload.put("FromName", event.getDisplayName()); mailPayload.put("Subject", subject); mailPayload.put("Text-part", text); html.ifPresent(h -> mailPayload.put("Html-part", h)); mailPayload.put("Recipients", Collections.singletonList(Collections.singletonMap("Email", to))); String replyTo = configurationManager.getStringConfigValue( Configuration.from(event.getOrganizationId(), event.getId(), ConfigurationKeys.MAIL_REPLY_TO), ""); if (StringUtils.isNotBlank(replyTo)) { mailPayload.put("Headers", Collections.singletonMap("Reply-To", replyTo)); } if (attachment != null && attachment.length > 0) { mailPayload.put("Attachments", Arrays.stream(attachment).map(MailjetMailer::fromAttachment).collect(Collectors.toList())); } try { RequestBody body = RequestBody.create(MediaType.parse("application/json"), Json.GSON.toJson(mailPayload)); Request request = new Request.Builder().url("https://api.mailjet.com/v3/send") .header("Authorization", Credentials.basic(apiKeyPublic, apiKeyPrivate)).post(body).build(); Response resp = client.newCall(request).execute(); if (!resp.isSuccessful()) { log.warn("sending email was not successful:" + resp); } } catch (IOException e) { log.warn("error while sending email", e); } }
From source file:alfio.plugin.mailchimp.MailChimpPlugin.java
License:Open Source License
private boolean send(int eventId, String address, String apiKey, String email, CustomerName name, String language, String eventKey) { Map<String, Object> content = new HashMap<>(); content.put("email_address", email); content.put("status", "subscribed"); Map<String, String> mergeFields = new HashMap<>(); mergeFields.put("FNAME", name.isHasFirstAndLastName() ? name.getFirstName() : name.getFullName()); mergeFields.put(ALFIO_EVENT_KEY, eventKey); content.put("merge_fields", mergeFields); content.put("language", language); Request request = new Request.Builder().url(address) .header("Authorization", Credentials.basic("alfio", apiKey)) .put(RequestBody.create(MediaType.parse(APPLICATION_JSON), Json.GSON.toJson(content, Map.class))) .build();//w w w .j a v a 2 s.co m try { Response response = httpClient.newCall(request).execute(); if (response.isSuccessful()) { pluginDataStorage.registerSuccess(String.format("user %s has been subscribed to list", email), eventId); return true; } String responseBody = response.body().string(); if (response.code() != 400 || responseBody.contains("\"errors\"")) { pluginDataStorage.registerFailure(String.format(FAILURE_MSG, email, name, language, responseBody), eventId); return false; } else { pluginDataStorage.registerWarning(String.format(FAILURE_MSG, email, name, language, responseBody), eventId); } return true; } catch (IOException e) { pluginDataStorage.registerFailure(String.format(FAILURE_MSG, email, name, language, e.toString()), eventId); return false; } }
From source file:alfio.plugin.mailchimp.MailChimpPlugin.java
License:Open Source License
private void createMergeField(String listAddress, String apiKey, String eventKey, int eventId) { Map<String, Object> mergeField = new HashMap<>(); mergeField.put("tag", ALFIO_EVENT_KEY); mergeField.put("name", "Alfio's event key"); mergeField.put("type", "text"); mergeField.put("required", false); mergeField.put("public", false); Request request = new Request.Builder().url(listAddress + MERGE_FIELDS) .header("Authorization", Credentials.basic("alfio", apiKey)).post(RequestBody .create(MediaType.parse(APPLICATION_JSON), Json.GSON.toJson(mergeField, Map.class))) .build();//from www. j av a2 s. com try { Response response = httpClient.newCall(request).execute(); if (!response.isSuccessful()) { log.debug("can't create {} merge field. Got: {}", ALFIO_EVENT_KEY, response.body().string()); } } catch (IOException e) { pluginDataStorage.registerFailure( String.format("Cannot create merge field for %s, got: %s", eventKey, e.getMessage()), eventId); log.warn("exception while creating ALFIO_EKEY for event id " + eventId, e); } }
From source file:at.bitfire.dav4android.BasicDigestAuthenticatorTest.java
License:Open Source License
public void testMD5Sess() { BasicDigestAuthenticator authenticator = new BasicDigestAuthenticator(null, "admin", "12345", "hxk1lu63b6c7vhk"); HttpUtils.AuthScheme authScheme = new HttpUtils.AuthScheme("Digest"); authScheme.params.put("realm", "MD5-sess Example"); authScheme.params.put("qop", "auth"); authScheme.params.put("algorithm", "MD5-sess"); authScheme.params.put("nonce", "dcd98b7102dd2f0e8b11d0f600bfb0c093"); authScheme.params.put("opaque", "5ccc069c403ebaf9f0171e9517f40e41"); /* A1 = h("admin:MD5-sess Example:12345"):dcd98b7102dd2f0e8b11d0f600bfb0c093:hxk1lu63b6c7vhk = 4eaed818bc587129e73b39c8d3e8425a:dcd98b7102dd2f0e8b11d0f600bfb0c093:hxk1lu63b6c7vhk a994ee9d33e2f077d3a6e13e882f6686 A2 = POST:/plain.txt 1b557703454e1aa1230c5523f54380ed //from w w w . j av a 2 s. com h("a994ee9d33e2f077d3a6e13e882f6686:dcd98b7102dd2f0e8b11d0f600bfb0c093:00000001:hxk1lu63b6c7vhk:auth:1b557703454e1aa1230c5523f54380ed") = af2a72145775cfd08c36ad2676e89446 */ Request original = new Request.Builder() .method("POST", RequestBody.create(MediaType.parse("text/plain"), "PLAIN TEXT")) .url("http://example.com/plain.txt").build(); Request request = authenticator.authorizationRequest(original, authScheme); String auth = request.header("Authorization"); assertTrue(auth.contains("username=\"admin\"")); assertTrue(auth.contains("realm=\"MD5-sess Example\"")); assertTrue(auth.contains("nonce=\"dcd98b7102dd2f0e8b11d0f600bfb0c093\"")); assertTrue(auth.contains("uri=\"/plain.txt\"")); assertTrue(auth.contains("cnonce=\"hxk1lu63b6c7vhk\"")); assertTrue(auth.contains("nc=00000001")); assertTrue(auth.contains("qop=auth")); assertTrue(auth.contains("response=\"af2a72145775cfd08c36ad2676e89446\"")); assertTrue(auth.contains("opaque=\"5ccc069c403ebaf9f0171e9517f40e41\"")); }
From source file:at.bitfire.dav4android.BasicDigestAuthenticatorTest.java
License:Open Source License
public void testMD5AuthInt() { BasicDigestAuthenticator authenticator = new BasicDigestAuthenticator(null, "admin", "12435", "hxk1lu63b6c7vhk"); HttpUtils.AuthScheme authScheme = new HttpUtils.AuthScheme("Digest"); authScheme.params.put("realm", "AuthInt Example"); authScheme.params.put("qop", "auth-int"); authScheme.params.put("nonce", "367sj3265s5"); authScheme.params.put("opaque", "87aaxcval4gba36"); /* A1 = admin:AuthInt Example:12345 380dc3fc1305127cd2aa81ab68ef3f34 /*from w w w. j a v a 2 s.c om*/ h("PLAIN TEXT") = 20296edbd4c4275fb416b64e4be752f9 A2 = POST:/plain.txt:20296edbd4c4275fb416b64e4be752f9 a71c4c86e18b3993ffc98c6e426fe4b0 h(380dc3fc1305127cd2aa81ab68ef3f34:367sj3265s5:00000001:hxk1lu63b6c7vhk:auth-int:a71c4c86e18b3993ffc98c6e426fe4b0) = 81d07cb3b8d412b34144164124c970cb */ Request original = new Request.Builder() .method("POST", RequestBody.create(MediaType.parse("text/plain"), "PLAIN TEXT")) .url("http://example.com/plain.txt").build(); Request request = authenticator.authorizationRequest(original, authScheme); String auth = request.header("Authorization"); assertTrue(auth.contains("username=\"admin\"")); assertTrue(auth.contains("realm=\"AuthInt Example\"")); assertTrue(auth.contains("nonce=\"367sj3265s5\"")); assertTrue(auth.contains("uri=\"/plain.txt\"")); assertTrue(auth.contains("cnonce=\"hxk1lu63b6c7vhk\"")); assertTrue(auth.contains("nc=00000001")); assertTrue(auth.contains("qop=auth-int")); assertTrue(auth.contains("response=\"5ab6822b9d906cc711760a7783b28dca\"")); assertTrue(auth.contains("opaque=\"87aaxcval4gba36\"")); }