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;
}
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 + "]");
}
}
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();
}
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();
}
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")));
}
Aggregations