use of okhttp3.Headers in project Parse-SDK-Android by ParsePlatform.
the class ParseOkHttpClientTest method testGetOkHttpRequest.
@Test
public void testGetOkHttpRequest() throws IOException {
Map<String, String> headers = new HashMap<>();
String headerName = "name";
String headerValue = "value";
headers.put(headerName, headerValue);
String url = "http://www.parse.com/";
String content = "test";
int contentLength = content.length();
String contentType = "application/json";
ParseHttpRequest parseRequest = new ParseHttpRequest.Builder().setUrl(url).setMethod(ParseHttpRequest.Method.POST).setBody(new ParseByteArrayHttpBody(content, contentType)).setHeaders(headers).build();
ParseOkHttpClient parseClient = new ParseOkHttpClient(10000, null);
Request okHttpRequest = parseClient.getRequest(parseRequest);
// Verify method
assertEquals(ParseHttpRequest.Method.POST.toString(), okHttpRequest.method());
// Verify URL
assertEquals(url, okHttpRequest.url().toString());
// Verify Headers
assertEquals(1, okHttpRequest.headers(headerName).size());
assertEquals(headerValue, okHttpRequest.headers(headerName).get(0));
// Verify Body
RequestBody okHttpBody = okHttpRequest.body();
assertEquals(contentLength, okHttpBody.contentLength());
assertEquals(contentType, okHttpBody.contentType().toString());
// Can not read parseRequest body to compare since it has been read during
// creating okHttpRequest
Buffer buffer = new Buffer();
okHttpBody.writeTo(buffer);
ByteArrayOutputStream output = new ByteArrayOutputStream();
buffer.copyTo(output);
assertArrayEquals(content.getBytes(), output.toByteArray());
}
use of okhttp3.Headers in project Gradle-demo by Arisono.
the class OkhttpUtilsMain method okBasicRequest.
public static void okBasicRequest() {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url("http://www.baidu.com").build();
try {
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) {
}
Headers responseHeaders = response.headers();
for (int i = 0; i < responseHeaders.size(); i++) {
System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
}
} catch (IOException e) {
e.printStackTrace();
}
}
use of okhttp3.Headers in project graylog2-server by Graylog2.
the class HttpPollTransport method doLaunch.
@Override
public void doLaunch(final MessageInput input) throws MisfireException {
serverStatus.awaitRunning(() -> lifecycleStateChange(Lifecycle.RUNNING));
// listen for lifecycle changes
serverEventBus.register(this);
final Map<String, String> headers = parseHeaders(configuration.getString(CK_HEADERS));
// figure out a reasonable remote address
final String url = configuration.getString(CK_URL);
final InetSocketAddress remoteAddress;
InetSocketAddress remoteAddress1;
try {
final URL url1 = new URL(url);
final int port = url1.getPort();
remoteAddress1 = new InetSocketAddress(url1.getHost(), port != -1 ? port : 80);
} catch (MalformedURLException e) {
remoteAddress1 = null;
}
remoteAddress = remoteAddress1;
final Runnable task = () -> {
if (paused) {
LOG.debug("Message processing paused, not polling HTTP resource {}.", url);
return;
}
if (isThrottled()) {
// this transport won't block, but we can simply skip this iteration
LOG.debug("Not polling HTTP resource {} because we are throttled.", url);
}
final Request.Builder requestBuilder = new Request.Builder().get().url(url).headers(Headers.of(headers));
try (final Response r = httpClient.newCall(requestBuilder.build()).execute()) {
if (!r.isSuccessful()) {
throw new RuntimeException("Expected successful HTTP status code [2xx], got " + r.code());
}
input.processRawMessage(new RawMessage(r.body().bytes(), remoteAddress));
} catch (IOException e) {
LOG.error("Could not fetch HTTP resource at " + url, e);
}
};
scheduledFuture = scheduler.scheduleAtFixedRate(task, 0, configuration.getInt(CK_INTERVAL), TimeUnit.valueOf(configuration.getString(CK_TIMEUNIT)));
}
use of okhttp3.Headers 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 okhttp3.Headers in project amhttp by Eddieyuan123.
the class RequestManager method post.
public <T> void post(Context context, String url, CacheControl cacheControl, HashMap<String, String> headers, HashMap<String, String> params, Object tag, int callMethod, final OnAddListener<T> listener) {
try {
IRequestBodyFactory requestBodyFactory = new RequestBodyFactoryImpl();
RequestBody requestBody = requestBodyFactory.buildRequestBody(params);
final Request request = new Request.Builder().cacheControl(cacheControl == null ? CacheControl.FORCE_NETWORK : cacheControl).headers(Headers.of(headers)).tag(tag == null ? context.hashCode() : tag).url(url).post(requestBody).build();
if (callMethod == CallMethod.SYNC) {
RequestUtils.execute(mOkHttpClient, request, listener);
} else {
RequestUtils.enqueue(mOkHttpClient, request, listener);
}
} catch (Exception e) {
e.printStackTrace();
}
}
Aggregations