Search in sources :

Example 86 with MediaType

use of com.reprezen.kaizen.oasparser.model3.MediaType in project MVPArms by JessYanCoding.

the class RequestIntercept method intercept.

@Override
public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    if (//在请求服务器之前可以拿到request,做一些操作比如给request添加header,如果不做操作则返回参数中的request
    mHandler != null)
        request = mHandler.onHttpRequestBefore(chain, request);
    Buffer requestbuffer = new Buffer();
    if (request.body() != null) {
        request.body().writeTo(requestbuffer);
    } else {
        Timber.tag("Request").w("request.body() == null");
    }
    //打印url信息
    Timber.tag("Request").w("Sending Request %s on %n Params --->  %s%n Connection ---> %s%n Headers ---> %s", request.url(), request.body() != null ? parseParams(request.body(), requestbuffer) : "null", chain.connection(), request.headers());
    long t1 = System.nanoTime();
    Response originalResponse = chain.proceed(request);
    long t2 = System.nanoTime();
    //打印响应时间
    Timber.tag("Response").w("Received response  in %.1fms%n%s", (t2 - t1) / 1e6d, originalResponse.headers());
    //读取服务器返回的结果
    ResponseBody responseBody = originalResponse.body();
    BufferedSource source = responseBody.source();
    // Buffer the entire body.
    source.request(Long.MAX_VALUE);
    Buffer buffer = source.buffer();
    //获取content的压缩类型
    String encoding = originalResponse.headers().get("Content-Encoding");
    Buffer clone = buffer.clone();
    String bodyString;
    //解析response content
    if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
        //content使用gzip压缩
        //解压
        bodyString = ZipHelper.decompressForGzip(clone.readByteArray());
    } else if (encoding != null && encoding.equalsIgnoreCase("zlib")) {
        //content使用zlib压缩
        //解压
        bodyString = ZipHelper.decompressToStringForZlib(clone.readByteArray());
    } else {
        //content没有被压缩
        Charset charset = Charset.forName("UTF-8");
        MediaType contentType = responseBody.contentType();
        if (contentType != null) {
            charset = contentType.charset(charset);
        }
        bodyString = clone.readString(charset);
    }
    Timber.tag("Result").w(jsonFormat(bodyString));
    if (//这里可以比客户端提前一步拿到服务器返回的结果,可以做一些操作,比如token超时,重新获取
    mHandler != null)
        return mHandler.onHttpResultResponse(bodyString, chain, originalResponse);
    return originalResponse;
}
Also used : Buffer(okio.Buffer) Response(okhttp3.Response) Request(okhttp3.Request) Charset(java.nio.charset.Charset) MediaType(okhttp3.MediaType) ResponseBody(okhttp3.ResponseBody) BufferedSource(okio.BufferedSource)

Example 87 with MediaType

use of com.reprezen.kaizen.oasparser.model3.MediaType 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 88 with MediaType

use of com.reprezen.kaizen.oasparser.model3.MediaType in project graphhopper by graphhopper.

the class BaseServletTester method post.

protected String post(String path, int expectedStatusCode, String xmlOrJson) throws IOException {
    String url = getTestAPIUrl(path);
    MediaType type;
    if (xmlOrJson.startsWith("<")) {
        type = MT_XML;
    } else {
        type = MT_JSON;
    }
    Response rsp = client.newCall(new Request.Builder().url(url).post(RequestBody.create(type, xmlOrJson)).build()).execute();
    assertEquals(url + ", http status was:" + rsp.code(), HttpStatus.getMessage(expectedStatusCode), HttpStatus.getMessage(rsp.code()));
    return rsp.body().string();
}
Also used : Response(okhttp3.Response) Request(okhttp3.Request) MediaType(okhttp3.MediaType)

Example 89 with MediaType

use of com.reprezen.kaizen.oasparser.model3.MediaType in project okhttp by square.

the class BridgeInterceptor method intercept.

