Search in sources :

Example 76 with Request

use of okhttp3.Request in project Lightning-Browser by anthonycr.

the class BaseSuggestionsModel method downloadSuggestionsForQuery.

/**
     * This method downloads the search suggestions for the specific query.
     * NOTE: This is a blocking operation, do not getResults on the UI thread.
     *
     * @param query the query to get suggestions for
     * @return the cache file containing the suggestions
     */
@Nullable
private InputStream downloadSuggestionsForQuery(@NonNull String query, @NonNull String language) {
    String queryUrl = createQueryUrl(query, language);
    try {
        URL url = new URL(queryUrl);
        // OkHttp automatically gzips requests
        Request suggestionsRequest = new Request.Builder().url(url).addHeader("Accept-Charset", mEncoding).cacheControl(mCacheControl).build();
        Response suggestionsResponse = mHttpClient.newCall(suggestionsRequest).execute();
        ResponseBody responseBody = suggestionsResponse.body();
        return responseBody != null ? responseBody.byteStream() : null;
    } catch (IOException exception) {
        Log.e(TAG, "Problem getting search suggestions", exception);
    }
    return null;
}
Also used : Response(okhttp3.Response) Request(okhttp3.Request) IOException(java.io.IOException) URL(java.net.URL) ResponseBody(okhttp3.ResponseBody) Nullable(android.support.annotation.Nullable)

Example 77 with Request

use of okhttp3.Request in project ignite by apache.

the class RestExecutor method sendRequest.

/** */
private RestResult sendRequest(boolean demo, String path, Map<String, Object> params, String mtd, Map<String, Object> headers, String body) throws IOException {
    if (demo && AgentClusterDemo.getDemoUrl() == null) {
        try {
            AgentClusterDemo.tryStart().await();
        } catch (InterruptedException ignore) {
            throw new IllegalStateException("Failed to execute request because of embedded node for demo mode is not started yet.");
        }
    }
    String url = demo ? AgentClusterDemo.getDemoUrl() : nodeUrl;
    HttpUrl.Builder urlBuilder = HttpUrl.parse(url).newBuilder();
    if (path != null)
        urlBuilder.addPathSegment(path);
    final Request.Builder reqBuilder = new Request.Builder();
    if (headers != null) {
        for (Map.Entry<String, Object> entry : headers.entrySet()) if (entry.getValue() != null)
            reqBuilder.addHeader(entry.getKey(), entry.getValue().toString());
    }
    if ("GET".equalsIgnoreCase(mtd)) {
        if (params != null) {
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                if (entry.getValue() != null)
                    urlBuilder.addQueryParameter(entry.getKey(), entry.getValue().toString());
            }
        }
    } else if ("POST".equalsIgnoreCase(mtd)) {
        if (body != null) {
            MediaType contentType = MediaType.parse("text/plain");
            reqBuilder.post(RequestBody.create(contentType, body));
        } else {
            FormBody.Builder formBody = new FormBody.Builder();
            if (params != null) {
                for (Map.Entry<String, Object> entry : params.entrySet()) {
                    if (entry.getValue() != null)
                        formBody.add(entry.getKey(), entry.getValue().toString());
                }
            }
            reqBuilder.post(formBody.build());
        }
    } else
        throw new IllegalArgumentException("Unknown HTTP-method: " + mtd);
    reqBuilder.url(urlBuilder.build());
    try (Response resp = httpClient.newCall(reqBuilder.build()).execute()) {
        String content = resp.body().string();
        if (resp.isSuccessful()) {
            JsonNode node = mapper.readTree(content);
            int status = node.get("successStatus").asInt();
            switch(status) {
                case STATUS_SUCCESS:
                    return RestResult.success(node.get("response").toString());
                default:
                    return RestResult.fail(status, node.get("error").asText());
            }
        }
        if (resp.code() == 401)
            return RestResult.fail(STATUS_AUTH_FAILED, "Failed to authenticate in grid. Please check agent\'s login and password or node port.");
        return RestResult.fail(STATUS_FAILED, "Failed connect to node and execute REST command.");
    } catch (ConnectException ignore) {
        throw new ConnectException("Failed connect to node and execute REST command [url=" + urlBuilder + "]");
    }
}
Also used : Request(okhttp3.Request) FormBody(okhttp3.FormBody) JsonNode(com.fasterxml.jackson.databind.JsonNode) HttpUrl(okhttp3.HttpUrl) Response(okhttp3.Response) MediaType(okhttp3.MediaType) HashMap(java.util.HashMap) Map(java.util.Map) ConnectException(java.net.ConnectException)

