private CacheRequest put(Response response) throws IOException { String requestMethod = response.request().method(); if (HttpMethod.invalidatesCache(response.request().method())) { try { remove(response.request()); return null; } catch (IOException e) { return null; } } else if (!requestMethod.equals("GET") || OkHeaders.hasVaryAll(response)) { return null; } else { Entry entry = new Entry(response); try { Editor editor = this.cache.edit(urlToKey(response.request())); if (editor == null) { return null; } entry.writeTo(editor); return new CacheRequestImpl(editor); } catch (IOException e2) { abortQuietly(null); return null; } } }
private void initHttpEngine() throws IOException { if (this.httpEngineFailure != null) { throw this.httpEngineFailure; } else if (this.httpEngine == null) { this.connected = true; try { if (this.doOutput) { if (this.method.equals("GET")) { this.method = Constants.HTTP_POST; } else if (!HttpMethod.permitsRequestBody(this.method)) { throw new ProtocolException(this.method + " does not support writing"); } } this.httpEngine = newHttpEngine(this.method, null, null, null); } catch (IOException e) { this.httpEngineFailure = e; throw e; } } }
private void initHttpEngine() throws IOException { if (httpEngineFailure != null) { throw httpEngineFailure; } else if (httpEngine != null) { return; } connected = true; try { if (doOutput) { if (method.equals("GET")) { // they are requesting a stream to write to. This implies a POST method method = "POST"; } else if (!HttpMethod.hasRequestBody(method)) { // If the request method is neither POST nor PUT nor PATCH, then you're not writing throw new ProtocolException(method + " does not support writing"); } } // If the user set content length to zero, we know there will not be a request body. RetryableSink requestBody = doOutput && fixedContentLength == 0 ? Util.emptySink() : null; httpEngine = newHttpEngine(method, null, requestBody, null); } catch (IOException e) { httpEngineFailure = e; throw e; } }
private void initHttpEngine() throws IOException { if (httpEngineFailure != null) { throw httpEngineFailure; } else if (httpEngine != null) { return; } connected = true; try { if (doOutput) { if (method.equals("GET")) { // they are requesting a stream to write to. This implies a POST method method = "POST"; } else if (!HttpMethod.permitsRequestBody(method)) { throw new ProtocolException(method + " does not support writing"); } } // If the user set content length to zero, we know there will not be a request body. httpEngine = newHttpEngine(method, null, null, null); } catch (IOException e) { httpEngineFailure = e; throw e; } }
private HttpEngine newHttpEngine(String method, StreamAllocation streamAllocation, RetryableSink requestBody, Response priorResponse) throws MalformedURLException, UnknownHostException { Request.Builder builder = new Request.Builder().url(Internal.instance.getHttpUrlChecked (getURL().toString())).method(method, HttpMethod.requiresRequestBody(method) ? EMPTY_REQUEST_BODY : null); Headers headers = this.requestHeaders.build(); int size = headers.size(); for (int i = 0; i < size; i++) { builder.addHeader(headers.name(i), headers.value(i)); } boolean bufferRequestBody = false; if (HttpMethod.permitsRequestBody(method)) { if (this.fixedContentLength != -1) { builder.header("Content-Length", Long.toString(this.fixedContentLength)); } else if (this.chunkLength > 0) { builder.header("Transfer-Encoding", "chunked"); } else { bufferRequestBody = true; } if (headers.get("Content-Type") == null) { builder.header("Content-Type", Client.FormMime); } } if (headers.get(Network.USER_AGENT) == null) { builder.header(Network.USER_AGENT, defaultUserAgent()); } Request request = builder.build(); OkHttpClient engineClient = this.client; if (!(Internal.instance.internalCache(engineClient) == null || getUseCaches())) { engineClient = this.client.clone().setCache(null); } return new HttpEngine(engineClient, request, bufferRequestBody, true, false, streamAllocation, requestBody, priorResponse); }
public final Builder method(String paramString, RequestBody paramRequestBody) { if (paramString.length() == 0) { throw new IllegalArgumentException("method == null || method.length() == 0"); } if ((paramRequestBody != null) && (!HttpMethod.permitsRequestBody(paramString))) { throw new IllegalArgumentException("method " + paramString + " must not have a request body."); } if ((paramRequestBody == null) && (HttpMethod.permitsRequestBody(paramString))) { paramRequestBody = RequestBody.create(null, Util.EMPTY_BYTE_ARRAY); } this.method = paramString; this.body = paramRequestBody; return this; }
private CacheRequest put(Response response) throws IOException { String requestMethod = response.request().method(); if (HttpMethod.invalidatesCache(response.request().method())) { try { remove(response.request()); } catch (IOException ignored) { // The cache cannot be written. } return null; } if (!requestMethod.equals("GET")) { // Don't cache non-GET responses. We're technically allowed to cache // HEAD requests and some POST requests, but the complexity of doing // so is high and the benefit is low. return null; } if (OkHeaders.hasVaryAll(response)) { return null; } Entry entry = new Entry(response); DiskLruCache.Editor editor = null; try { editor = cache.edit(urlToKey(response.request())); if (editor == null) { return null; } entry.writeTo(editor); return new CacheRequestImpl(editor); } catch (IOException e) { abortQuietly(editor); return null; } }
@Override public void setRequestMethod(String method) throws ProtocolException { if (!HttpMethod.METHODS.contains(method)) { throw new ProtocolException( "Expected one of " + HttpMethod.METHODS + " but was " + method); } this.method = method; }
@Override public boolean maybeRemove(Request request) { if (HttpMethod.invalidatesCache(request.method())) { try { cache.remove(urlToKey(request)); } catch (IOException ignored) { // The cache cannot be written. } return true; } return false; }
public Request buildRequest(String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, Object> formParams, String[] authNames, ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { updateParamsForAuth(authNames, queryParams, headerParams); final String url = buildUrl(path, queryParams); final Request.Builder reqBuilder = new Request.Builder().url(url); processHeaderParams(headerParams, reqBuilder); String contentType = (String) headerParams.get("Content-Type"); // ensuring a default content type if (contentType == null) { contentType = "application/json"; } RequestBody reqBody; if (!HttpMethod.permitsRequestBody(method)) { reqBody = null; } else if ("application/x-www-form-urlencoded".equals(contentType)) { reqBody = buildRequestBodyFormEncoding(formParams); } else if ("multipart/form-data".equals(contentType)) { reqBody = buildRequestBodyMultipart(formParams); } else if (body == null) { if ("DELETE".equals(method)) { // allow calling DELETE without sending a request body reqBody = null; } else { // use an empty request body (for POST, PUT and PATCH) reqBody = RequestBody.create(MediaType.parse(contentType), ""); } } else { reqBody = serialize(body, contentType); } Request request = null; if(progressRequestListener != null && reqBody != null) { ProgressRequestBody progressRequestBody = new ProgressRequestBody(reqBody, progressRequestListener); request = reqBuilder.method(method, progressRequestBody).build(); } else { request = reqBuilder.method(method, reqBody).build(); } return request; }
/** * Build HTTP call with the given options. * * @param path The sub-path of the HTTP URL * @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE" * @param queryParams The query parameters * @param body The request body object * @param headerParams The header parameters * @param formParams The form parameters * @param authNames The authentications to apply * @param progressRequestListener Progress request listener * @return The HTTP call * @throws ApiException If fail to serialize the request body object */ public Call buildCall(String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, Object> formParams, String[] authNames, ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { updateParamsForAuth(authNames, queryParams, headerParams); final String url = buildUrl(path, queryParams); final Request.Builder reqBuilder = new Request.Builder().url(url); processHeaderParams(headerParams, reqBuilder); String contentType = (String) headerParams.get("Content-Type"); // ensuring a default content type if (contentType == null) { contentType = "application/json"; } RequestBody reqBody; if (!HttpMethod.permitsRequestBody(method)) { reqBody = null; } else if ("application/x-www-form-urlencoded".equals(contentType)) { reqBody = buildRequestBodyFormEncoding(formParams); } else if ("multipart/form-data".equals(contentType)) { reqBody = buildRequestBodyMultipart(formParams); } else if (body == null) { if ("DELETE".equals(method)) { // allow calling DELETE without sending a request body reqBody = null; } else { // use an empty request body (for POST, PUT and PATCH) reqBody = RequestBody.create(MediaType.parse(contentType), ""); } } else { reqBody = serialize(body, contentType); } Request request = null; if(progressRequestListener != null && reqBody != null) { ProgressRequestBody progressRequestBody = new ProgressRequestBody(reqBody, progressRequestListener); request = reqBuilder.method(method, progressRequestBody).build(); } else { request = reqBuilder.method(method, reqBody).build(); } return httpClient.newCall(request); }
/** * Build an HTTP request with the given options. * * @param path The sub-path of the HTTP URL * @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE" * @param queryParams The query parameters * @param collectionQueryParams The collection query parameters * @param body The request body object * @param headerParams The header parameters * @param formParams The form parameters * @param authNames The authentications to apply * @param progressRequestListener Progress request listener * @return The HTTP request * @throws ApiException If fail to serialize the request body object */ public Request buildRequest(String path, String method, List<Pair> queryParams, List<Pair> collectionQueryParams, Object body, Map<String, String> headerParams, Map<String, Object> formParams, String[] authNames, ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { updateParamsForAuth(authNames, queryParams, headerParams); final String url = buildUrl(path, queryParams, collectionQueryParams); final Request.Builder reqBuilder = new Request.Builder().url(url); processHeaderParams(headerParams, reqBuilder); String contentType = (String) headerParams.get("Content-Type"); // ensuring a default content type if (contentType == null) { contentType = "application/json"; } RequestBody reqBody; if (!HttpMethod.permitsRequestBody(method)) { reqBody = null; } else if ("application/x-www-form-urlencoded".equals(contentType)) { reqBody = buildRequestBodyFormEncoding(formParams); } else if ("multipart/form-data".equals(contentType)) { reqBody = buildRequestBodyMultipart(formParams); } else if (body == null) { if ("DELETE".equals(method)) { // allow calling DELETE without sending a request body reqBody = null; } else { // use an empty request body (for POST, PUT and PATCH) reqBody = RequestBody.create(MediaType.parse(contentType), ""); } } else { reqBody = serialize(body, contentType); } Request request = null; if(progressRequestListener != null && reqBody != null) { ProgressRequestBody progressRequestBody = new ProgressRequestBody(reqBody, progressRequestListener); request = reqBuilder.method(method, progressRequestBody).build(); } else { request = reqBuilder.method(method, reqBody).build(); } return request; }
/** * Build an HTTP request with the given options. * * @param path The sub-path of the HTTP URL * @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE" * @param queryParams The query parameters * @param body The request body object * @param headerParams The header parameters * @param formParams The form parameters * @param authNames The authentications to apply * @param progressRequestListener Progress request listener * @return The HTTP request * @throws ApiException If fail to serialize the request body object */ public Request buildRequest(String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, Object> formParams, String[] authNames, ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { updateParamsForAuth(authNames, queryParams, headerParams); final String url = buildUrl(path, queryParams); final Request.Builder reqBuilder = new Request.Builder().url(url); processHeaderParams(headerParams, reqBuilder); String contentType = (String) headerParams.get("Content-Type"); // ensuring a default content type if (contentType == null) { contentType = "application/json"; } RequestBody reqBody; if (!HttpMethod.permitsRequestBody(method)) { reqBody = null; } else if ("application/x-www-form-urlencoded".equals(contentType)) { reqBody = buildRequestBodyFormEncoding(formParams); } else if ("multipart/form-data".equals(contentType)) { reqBody = buildRequestBodyMultipart(formParams); } else if (body == null) { if ("DELETE".equals(method)) { // allow calling DELETE without sending a request body reqBody = null; } else { // use an empty request body (for POST, PUT and PATCH) reqBody = RequestBody.create(MediaType.parse(contentType), ""); } } else { reqBody = serialize(body, contentType); } Request request = null; if(progressRequestListener != null && reqBody != null) { ProgressRequestBody progressRequestBody = new ProgressRequestBody(reqBody, progressRequestListener); request = reqBuilder.method(method, progressRequestBody).build(); } else { request = reqBuilder.method(method, reqBody).build(); } return request; }
@Override public LowLevelHttpResponse execute() throws IOException { // write content RequestBody requestBody = null; if (getStreamingContent() != null) { String contentType = getContentType(); if (contentType != null) { addHeader("Content-Type", contentType); } String contentEncoding = getContentEncoding(); if (contentEncoding != null) { addHeader("Content-Encoding", contentEncoding); } long contentLength = getContentLength(); if (contentLength >= 0) { addHeader("Content-Length", Long.toString(contentLength)); } // add request body if (HttpMethod.permitsRequestBody(method)) { // parse media type MediaType mediaType = null; if (contentType != null) { mediaType = MediaType.parse(contentType); } ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); getStreamingContent().writeTo(outputStream); requestBody = RequestBody.create( mediaType, outputStream.toByteArray() ); } else { // cannot add body because it would change a GET method to POST // for HEAD, OPTIONS, or TRACE it would throw a IllegalArgumentException Preconditions.checkArgument( contentLength == 0, "%s with non-zero content length is not supported", method); } } // send Request request = requestBuilder.method(method, requestBody).build(); Response response = client.newCall(request).execute(); return new OkHttpResponse(response); }
/** * Performs the request and returns the response. May return null if this * call was canceled. */ private Response getResponse() throws IOException { // Copy body metadata to the appropriate request headers. RequestBody body = request.body(); RetryableSink requestBodyOut = null; if (body != null) { Request.Builder requestBuilder = request.newBuilder(); 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"); } request = requestBuilder.build(); } else if (HttpMethod.hasRequestBody(request.method())) { requestBodyOut = Util.emptySink(); } // Create the initial HTTP engine. Retries and redirects need new engine for each attempt. engine = new HttpEngine(client, request, false, null, null, requestBodyOut, null); while (true) { if (canceled) return null; try { engine.sendRequest(); if (request.body() != null) { BufferedSink sink = engine.getBufferedRequestBody(); request.body().writeTo(sink); } engine.readResponse(); } catch (IOException e) { HttpEngine retryEngine = engine.recover(e, null); if (retryEngine != null) { // sync up the rquest request = engine.getRequest(); engine = retryEngine; continue; } // Give up; recovery is not possible. throw e; } Response response = engine.getResponse(); Request followUp = engine.followUpRequest(); if (followUp == null) { engine.releaseConnection(); return response.newBuilder() .body(new RealResponseBody(response, engine.getResponseBody())) .build(); } if (engine.getResponse().isRedirect() && ++redirectionCount > MAX_REDIRECTS) { throw new ProtocolException("Too many redirects: " + redirectionCount); } if (!engine.sameConnection(followUp.url())) { engine.releaseConnection(); } Connection connection = engine.close(); request = followUp; engine = new HttpEngine(client, request, false, connection, null, null, response); } }
private HttpEngine newHttpEngine(String method, Connection connection, RetryableSink requestBody, Response priorResponse) { Request.Builder builder = new Request.Builder() .url(getURL()) .method(method, null /* No body; that's passed separately. */); Headers headers = requestHeaders.build(); for (int i = 0; i < headers.size(); i++) { builder.addHeader(headers.name(i), headers.value(i)); } boolean bufferRequestBody = false; if (HttpMethod.hasRequestBody(method)) { // Specify how the request body is terminated. if (fixedContentLength != -1) { builder.header("Content-Length", Long.toString(fixedContentLength)); } else if (chunkLength > 0) { builder.header("Transfer-Encoding", "chunked"); } else { bufferRequestBody = true; } // Add a content type for the request body, if one isn't already present. if (headers.get("Content-Type") == null) { builder.header("Content-Type", "application/x-www-form-urlencoded"); } } if (headers.get("User-Agent") == null) { builder.header("User-Agent", defaultUserAgent()); } Request request = builder.build(); // If we're currently not using caches, make sure the engine's client doesn't have one. OkHttpClient engineClient = client; if (Internal.instance.internalCache(engineClient) != null && !getUseCaches()) { engineClient = client.clone().setCache(null); } request = client.preConfigRequest(request); return new HttpEngine(engineClient, request, bufferRequestBody, connection, null, requestBody, priorResponse); }
private HttpEngine newHttpEngine(String method, Connection connection, RetryableSink requestBody, Response priorResponse) { // OkHttp's Call API requires a placeholder body; the real body will be streamed separately. RequestBody placeholderBody = HttpMethod.requiresRequestBody(method) ? EMPTY_REQUEST_BODY : null; Request.Builder builder = new Request.Builder() .url(getURL()) .method(method, placeholderBody); Headers headers = requestHeaders.build(); for (int i = 0, size = headers.size(); i < size; i++) { builder.addHeader(headers.name(i), headers.value(i)); } boolean bufferRequestBody = false; if (HttpMethod.permitsRequestBody(method)) { // Specify how the request body is terminated. if (fixedContentLength != -1) { builder.header("Content-Length", Long.toString(fixedContentLength)); } else if (chunkLength > 0) { builder.header("Transfer-Encoding", "chunked"); } else { bufferRequestBody = true; } // Add a content type for the request body, if one isn't already present. if (headers.get("Content-Type") == null) { builder.header("Content-Type", "application/x-www-form-urlencoded"); } } if (headers.get("User-Agent") == null) { builder.header("User-Agent", defaultUserAgent()); } Request request = builder.build(); // If we're currently not using caches, make sure the engine's client doesn't have one. OkHttpClient engineClient = client; if (Internal.instance.internalCache(engineClient) != null && !getUseCaches()) { engineClient = client.clone().setCache(null); } return new HttpEngine(engineClient, request, bufferRequestBody, true, false, connection, null, requestBody, priorResponse); }