Example usage for com.squareup.okhttp MediaType parse

List of usage examples for com.squareup.okhttp MediaType parse

Introduction

In this page you can find the example usage for com.squareup.okhttp MediaType parse.

Prototype

public static MediaType parse(String string) 

Source Link

Document

Returns a media type for string , or null if string is not a well-formed media type.

Usage

From source file:net.qiujuer.common.okhttp.impl.RequestCallBuilder.java

License:Apache License

@Override
public Request.Builder builderPost(String url, JSONArray jsonArray) {
    RequestBody body = RequestBody.create(
            MediaType.parse(String.format("application/json; charset=%s", mProtocolCharset)),
            jsonArray.toString());//w  w  w  .  ja va2  s.  c om

    return builderPost(url, body);
}

From source file:net.yatomiya.nicherry.services.bbs.PostMessageHandler.java

License:Open Source License

public Call execute(ThreadProcessor processor, boolean isSynchronous, String name, String mail, String body,
        Map<String, String> additionalParams) {
    this.processor = processor;
    this.isSynchronous = isSynchronous;
    this.name = name;
    this.mail = mail;
    this.body = body;

    executeTime = JUtils.getCurrentTime();

    EUtils.get(EventService.class).send(BBSService.Event.Post.START, getModel());

    BBSService bbsSrv = processor.getManager().getBBSService();
    BBSHttpClient client = bbsSrv.getHttpClient();

    ThreadId threadId = getModel().getId();
    MBoard board = bbsSrv.getBoard(threadId.getBoardId());
    String hostUrl = HttpUtils.getHostUrl(board.getUrl());
    String postUrl = hostUrl + "/test/bbs.cgi";

    Request.Builder builder = new Request.Builder();
    builder.url(postUrl);/* www.  j  a va  2 s .  c  o m*/

    Map<String, String> valueMap = new HashMap<>();
    valueMap.put("bbs", threadId.getBoardId().getIdValue());
    valueMap.put("key", threadId.getIdValue());
    valueMap.put("time", String.valueOf((JUtils.getCurrentTime() / 1000) - 60));
    valueMap.put("submit", "??");
    valueMap.put("FROM", name);
    valueMap.put("mail", mail);
    valueMap.put("MESSAGE", body);
    if (additionalParams != null)
        valueMap.putAll(additionalParams);
    String valueStr = HttpUtils.buildFormPostData(valueMap, NConstants.CHARSET_SHIFT_JIS);

    builder.post(RequestBody.create(MediaType.parse("application/x-www-form-urlencoded; charset=Shift_JIS"),
            StringUtils.getBytes(valueStr, NConstants.CHARSET_SHIFT_JIS)));

    builder.header("Referer", board.getUrl());

    Request request = builder.build();

    Callback callback = new Callback() {
        @Override
        public void onResponse(Response response) throws IOException {
            EUtils.asyncExec(() -> doOnResponse(response));
        }

        @Override
        public void onFailure(Request request, IOException e) {
            EUtils.asyncExec(() -> doOnFailure(request, e));
        }
    };
    httpCall = client.execute(request, callback, isSynchronous);

    postEvent = new PostMessageEvent(name, mail, body);

    return httpCall;
}

From source file:nextflow.ga4gh.tes.client.ApiClient.java

License:Apache License

/**
 * Build an HTTP request 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//  ww w .  j a v  a2 s  . co  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 request 
 * @throws ApiException If fail to serialize the request body object
 */
public Request buildRequest(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 request;
}

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 w  w  .  ja  v  a  2 s.  c o  m
            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.floens.chan.core.http.ReplyHttpCall.java

License:Open Source License

@Override
public void setup(Request.Builder requestBuilder) {
    boolean thread = reply.resto >= 0;

    password = Long.toHexString(RANDOM.nextLong());

    MultipartBuilder formBuilder = new MultipartBuilder();
    formBuilder.type(MultipartBuilder.FORM);

    formBuilder.addFormDataPart("mode", "regist");
    formBuilder.addFormDataPart("pwd", password);

    if (thread) {
        formBuilder.addFormDataPart("resto", String.valueOf(reply.resto));
    }//from  w w w .  j a va2  s  . co m

    formBuilder.addFormDataPart("name", reply.name);
    formBuilder.addFormDataPart("email", reply.options);

    if (!thread && !TextUtils.isEmpty(reply.subject)) {
        formBuilder.addFormDataPart("sub", reply.subject);
    }

    formBuilder.addFormDataPart("com", reply.comment);

    if (reply.captchaResponse != null) {
        if (reply.captchaChallenge != null) {
            formBuilder.addFormDataPart("recaptcha_challenge_field", reply.captchaChallenge);
            formBuilder.addFormDataPart("recaptcha_response_field", reply.captchaResponse);
        } else {
            formBuilder.addFormDataPart("g-recaptcha-response", reply.captchaResponse);
        }
    }

    if (reply.file != null) {
        formBuilder.addFormDataPart("upfile", reply.fileName,
                RequestBody.create(MediaType.parse("application/octet-stream"), reply.file));
    }

    if (reply.spoilerImage) {
        formBuilder.addFormDataPart("spoiler", "on");
    }

    requestBuilder.url(ChanUrls.getReplyUrl(reply.board));
    requestBuilder.post(formBuilder.build());

    if (reply.usePass) {
        requestBuilder.addHeader("Cookie", "pass_id=" + reply.passId);
    }
}

