Search in sources :

Example 51 with FormBody

use of okhttp3.FormBody in project Douya by DreaminginCodeZH.

the class InterceptorUtils method addParameters.

public static void addParameters(Request.Builder builder, Request request, Map<String, String> parameters) throws IOException {
    String method = request.method();
    if (!HttpMethod.requiresRequestBody(method)) {
        HttpUrl.Builder urlBuilder = request.url().newBuilder();
        for (Map.Entry<String, String> parameter : parameters.entrySet()) {
            String parameterName = parameter.getKey();
            urlBuilder.removeAllQueryParameters(parameterName);
            urlBuilder.addQueryParameter(parameterName, parameter.getValue());
        }
        builder.url(urlBuilder.build());
    } else {
        RequestBody body = request.body();
        if (body == null || body.contentLength() == 0) {
            FormBody.Builder bodyBuilder = new FormBody.Builder();
            for (Map.Entry<String, String> parameter : parameters.entrySet()) {
                bodyBuilder.add(parameter.getKey(), parameter.getValue());
            }
            body = bodyBuilder.build();
        } else if (body instanceof FormBody) {
            FormBody formBody = (FormBody) body;
            FormBody.Builder bodyBuilder = new FormBody.Builder();
            for (int i = 0, size = formBody.size(); i < size; ++i) {
                String name = formBody.name(i);
                if (parameters.containsKey(name)) {
                    continue;
                }
                bodyBuilder.add(name, formBody.value(i));
            }
            for (Map.Entry<String, String> parameter : parameters.entrySet()) {
                bodyBuilder.add(parameter.getKey(), parameter.getValue());
            }
            body = bodyBuilder.build();
        } else if (body instanceof MultipartBody) {
            MultipartBody multipartBody = (MultipartBody) body;
            MultipartBody.Builder bodyBuilder = new MultipartBody.Builder(multipartBody.boundary()).setType(multipartBody.type());
            List<MultipartBody.Part> parameterParts = new ArrayList<>();
            for (Map.Entry<String, String> parameter : parameters.entrySet()) {
                MultipartBody.Part parameterPart = MultipartBody.Part.createFormData(parameter.getKey(), parameter.getValue());
                parameterParts.add(parameterPart);
            }
            List<String> parameterContentDispositions = new ArrayList<>();
            for (MultipartBody.Part parameterPart : parameterParts) {
                String parameterContentDisposition = parameterPart.headers().get(Http.Headers.CONTENT_DISPOSITION);
                parameterContentDispositions.add(parameterContentDisposition);
            }
            for (int i = 0, size = multipartBody.size(); i < size; ++i) {
                MultipartBody.Part part = multipartBody.part(i);
                Headers headers = part.headers();
                if (headers != null) {
                    String contentDisposition = headers.get(Http.Headers.CONTENT_DISPOSITION);
                    if (parameterContentDispositions.contains(contentDisposition)) {
                        continue;
                    }
                }
                bodyBuilder.addPart(part);
            }
            for (MultipartBody.Part parameterPart : parameterParts) {
                bodyBuilder.addPart(parameterPart);
            }
            body = bodyBuilder.build();
        } else {
            LogUtils.wtf("Unknown request body " + body.getClass().getName() + ": " + body);
        }
        builder.method(method, body).removeHeader(Http.Headers.CONTENT_LENGTH).header(Http.Headers.CONTENT_LENGTH, String.valueOf(body.contentLength()));
    }
}
Also used : Headers(okhttp3.Headers) FormBody(okhttp3.FormBody) ArrayList(java.util.ArrayList) HttpUrl(okhttp3.HttpUrl) MultipartBody(okhttp3.MultipartBody) Map(java.util.Map) RequestBody(okhttp3.RequestBody)

Example 52 with FormBody

use of okhttp3.FormBody in project sonarqube by SonarSource.

the class HttpConnector method post.

private WsResponse post(PostRequest postRequest) {
    HttpUrl.Builder urlBuilder = prepareUrlBuilder(postRequest);
    RequestBody body;
    Map<String, PostRequest.Part> parts = postRequest.getParts();
    if (parts.isEmpty()) {
        // parameters are defined in the body (application/x-www-form-urlencoded)
        FormBody.Builder formBody = new FormBody.Builder();
        postRequest.getParameters().getKeys().forEach(key -> postRequest.getParameters().getValues(key).forEach(value -> formBody.add(key, value)));
        body = formBody.build();
    } else {
        // parameters are defined in the URL (as GET)
        completeUrlQueryParameters(postRequest, urlBuilder);
        MultipartBody.Builder bodyBuilder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        parts.entrySet().forEach(param -> {
            PostRequest.Part part = param.getValue();
            bodyBuilder.addFormDataPart(param.getKey(), part.getFile().getName(), RequestBody.create(MediaType.parse(part.getMediaType()), part.getFile()));
        });
        body = bodyBuilder.build();
    }
    Request.Builder okRequestBuilder = prepareOkRequestBuilder(postRequest, urlBuilder).post(body);
    Response response = doCall(prepareOkHttpClient(noRedirectOkHttpClient, postRequest), okRequestBuilder.build());
    response = checkRedirect(response, postRequest);
    return new OkHttpResponse(response);
}
Also used : WsUtils.nullToEmpty(org.sonarqube.ws.WsUtils.nullToEmpty) HTTP_MOVED_PERM(java.net.HttpURLConnection.HTTP_MOVED_PERM) WsUtils.checkArgument(org.sonarqube.ws.WsUtils.checkArgument) HTTP_PERM_REDIRECT(okhttp3.internal.http.StatusLine.HTTP_PERM_REDIRECT) RequestBody(okhttp3.RequestBody) FormBody(okhttp3.FormBody) HTTP_TEMP_REDIRECT(okhttp3.internal.http.StatusLine.HTTP_TEMP_REDIRECT) Proxy(java.net.Proxy) Map(java.util.Map) Response(okhttp3.Response) Call(okhttp3.Call) Nullable(javax.annotation.Nullable) MediaType(okhttp3.MediaType) Request(okhttp3.Request) UTF_8(java.nio.charset.StandardCharsets.UTF_8) WsUtils.isNullOrEmpty(org.sonarqube.ws.WsUtils.isNullOrEmpty) IOException(java.io.IOException) Credentials(okhttp3.Credentials) String.format(java.lang.String.format) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) TimeUnit(java.util.concurrent.TimeUnit) HTTP_MOVED_TEMP(java.net.HttpURLConnection.HTTP_MOVED_TEMP) OkHttpClient(okhttp3.OkHttpClient) MultipartBody(okhttp3.MultipartBody) X509TrustManager(javax.net.ssl.X509TrustManager) HttpUrl(okhttp3.HttpUrl) FormBody(okhttp3.FormBody) Request(okhttp3.Request) HttpUrl(okhttp3.HttpUrl) Response(okhttp3.Response) MultipartBody(okhttp3.MultipartBody) RequestBody(okhttp3.RequestBody)