@Override
public Response intercept(Chain chain) throws IOException {
    Request userRequest = chain.request();
    Request.Builder requestBuilder = userRequest.newBuilder();
    RequestBody body = userRequest.body();
    if (body != null) {
        MediaType contentType = body.contentType();
        if (contentType != null) {
            requestBuilder.header("Content-Type", contentType.toString());
        }
        long contentLength = body.contentLength();
        if (contentLength != -1) {
            requestBuilder.header("Content-Length", Long.toString(contentLength));
            requestBuilder.removeHeader("Transfer-Encoding");
        } else {
            requestBuilder.header("Transfer-Encoding", "chunked");
            requestBuilder.removeHeader("Content-Length");
        }
    }
    if (userRequest.header("Host") == null) {
        requestBuilder.header("Host", hostHeader(userRequest.url(), false));
    }
    if (userRequest.header("Connection") == null) {
        requestBuilder.header("Connection", "Keep-Alive");
    }
    // If we add an "Accept-Encoding: gzip" header field we're responsible for also decompressing
    // the transfer stream.
    boolean transparentGzip = false;
    if (userRequest.header("Accept-Encoding") == null && userRequest.header("Range") == null) {
        transparentGzip = true;
        requestBuilder.header("Accept-Encoding", "gzip");
    }
    List<Cookie> cookies = cookieJar.loadForRequest(userRequest.url());
    if (!cookies.isEmpty()) {
        requestBuilder.header("Cookie", cookieHeader(cookies));
    }
    if (userRequest.header("User-Agent") == null) {
        requestBuilder.header("User-Agent", Version.userAgent());
    }
    Response networkResponse = chain.proceed(requestBuilder.build());
    HttpHeaders.receiveHeaders(cookieJar, userRequest.url(), networkResponse.headers());
    Response.Builder responseBuilder = networkResponse.newBuilder().request(userRequest);
    if (transparentGzip && "gzip".equalsIgnoreCase(networkResponse.header("Content-Encoding")) && HttpHeaders.hasBody(networkResponse)) {
        GzipSource responseBody = new GzipSource(networkResponse.body().source());
        Headers strippedHeaders = networkResponse.headers().newBuilder().removeAll("Content-Encoding").removeAll("Content-Length").build();
        responseBuilder.headers(strippedHeaders);
        responseBuilder.body(new RealResponseBody(strippedHeaders, Okio.buffer(responseBody)));
    }
    return responseBuilder.build();
}
Also used : Cookie(okhttp3.Cookie) Headers(okhttp3.Headers) Request(okhttp3.Request) Response(okhttp3.Response) GzipSource(okio.GzipSource) MediaType(okhttp3.MediaType) RequestBody(okhttp3.RequestBody)

Example 90 with MediaType

use of com.reprezen.kaizen.oasparser.model3.MediaType in project okhttp by square.

the class HttpOverHttp2Test method closeAfterFlush.

@Test
public void closeAfterFlush() throws Exception {
    final byte[] postBytes = "FGHIJ".getBytes(Util.UTF_8);
    server.enqueue(new MockResponse().setBody("ABCDE"));
    Call call = client.newCall(new Request.Builder().url(server.url("/foo")).post(new RequestBody() {

        @Override
        public MediaType contentType() {
            return MediaType.parse("text/plain; charset=utf-8");
        }

        @Override
        public long contentLength() throws IOException {
            return postBytes.length;
        }

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            // push bytes into the stream's buffer
            sink.write(postBytes);
            // Http2Connection.writeData subject to write window
            sink.flush();
            // Http2Connection.writeData empty frame
            sink.close();
        }
    }).build());
    Response response = call.execute();
    assertEquals("ABCDE", response.body().string());
    RecordedRequest request = server.takeRequest();
    assertEquals("POST /foo HTTP/1.1", request.getRequestLine());
    assertArrayEquals(postBytes, request.getBody().readByteArray());
    assertEquals(postBytes.length, Integer.parseInt(request.getHeader("Content-Length")));
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) Response(okhttp3.Response) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) MockResponse(okhttp3.mockwebserver.MockResponse) Call(okhttp3.Call) MediaType(okhttp3.MediaType) BufferedSink(okio.BufferedSink) IOException(java.io.IOException) RequestBody(okhttp3.RequestBody) Test(org.junit.Test)

Aggregations

MediaType (okhttp3.MediaType)297 RequestBody (okhttp3.RequestBody)186 Request (okhttp3.Request)179 Response (okhttp3.Response)158 IOException (java.io.IOException)137 ResponseBody (okhttp3.ResponseBody)71 OkHttpClient (okhttp3.OkHttpClient)68 Charset (java.nio.charset.Charset)50 Buffer (okio.Buffer)50 Headers (okhttp3.Headers)48 JSONObject (org.json.JSONObject)38 BufferedSource (okio.BufferedSource)36 MultipartBody (okhttp3.MultipartBody)34 HttpUrl (okhttp3.HttpUrl)30 Map (java.util.Map)24 BufferedSink (okio.BufferedSink)23 File (java.io.File)22 InputStream (java.io.InputStream)21 ArrayList (java.util.ArrayList)21 Test (org.junit.Test)21