From source file:org.floens.chan.core.manager.ReplyManager.java

License:Open Source License

private void postReplyInternal(final Reply reply, final ReplyListener replyListener, String captchaHash) {
    reply.password = Long.toHexString(random.nextLong());

    MultipartBuilder formBuilder = new MultipartBuilder();
    formBuilder.type(MultipartBuilder.FORM);

    formBuilder.addFormDataPart("mode", "regist");
    formBuilder.addFormDataPart("pwd", reply.password);

    if (reply.resto >= 0) {
        formBuilder.addFormDataPart("resto", String.valueOf(reply.resto));
    }/*from   w  ww  . java 2  s.  c  om*/

    formBuilder.addFormDataPart("name", reply.name);
    formBuilder.addFormDataPart("email", reply.email);

    if (!TextUtils.isEmpty(reply.subject)) {
        formBuilder.addFormDataPart("sub", reply.subject);
    }

    formBuilder.addFormDataPart("com", reply.comment);

    if (captchaHash != null) {
        formBuilder.addFormDataPart("g-recaptcha-response", captchaHash);
    }

    if (reply.file != null) {
        formBuilder.addFormDataPart("upfile", reply.fileName,
                RequestBody.create(MediaType.parse("application/octet-stream"), reply.file));
    }

    if (reply.spoilerImage) {
        formBuilder.addFormDataPart("spoiler", "on");
    }

    Request.Builder request = new Request.Builder().url(ChanUrls.getReplyUrl(reply.board))
            .post(formBuilder.build());

    if (reply.usePass) {
        request.addHeader("Cookie", "pass_id=" + reply.passId);
    }

    makeOkHttpCall(request, new Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
            final ReplyResponse res = new ReplyResponse();
            res.isNetworkError = true;

            runUI(new Runnable() {
                public void run() {
                    replyListener.onResponse(res);
                }
            });
        }

        @Override
        public void onResponse(Response response) throws IOException {
            final ReplyResponse res = new ReplyResponse();
            if (response.isSuccessful()) {
                onReplyPosted(response.body().string(), reply, res);
                response.body().close();
            } else {
                res.isNetworkError = true;
            }

            runUI(new Runnable() {
                public void run() {
                    replyListener.onResponse(res);
                }
            });
        }
    });
}

From source file:org.fs.ghanaian.soap.SoapObjectCallback.java

License:Apache License

/***
 *
 * @param request//from w ww  .j  a  va 2  s  .  c o  m
 * @return
 */
@Override
public CoreCallback<Document> addRequest(Request request) {
    if (request != null) {
        Serializer serializer = new Serializer();
        RequestBody body = RequestBody.create(MediaType.parse("text/xml; charset=utf-8"),
                serializer.serialize(envelope));
        Request newRequest = request.newBuilder().post(body).build();
        mRequest = newRequest;
    }
    return this;
}

From source file:org.fs.ghanaian.util.RequestUtility.java

License:Apache License

/***
 * Converts rawRequestString and Mime to RequestBody object.
 * dont forget to pass charset as charset=utf-8
 *
 * @param rawPost//from   w  w w  .jav  a2s.c o  m
 * @param mime
 * @return
 */
static RequestBody body(String rawPost, String mime) {
    return RequestBody.create(MediaType.parse(mime), rawPost);
}

From source file:org.fuse.hawkular.agent.monitor.storage.HttpClientBuilder.java

License:Apache License

public Request buildJsonPostRequest(String url, Map<String, String> headers, String jsonPayload) {
    // make sure we are authenticated. see http://en.wikipedia.org/wiki/Basic_access_authentication#Client_side
    String base64Credentials = buildBase64Credentials();

    Builder requestBuilder = new Request.Builder().url(url)
            .addHeader("Authorization", "Basic " + base64Credentials).addHeader("Accept", "application/json");

    if (headers != null) {
        for (Map.Entry<String, String> header : headers.entrySet()) {
            requestBuilder.addHeader(header.getKey(), header.getValue());
        }//from www  . j  a v  a  2s .  c om
    }

    RequestBody body = RequestBody.create(MediaType.parse("application/json"), jsonPayload);

    return requestBuilder.post(body).build();
}

From source file:org.fuse.hawkular.agent.monitor.storage.HttpClientBuilder.java

License:Apache License

public Request buildJsonPutRequest(String url, Map<String, String> headers, String jsonPayload) {
    String base64Credentials = buildBase64Credentials();

    Builder requestBuilder = new Request.Builder().url(url)
            .addHeader("Authorization", "Basic " + base64Credentials).addHeader("Accept", "application/json");

    if (headers != null) {
        for (Map.Entry<String, String> header : headers.entrySet()) {
            requestBuilder.addHeader(header.getKey(), header.getValue());
        }/*from  w  ww .  j a va 2  s  .c o m*/
    }

    RequestBody body = RequestBody.create(MediaType.parse("application/json"), jsonPayload);

    return requestBuilder.put(body).build();
}