Example 53 with FormBody

use of okhttp3.FormBody in project instagram-java-scraper by postaddictme.

the class Instagram method addMediaComment.

public ActionResponse<Comment> addMediaComment(String code, String commentText) throws IOException {
    String url = Endpoint.addMediaCommentLink(MediaUtil.getIdFromCode(code));
    FormBody formBody = new FormBody.Builder().add("comment_text", commentText).build();
    Request request = new Request.Builder().url(url).header(Endpoint.REFERER, Endpoint.getMediaPageLinkByCode(code) + "/").post(formBody).build();
    Response response = executeHttpRequest(withCsrfToken(request));
    try (InputStream jsonStream = response.body().byteStream()) {
        return mapper.mapMediaCommentResponse(jsonStream);
    }
}
Also used : Response(okhttp3.Response) ActionResponse(me.postaddict.instagram.scraper.model.ActionResponse) DataInputStream(java.io.DataInputStream) InputStream(java.io.InputStream) FormBody(okhttp3.FormBody) GetMediaByTagRequest(me.postaddict.instagram.scraper.request.GetMediaByTagRequest) GetLocationRequest(me.postaddict.instagram.scraper.request.GetLocationRequest) GetMediasRequest(me.postaddict.instagram.scraper.request.GetMediasRequest) GetMediaLikesRequest(me.postaddict.instagram.scraper.request.GetMediaLikesRequest) Request(okhttp3.Request) GetFollowsRequest(me.postaddict.instagram.scraper.request.GetFollowsRequest) GetFollowersRequest(me.postaddict.instagram.scraper.request.GetFollowersRequest)

Example 54 with FormBody

use of okhttp3.FormBody in project Auto.js by hyb1996.

the class ExampleUnitTest method test.

@Test
public void test() throws IOException {
    File file = new File("C:\\Users\\Stardust\\Desktop\\1.txt");
    System.out.println(PFiles.read(file));
    String url = "http://posttestserver.com/post.php?dir=example";
    OkHttpClient client = new OkHttpClient();
    RequestBody formBody = new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("text/plain"), file)).addFormDataPart("other_field", "other_field_value").build();
    Request request = new Request.Builder().url(url).post(formBody).build();
    Response response = client.newCall(request).execute();
    System.out.println(response.body().string());
}
Also used : Response(okhttp3.Response) OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) File(java.io.File) RequestBody(okhttp3.RequestBody) Test(org.junit.Test)

Example 55 with FormBody

use of okhttp3.FormBody in project okhttp by square.

the class PostForm method run.

public void run() throws Exception {
    RequestBody formBody = new FormBody.Builder().add("search", "Jurassic Park").build();
    Request request = new Request.Builder().url("https://en.wikipedia.org/w/index.php").post(formBody).build();
    try (Response response = client.newCall(request).execute()) {
        if (!response.isSuccessful())
            throw new IOException("Unexpected code " + response);
        System.out.println(response.body().string());
    }
}
Also used : Response(okhttp3.Response) Request(okhttp3.Request) IOException(java.io.IOException) RequestBody(okhttp3.RequestBody)

Aggregations

Request (okhttp3.Request)61 Response (okhttp3.Response)58 FormBody (okhttp3.FormBody)54 RequestBody (okhttp3.RequestBody)43 IOException (java.io.IOException)40 Call (okhttp3.Call)33 Callback (okhttp3.Callback)29 JSONObject (org.json.JSONObject)20 Map (java.util.Map)16 HttpUrl (okhttp3.HttpUrl)10 OkHttpClient (okhttp3.OkHttpClient)10 HashMap (java.util.HashMap)9 MultipartBody (okhttp3.MultipartBody)9 ArrayList (java.util.ArrayList)6 MediaType (okhttp3.MediaType)6 TypeToken (com.google.gson.reflect.TypeToken)4 File (java.io.File)3 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)2 List (java.util.List)2 ProgressRequestBody (me.ccrama.redditslide.util.ProgressRequestBody)2