List of usage examples for com.squareup.okhttp Response headers
Headers headers
To view the source code for com.squareup.okhttp Response headers.
Click Source Link
From source file:org.apache.nifi.processors.standard.InvokeHTTP.java
License:Apache License
/** * Returns a Map of flowfile attributes from the response http headers. Multivalue headers are naively converted to comma separated strings. *///from w w w . j a va 2s. co m private Map<String, String> convertAttributesFromHeaders(URL url, Response responseHttp) { // create a new hashmap to store the values from the connection Map<String, String> map = new HashMap<>(); for (Map.Entry<String, List<String>> entry : responseHttp.headers().toMultimap().entrySet()) { String key = entry.getKey(); if (key == null) { continue; } List<String> values = entry.getValue(); // we ignore any headers with no actual values (rare) if (values == null || values.isEmpty()) { continue; } // create a comma separated string from the values, this is stored in the map String value = csv(values); // put the csv into the map map.put(key, value); } if ("HTTPS".equals(url.getProtocol().toUpperCase())) { map.put(REMOTE_DN, responseHttp.handshake().peerPrincipal().getName()); } return map; }
From source file:org.dkf.jed2k.util.http.OKHTTPClient.java
License:Open Source License
@Override public void save(String url, File file, boolean resume, int timeout, String userAgent, String referrer) throws IOException { FileOutputStream fos;/*from ww w . j ava 2 s . c o m*/ long rangeStart; canceled = false; if (resume && file.exists()) { fos = new FileOutputStream(file, true); rangeStart = file.length(); } else { fos = new FileOutputStream(file, false); rangeStart = -1; } final OkHttpClient okHttpClient = newOkHttpClient(); final Request.Builder builder = prepareRequestBuilder(okHttpClient, url, timeout, userAgent, referrer, null); addRangeHeader(rangeStart, -1, builder); final Response response = getSyncResponse(okHttpClient, builder); final Headers headers = response.headers(); onHeaders(headers); final InputStream in = response.body().byteStream(); byte[] b = new byte[4096]; int n; while (!canceled && (n = in.read(b, 0, b.length)) != -1) { if (!canceled) { fos.write(b, 0, n); onData(b, 0, n); } } closeQuietly(fos); closeQuietly(response.body()); if (canceled) { onCancel(); } else { onComplete(); } }
From source file:org.floens.chan.core.http.PassHttpCall.java
License:Open Source License
@Override public void process(Response response, String result) throws IOException { boolean authSuccess = false; if (result.contains("Success! Your device is now authorized")) { authSuccess = true;/* w w w. ja v a2s . c o m*/ } else { if (result.contains("Your Token must be exactly 10 characters")) { message = "Incorrect token"; } else if (result.contains("You have left one or more fields blank")) { message = "You have left one or more fields blank"; } else if (result.contains("Incorrect Token or PIN")) { message = "Incorrect Token or PIN"; } else { message = "Unknown error"; } } if (authSuccess) { List<String> cookies = response.headers("Set-Cookie"); String passId = null; for (String cookie : cookies) { try { List<HttpCookie> parsedList = HttpCookie.parse(cookie); for (HttpCookie parsed : parsedList) { if (parsed.getName().equals("pass_id") && !parsed.getValue().equals("0")) { passId = parsed.getValue(); } } } catch (IllegalArgumentException ignored) { } } if (passId != null) { this.passId = passId; message = "Success! Your device is now authorized."; success = true; } else { message = "Could not get pass id"; } } }
From source file:org.floens.chan.core.manager.ReplyManager.java
License:Open Source License
public void postPass(String token, String pin, final PassListener passListener) { FormEncodingBuilder formBuilder = new FormEncodingBuilder(); formBuilder.add("act", "do_login"); formBuilder.add("id", token); formBuilder.add("pin", pin); Request.Builder request = new Request.Builder().url(ChanUrls.getPassUrl()).post(formBuilder.build()); makeOkHttpCall(request, new Callback() { @Override/*from w w w . ja va2 s.co m*/ public void onFailure(Request request, IOException e) { final PassResponse res = new PassResponse(); res.isError = true; res.message = context.getString(R.string.pass_error); runUI(new Runnable() { public void run() { passListener.onResponse(res); } }); } @Override public void onResponse(Response response) throws IOException { if (!response.isSuccessful()) { onFailure(response.request(), null); return; } String responseString = response.body().string(); response.body().close(); final PassResponse res = new PassResponse(); if (responseString.contains("Your device is now authorized")) { List<String> cookies = response.headers("Set-Cookie"); String passId = null; for (String cookie : cookies) { try { List<HttpCookie> parsedList = HttpCookie.parse(cookie); for (HttpCookie parsed : parsedList) { if (parsed.getName().equals("pass_id") && !parsed.getValue().equals("0")) { passId = parsed.getValue(); } } } catch (IllegalArgumentException ignored) { } } if (passId != null) { res.passId = passId; res.message = "Success! Your device is now authorized."; } else { res.isError = true; res.message = "Could not get pass id"; } } else { res.isError = true; if (responseString.contains("Your Token must be exactly 10 characters")) { res.message = "Incorrect token"; } else if (responseString.contains("You have left one or more fields blank")) { res.message = "You have left one or more fields blank"; } else if (responseString.contains("Incorrect Token or PIN")) { res.message = "Incorrect Token or PIN"; } else { res.unknownError = true; } } runUI(new Runnable() { public void run() { passListener.onResponse(res); } }); } }); }
From source file:org.jclouds.http.okhttp.OkHttpCommandExecutorService.java
License:Apache License
@Override protected HttpResponse invoke(Request nativeRequest) throws IOException, InterruptedException { OkHttpClient requestScopedClient = globalClient.clone(); requestScopedClient.setProxy(proxyForURI.apply(nativeRequest.uri())); Response response = requestScopedClient.newCall(nativeRequest).execute(); HttpResponse.Builder<?> builder = HttpResponse.builder(); builder.statusCode(response.code()); builder.message(response.message()); Builder<String, String> headerBuilder = ImmutableMultimap.builder(); Headers responseHeaders = response.headers(); for (String header : responseHeaders.names()) { headerBuilder.putAll(header, responseHeaders.values(header)); }/*from ww w . j ava 2s . c om*/ ImmutableMultimap<String, String> headers = headerBuilder.build(); if (response.code() == 204 && response.body() != null) { response.body().close(); } else { Payload payload = newInputStreamPayload(response.body().byteStream()); contentMetadataCodec.fromHeaders(payload.getContentMetadata(), headers); builder.payload(payload); } builder.headers(filterOutContentHeaders(headers)); return builder.build(); }
From source file:org.opensilk.music.renderer.googlecast.server.ProxyHandler.java
License:Open Source License
@Override public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { if (!HttpMethods.GET.equals(request.getMethod())) { response.sendError(HttpStatus.METHOD_NOT_ALLOWED_405); baseRequest.setHandled(true);/* w ww.j a v a 2 s . c om*/ return; } String pathInfo = StringUtils.stripStart(request.getPathInfo(), "/"); Uri contentUri = Uri.parse(CastServerUtil.decodeString(pathInfo)); if (CastServer.DUMP_REQUEST_HEADERS) { StringBuilder reqlog = new StringBuilder(); reqlog.append("Serving artwork uri ").append(contentUri).append("\n Method ") .append(request.getMethod()); for (Enumeration<String> names = request.getHeaderNames(); names.hasMoreElements();) { String name = names.nextElement(); reqlog.append("\n HDR: ").append(name).append(":").append(request.getHeader(name)); } Timber.v(reqlog.toString()); } com.squareup.okhttp.Request.Builder rb = new com.squareup.okhttp.Request.Builder() .url(contentUri.toString()); Track.Res trackRes = mTrackResCache.get(contentUri); //add resource headers Map<String, String> headers = trackRes.getHeaders(); for (Map.Entry<String, String> e : headers.entrySet()) { rb.addHeader(e.getKey(), e.getValue()); } String range = request.getHeader("Range"); if (!StringUtils.isEmpty(range)) { rb.addHeader("Range", range); } String ifnonematch = request.getHeader("if-none-match"); if (!StringUtils.isEmpty(ifnonematch)) { rb.addHeader("if-none-match", ifnonematch); } //dont clog our cache with binaries CacheControl pCC = new CacheControl.Builder().noStore().noCache().build(); rb.cacheControl(pCC); Response pResponse = mOkClient.newCall(rb.get().build()).execute(); if (CastServer.DUMP_REQUEST_HEADERS) { StringBuilder sb = new StringBuilder(); sb.append("Executed proxy GET request uri ").append(contentUri).append("\n Resp: ") .append(pResponse.code()).append(",").append(pResponse.message()); for (String name : pResponse.headers().names()) { sb.append("\n HDR: ").append(name).append(": ").append(pResponse.header(name)); } Timber.v(sb.toString()); } if (!pResponse.isSuccessful()) { response.sendError(pResponse.code(), pResponse.message()); baseRequest.setHandled(true); return; } //build the response String acceptRanges = pResponse.header("Accept-Ranges"); if (!StringUtils.isEmpty(acceptRanges)) { response.addHeader("Accept-Ranges", acceptRanges); } String contentRange = pResponse.header("Content-Range"); if (!StringUtils.isEmpty(contentRange)) { response.addHeader("Content-Range", contentRange); } String contentLen = pResponse.header("Content-Length"); if (!StringUtils.isEmpty(contentLen)) { response.addHeader("Content-Length", contentLen); } String contentType = pResponse.header("Content-Type"); if (StringUtils.isEmpty(contentType)) { contentType = "application/octet-stream"; } response.addHeader("Content-Type", contentType); String etag = pResponse.header("Etag"); if (!StringUtils.isEmpty(etag)) { response.addHeader("Etag", etag); } if (HttpStatus.NOT_MODIFIED_304 == pResponse.code()) { response.flushBuffer(); } else { InputStream in = pResponse.body().byteStream(); try { //XXX out need not be closed OutputStream out = response.getOutputStream(); IOUtils.copy(in, out); out.flush(); } finally { IOUtils.closeQuietly(in); } } baseRequest.setHandled(true); }
From source file:org.runbuddy.libtomahawk.resolver.ScriptAccount.java
License:Open Source License
private JsonObject jsHttpRequest(ScriptInterfaceRequestOptions options) { Response response = null; try {/* w ww . j a va2 s.c o m*/ String url = null; Map<String, String> headers = null; String method = null; String username = null; String password = null; String data = null; boolean isTestingConfig = false; if (options != null) { url = options.url; headers = options.headers; method = options.method; username = options.username; password = options.password; data = options.data; isTestingConfig = options.isTestingConfig; } java.net.CookieManager cookieManager = getCookieManager(isTestingConfig); response = NetworkUtils.httpRequest(method, url, headers, username, password, data, true, cookieManager); // We have to encode the %-chars because the Android WebView automatically decodes // percentage-escaped chars ... for whatever reason. Seems likely that this is a bug. String responseText = response.body().string().replace("%", "%25"); JsonObject responseHeaders = new JsonObject(); for (String headerName : response.headers().names()) { String concatenatedValues = ""; for (int i = 0; i < response.headers(headerName).size(); i++) { if (i > 0) { concatenatedValues += "\n"; } concatenatedValues += response.headers(headerName).get(i); } String escapedKey = headerName.toLowerCase().replace("%", "%25"); String escapedValue = concatenatedValues.replace("%", "%25"); responseHeaders.addProperty(escapedKey, escapedValue); } int status = response.code(); String statusText = response.message().replace("%", "%25"); JsonObject result = new JsonObject(); result.addProperty("responseText", responseText); result.add("responseHeaders", responseHeaders); result.addProperty("status", status); result.addProperty("statusText", statusText); return result; } catch (IOException e) { Log.e(TAG, "jsHttpRequest: " + e.getClass() + ": " + e.getLocalizedMessage()); return null; } finally { if (response != null) { try { response.body().close(); } catch (IOException e) { Log.e(TAG, "jsHttpRequest: " + e.getClass() + ": " + e.getLocalizedMessage()); } } } }
From source file:pl.appformation.smash.SmashOkHttp.java
License:Apache License
public static @NonNull SmashNetworkData perform(SmashRequest<?> request) throws SmashError { SmashNetworkData data = new SmashNetworkData(); try {// ww w . ja v a 2 s .c om Request.Builder okBuilder = new Request.Builder().url(request.getUrl()); okBuilder.removeHeader("User-Agent").addHeader("User-Agent", Smash.getUserAgent()); BufferedSource body = getBody(request); switch (request.getMethod()) { case GET: okBuilder = okBuilder.get(); break; case POST: okBuilder = okBuilder.post(convertBody(request, body)); break; case PUT: okBuilder = okBuilder.put(convertBody(request, body)); break; case DELETE: okBuilder = okBuilder.delete(convertBody(request, body)); break; case HEAD: okBuilder = okBuilder.head(); break; case PATCH: okBuilder = okBuilder.patch(convertBody(request, body)); break; } Request okRequest = okBuilder.build(); Response okResponse = sHttpClient.newCall(okRequest).execute(); if (body != null) { body.close(); } data.code = okResponse.code(); data.headers = okResponse.headers(); data.source = okResponse.body().source(); data.length = okResponse.body().contentLength(); } catch (IOException ioe) { throw new SmashError(ioe); } return data; }
From source file:quickbeer.android.next.network.utils.LoginRedirectInterceptor.java
License:Open Source License
@Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); Response response = chain.proceed(request); if (request.uri().getPath().equals("/Signin_r.asp") && response.isRedirect()) { Log.d(TAG, "Modifying response for login request"); return new Response.Builder().request(request).protocol(response.protocol()).code(200) .message(response.message()).handshake(response.handshake()).headers(response.headers()) .body(response.body()).networkResponse(response.networkResponse()).build(); }/*from w w w. j av a 2s.c o m*/ return response; }
From source file:twitter4j.OkHttpResponse.java
License:Apache License
public OkHttpResponse(Response response, HttpClientConfiguration conf) throws IOException { super(conf);/*from w ww. j av a 2 s .c o m*/ this.response = response; Headers headers = response.headers(); Set<String> names = headers.names(); HashMap<String, List<String>> headerFields = new HashMap<String, List<String>>(); for (String name : names) { headerFields.put(name, headers.values(name)); } this.headerFields = headerFields; is = response.body().byteStream(); if (is != null && "gzip".equals(response.header("Content-Encoding"))) { is = new StreamingGZIPInputStream(is); } statusCode = response.code(); }