Example 78 with Request

use of okhttp3.Request in project spring-framework by spring-projects.

the class AbstractMockWebServerTestCase method getRequest.

private MockResponse getRequest(RecordedRequest request, byte[] body, String contentType) {
    if (request.getMethod().equals("OPTIONS")) {
        return new MockResponse().setResponseCode(200).setHeader("Allow", "GET, OPTIONS, HEAD, TRACE");
    }
    Buffer buf = new Buffer();
    buf.write(body);
    MockResponse response = new MockResponse().setHeader("Content-Length", body.length).setBody(buf).setResponseCode(200);
    if (contentType != null) {
        response = response.setHeader("Content-Type", contentType);
    }
    return response;
}
Also used : Buffer(okio.Buffer) MockResponse(okhttp3.mockwebserver.MockResponse)

Example 79 with Request

use of okhttp3.Request in project spring-framework by spring-projects.

the class AbstractMockWebServerTestCase method putRequest.

private MockResponse putRequest(RecordedRequest request, String expectedRequestContent) {
    assertTrue("Invalid request content-length", Integer.parseInt(request.getHeader("Content-Length")) > 0);
    String requestContentType = request.getHeader("Content-Type");
    assertNotNull("No content-type", requestContentType);
    Charset charset = StandardCharsets.ISO_8859_1;
    if (requestContentType.contains("charset=")) {
        String charsetName = requestContentType.split("charset=")[1];
        charset = Charset.forName(charsetName);
    }
    assertEquals("Invalid request body", expectedRequestContent, request.getBody().readString(charset));
    return new MockResponse().setResponseCode(202);
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) Charset(java.nio.charset.Charset)

Example 80 with Request

use of okhttp3.Request in project spring-framework by spring-projects.

the class AbstractMockWebServerTestCase method postRequest.

private MockResponse postRequest(RecordedRequest request, String expectedRequestContent, String location, String contentType, byte[] responseBody) {
    assertEquals(1, request.getHeaders().values("Content-Length").size());
    assertTrue("Invalid request content-length", Integer.parseInt(request.getHeader("Content-Length")) > 0);
    String requestContentType = request.getHeader("Content-Type");
    assertNotNull("No content-type", requestContentType);
    Charset charset = StandardCharsets.ISO_8859_1;
    if (requestContentType.contains("charset=")) {
        String charsetName = requestContentType.split("charset=")[1];
        charset = Charset.forName(charsetName);
    }
    assertEquals("Invalid request body", expectedRequestContent, request.getBody().readString(charset));
    Buffer buf = new Buffer();
    buf.write(responseBody);
    return new MockResponse().setHeader("Location", baseUrl + location).setHeader("Content-Type", contentType).setHeader("Content-Length", responseBody.length).setBody(buf).setResponseCode(201);
}
Also used : Buffer(okio.Buffer) MockResponse(okhttp3.mockwebserver.MockResponse) Charset(java.nio.charset.Charset)

Aggregations

Request (okhttp3.Request)1552 Response (okhttp3.Response)1090 Test (org.junit.Test)948 IOException (java.io.IOException)624 MockResponse (okhttp3.mockwebserver.MockResponse)560 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)556 OkHttpClient (okhttp3.OkHttpClient)343 RequestBody (okhttp3.RequestBody)281 Call (okhttp3.Call)255 ResponseBody (okhttp3.ResponseBody)252 HttpUrl (okhttp3.HttpUrl)186 Test (org.junit.jupiter.api.Test)158 WatsonServiceUnitTest (com.ibm.watson.developer_cloud.WatsonServiceUnitTest)142 Buffer (okio.Buffer)138 List (java.util.List)114 Callback (okhttp3.Callback)114 File (java.io.File)105 URI (java.net.URI)101 InputStream (java.io.InputStream)99 JSONObject (org.json.JSONObject)96