/** * 构造GET请求对象 * * @param url * @param params * @return */ private Request buildGetRequest(String url, Map<String, Object> params) { HttpUrl fullUrl = buildUrl(url, params); Request.Builder builder = new Request.Builder().url(fullUrl); wrapHttpHeader(builder, url); builder.tag(url); return builder.build(); }
public Response send(final Request.Builder requestBuilder, StringMap headers) throws QiniuException { if (headers != null) { headers.forEach( new StringMap.Consumer() { @Override public void accept(String key, Object value) { requestBuilder.header(key, value.toString()); } }); } requestBuilder.header("User-Agent", userAgent()); long start = System.currentTimeMillis(); com.squareup.okhttp.Response res = null; Response r; double duration = (System.currentTimeMillis() - start) / 1000.0; IpTag tag = new IpTag(); try { res = httpClient.newCall(requestBuilder.tag(tag).build()).execute(); } catch (IOException e) { e.printStackTrace(); throw new QiniuException(e); } r = Response.create(res, tag.ip, duration); if (r.statusCode >= 300) { throw new QiniuException(r); } return r; }
/** * Fetch the list of movies from YTS * * @param currentList Current shown list to be extended * @param requestBuilder Request to be executed * @param callback Network callback * @return Call */ private Call fetchList( final ArrayList<Media> currentList, final Request.Builder requestBuilder, final Filters filters, final Callback callback) { requestBuilder.addHeader("Host", "xor.image.yt"); return enqueue( requestBuilder.build(), new com.squareup.okhttp.Callback() { @Override public void onFailure(Request request, IOException e) { if (generateFallback(requestBuilder)) { fetchList(currentList, requestBuilder, filters, callback); } else { callback.onFailure(e); } } @Override public void onResponse(Response response) throws IOException { if (response.isSuccessful()) { String responseStr; try { responseStr = response.body().string(); } catch (SocketException e) { onFailure(response.request(), new IOException("Socket failed")); return; } YTSReponse result; try { result = mGson.fromJson(responseStr, YTSReponse.class); } catch (IllegalStateException e) { onFailure(response.request(), new IOException("JSON Failed")); return; } catch (JsonSyntaxException e) { onFailure(response.request(), new IOException("JSON Failed")); return; } if (result.status != null && result.status.equals("error")) { callback.onFailure(new NetworkErrorException(result.status_message)); } else if (result.data != null && ((result.data.get("movies") != null && ((ArrayList<LinkedTreeMap<String, Object>>) result.data.get("movies")) .size() <= 0) || ((Double) result.data.get("movie_count")).intValue() <= currentList.size())) { callback.onFailure(new NetworkErrorException("No movies found")); } else { ArrayList<Media> formattedData = result.formatForPopcorn(currentList); callback.onSuccess(filters, formattedData, true); return; } } onFailure(response.request(), new IOException("Couldn't connect to YTS")); } }); }
private HttpEngine newHttpEngine( String method, Connection connection, RetryableOutputStream requestBody) throws IOException { 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; if (fixedContentLength != -1) { bufferRequestBody = false; builder.header("Content-Length", Long.toString(fixedContentLength)); } else if (chunkLength > 0) { bufferRequestBody = false; builder.header("Transfer-Encoding", "chunked"); } else { bufferRequestBody = true; } 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 (engineClient.getOkResponseCache() != null && !getUseCaches()) { engineClient = client.clone().setOkResponseCache(null); } return new HttpEngine(engineClient, request, bufferRequestBody, connection, requestBody); }
@Override public Call getDetail(String videoId, Callback callback) { Request.Builder requestBuilder = new Request.Builder(); requestBuilder.url(API_URL + "movie_details.json?movie_id=" + videoId); requestBuilder.addHeader("Host", "xor.image.yt"); requestBuilder.tag(MEDIA_CALL); return fetchDetail(requestBuilder, callback); }
@Override public Request buildRequest() { Request.Builder builder = new Request.Builder(); String url = getUrl() + "?key=" + cacHttpClient.getApiKey() + "&login=" + cacHttpClient.getLogin(); builder.url(url); return builder.build(); }
/** * 设置Http Header * * @param builder */ private void wrapHttpHeader(Request.Builder builder, String url) { for (Map.Entry<String, String> item : this.headers) { builder.addHeader(item.getKey(), item.getValue()); } final String signRequest = appSession.signRequest(url); builder.addHeader(HEADER_X_SIGN, signRequest); builder.addHeader(HEADER_ACCEPT, APPLICATION_X_PROTOBUF); builder.addHeader(HEADER_USER_AGENT, this.userAgent); // Timber.e("signRequest: %s %s", url, signRequest); }
/** * Set header parameters to the request builder, including default headers. * * @param headerParams Header parameters in the ofrm of Map * @param reqBuilder Reqeust.Builder */ public void processHeaderParams(Map<String, String> headerParams, Request.Builder reqBuilder) { for (Entry<String, String> param : headerParams.entrySet()) { reqBuilder.header(param.getKey(), parameterToString(param.getValue())); } for (Entry<String, String> header : defaultHeaderMap.entrySet()) { if (!headerParams.containsKey(header.getKey())) { reqBuilder.header(header.getKey(), parameterToString(header.getValue())); } } }
@Override protected Request buildRequest() { if (TextUtils.isEmpty(url)) { throw new IllegalArgumentException("url can not be empty!"); } Request.Builder builder = new Request.Builder(); appendHeaders(builder, headers); builder.url(url).tag(tag).post(requestBody); return builder.build(); }
/** * 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); }
@Override protected Request buildRequest() { if (TextUtils.isEmpty(url)) { throw new IllegalArgumentException("url can not be empty!"); } // append params , if necessary url = appendParams(url, params); Request.Builder builder = new Request.Builder(); // add headers , if necessary appendHeaders(builder, headers); builder.url(url).tag(tag); return builder.build(); }
private boolean generateFallback(Request.Builder requestBuilder) { String url = requestBuilder.build().urlString(); if (url.contains(MIRROR_URL2)) { return false; } else if (url.contains(MIRROR_URL)) { url = url.replace(MIRROR_URL, MIRROR_URL2); CURRENT_URL = MIRROR_URL2; } else { url = url.replace(API_URL, MIRROR_URL); CURRENT_URL = MIRROR_URL; } requestBuilder.url(url); return true; }
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { OkHttpClient client = okHttpClient.clone(); int timeoutMs = request.getTimeoutMs(); client.setConnectTimeout(timeoutMs, TimeUnit.MILLISECONDS); client.setReadTimeout(timeoutMs, TimeUnit.MILLISECONDS); client.setWriteTimeout(timeoutMs, TimeUnit.MILLISECONDS); com.squareup.okhttp.Request.Builder okHttpRequestBuilder = new com.squareup.okhttp.Request.Builder(); okHttpRequestBuilder.url(request.getUrl()); Map<String, String> headers = request.getHeaders(); for (final String name : headers.keySet()) { okHttpRequestBuilder.addHeader(name, headers.get(name)); } for (final String name : additionalHeaders.keySet()) { okHttpRequestBuilder.addHeader(name, additionalHeaders.get(name)); } setConnectionParametersForRequest(okHttpRequestBuilder, request); com.squareup.okhttp.Request okHttpRequest = okHttpRequestBuilder.build(); Call okHttpCall = client.newCall(okHttpRequest); Response okHttpResponse = okHttpCall.execute(); StatusLine responseStatus = new BasicStatusLine( parseProtocol(okHttpResponse.protocol()), okHttpResponse.code(), okHttpResponse.message()); BasicHttpResponse response = new BasicHttpResponse(responseStatus); response.setEntity(entityFromOkHttpResponse(okHttpResponse)); Headers responseHeaders = okHttpResponse.headers(); for (int i = 0, len = responseHeaders.size(); i < len; i++) { final String name = responseHeaders.name(i), value = responseHeaders.value(i); if (name != null) { response.addHeader(new BasicHeader(name, value)); } } return response; }
private APIResponse get_single(final String urlString, int expectedReturnCode) { if (!NetworkUtils.isOnline(context)) { return new APIResponse(context); } if (AppConstants.VERBOSE_LOG) { Log.d(this.getClass().getName(), "API GET " + urlString); } Request.Builder requestBuilder = new Request.Builder().url(urlString); addCookieHeader(requestBuilder); requestBuilder.header("User-Agent", this.customUserAgent); return new APIResponse(context, httpClient, requestBuilder.build(), expectedReturnCode); }
@Override public Response intercept(Chain chain) throws IOException { Request originalRequest = chain.request(); Request.Builder request = originalRequest.newBuilder(); if (originalRequest.header("fresh") != null) { request.cacheControl(CacheControl.FORCE_NETWORK); } Response response = chain.proceed(request.build()); return response .newBuilder() .removeHeader("Pragma") .removeHeader("Cache-Control") .header("Cache-Control", cacheControl()) .build(); }
@Override protected String doInBackground(Void... params) { try { OkHttpClient okHttpClient = new OkHttpClient(); Request.Builder builder = new Request.Builder(); Request request = builder.url(myURL).build(); Response response = okHttpClient.newCall(request).execute(); return response.body().string(); } catch (Exception e) { Log.d("Spinner", "e doInBack ==> " + e.toString()); return null; } }
private void call( Request request, final Net.Parser<T> parser, final Net.Callback<T> callback, final Object tag) { Request.Builder builder = request.newBuilder(); if (tag != null) builder.tag(tag); // 在这里添加头部文件 LinkedHashMap<String, String> map = headers(); if (map != null && !map.isEmpty()) { for (Iterator<String> iterator = map.keySet().iterator(); iterator.hasNext(); ) { String key = iterator.next(); builder.addHeader(key, map.get(key)); } request = builder.build(); } OkHttpClient client = mClient.clone(); client.setConnectTimeout(20, TimeUnit.SECONDS); final Call call = client.newCall(request); call.enqueue( new Callback() { @Override public void onFailure(Request request, final IOException e) { final String msg = e.getMessage(); mHandler.post( new Runnable() { @Override public void run() { onError(callback, msg); } }); } @Override public void onResponse(final Response response) throws IOException { final String resp = response.body().string(); mHandler.post( new Runnable() { @Override public void run() { onNetResponse(parser, callback, resp); } }); } }); }
private void addCookieHeader(Request.Builder requestBuilder) { SharedPreferences preferences = context.getSharedPreferences(PrefConstants.PREFERENCES, 0); String cookie = preferences.getString(PrefConstants.PREF_COOKIE, null); if (cookie != null) { requestBuilder.header("Cookie", cookie); } }
public void connect() throws IOException { LOG.log(Level.FINE, "connect"); disconnect(); // No support for ws:// or ws:// in okhttp. See https://github.com/square/okhttp/issues/1652 final String httpUrl = this.endpointUri.replaceFirst("^ws:", "http:").replaceFirst("^wss:", "https:"); Request.Builder builder = new Request.Builder().url(httpUrl); if (socketConnectionRequestHeaders != null) for (Map.Entry<String, String> entry : socketConnectionRequestHeaders.entrySet()) builder.addHeader(entry.getKey(), entry.getValue()); final Request request = builder.build(); final WebSocketCall wsCall = WebSocketCall.create(httpClient, request); wsCall.enqueue(wsListener); }
private APIResponse post_single(String urlString, RequestBody formBody) { if (!NetworkUtils.isOnline(context)) { return new APIResponse(context); } if (AppConstants.VERBOSE_LOG) { Log.d(this.getClass().getName(), "API POST " + urlString); Log.d(this.getClass().getName(), "post body: " + formBody.toString()); } Request.Builder requestBuilder = new Request.Builder().url(urlString); addCookieHeader(requestBuilder); requestBuilder.post(formBody); return new APIResponse(context, httpClient, requestBuilder.build()); }
@SuppressWarnings("deprecation") private static void setConnectionParametersForRequest( com.squareup.okhttp.Request.Builder builder, Request<?> request) throws IOException, AuthFailureError { switch (request.getMethod()) { case Request.Method.DEPRECATED_GET_OR_POST: // Ensure backwards compatibility. // Volley assumes a request with a null body is a GET. byte[] postBody = request.getPostBody(); if (postBody != null) { builder.post( RequestBody.create(MediaType.parse(request.getPostBodyContentType()), postBody)); } break; case Request.Method.GET: builder.get(); break; case Request.Method.DELETE: builder.delete(); break; case Request.Method.POST: builder.post(createRequestBody(request)); break; case Request.Method.PUT: builder.put(createRequestBody(request)); break; case Request.Method.HEAD: builder.head(); break; case Request.Method.OPTIONS: builder.method("OPTIONS", null); break; case Request.Method.TRACE: builder.method("TRACE", null); break; case Request.Method.PATCH: builder.patch(createRequestBody(request)); break; default: throw new IllegalStateException("Unknown method type."); } }
private Request networkRequest(Request request) { com.squareup.okhttp.Request.Builder builder = request.newBuilder(); if (request.header("Host") == null) { builder.header("Host", Util.hostHeader(request.httpUrl())); } if ((connection == null || connection.getProtocol() != Protocol.HTTP_1_0) && request.header("Connection") == null) { builder.header("Connection", "Keep-Alive"); } if (request.header("Accept-Encoding") == null) { transparentGzip = true; builder.header("Accept-Encoding", "gzip"); } CookieHandler cookiehandler = client.getCookieHandler(); if (cookiehandler != null) { java.util.Map map = OkHeaders.toMultimap(builder.build().headers(), null); OkHeaders.addCookies(builder, cookiehandler.get(request.uri(), map)); } if (request.header("User-Agent") == null) { builder.header("User-Agent", Version.userAgent()); } return builder.build(); }
private static Request transformRequest(HttpRequest request, Object tag) { Request.Builder builder = new Request.Builder(); RequestLine requestLine = request.getRequestLine(); String method = requestLine.getMethod(); builder.url(requestLine.getUri()); String contentType = null; for (Header header : request.getAllHeaders()) { String name = header.getName(); if ("Content-Type".equals(name)) { contentType = header.getValue(); } else { builder.header(name, header.getValue()); } } RequestBody body = null; if (request instanceof HttpEntityEnclosingRequest) { HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity(); if (entity != null) { // Wrap the entity in a custom Body which takes care of the content, length, and type. body = new HttpEntityBody(entity, contentType); Header encoding = entity.getContentEncoding(); if (encoding != null) { builder.header(encoding.getName(), encoding.getValue()); } } } builder.method(method, body); builder.tag(tag); return builder.build(); }
public KoalaDownloadTask build() { Map<String, String> params = new HashMap<String, String>(); Map<String, String> headers = new HashMap<String, String>(); Request.Builder builder = new Request.Builder(); if (task.req != null) { KoalaHttpType type = task.req.getClass().getAnnotation(KoalaHttpType.class); if (type != null) { KoalaHttpUtils.getParams(task.req, task.req.getClass(), params, headers); if (headers.size() > 0) { Set<Map.Entry<String, String>> set = params.entrySet(); Iterator<Map.Entry<String, String>> iterator = set.iterator(); while (iterator.hasNext()) { Map.Entry<String, String> maEntry = iterator.next(); builder.addHeader(maEntry.getKey(), maEntry.getValue()); } } if (params.size() > 0) { if (type.value() == KoalaRequestType.GET) { task.url += ("?" + KoalaHttpUtils.getNameValuePair(params)); } else if (type.value() == KoalaRequestType.POST) { Set<Map.Entry<String, String>> set = params.entrySet(); Iterator<Map.Entry<String, String>> iterator = set.iterator(); FormEncodingBuilder bodyBuilder = new FormEncodingBuilder(); while (iterator.hasNext()) { Map.Entry<String, String> maEntry = iterator.next(); bodyBuilder.add(maEntry.getKey(), maEntry.getValue()); } builder.post(bodyBuilder.build()); } } } task.url = KoalaHttpUtils.buildUrl(task.url, task.req); KoalaRequestTag tag = task.req.getClass().getAnnotation(KoalaRequestTag.class); if (tag != null) { if (TextUtils.isEmpty(tag.value())) { builder.tag(SecurityMD5.ToMD5(task.url)); } else { builder.tag(tag); } } else { builder.tag(SecurityMD5.ToMD5(task.url)); } } else { builder.tag(SecurityMD5.ToMD5(task.url)); } builder.url(task.url); task.request = builder.build(); task.tag = task.request.tag(); return task; }
@Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); Optional<String> appAuthHeader = Optional.fromNullable(request.header(X_API_KEY_HEADER)); if (appAuthHeader.isPresent()) { final Request.Builder newRequest = request.newBuilder(); final String today = getTodayDate(); newRequest.addHeader(DATE_HEADER, today); Signature signature = getSigner() .sign( request.method(), request.urlString(), Collections.singletonMap(DATE_HEADER, today)); newRequest.addHeader(AUTHORIZATION_HEADER, signature.toString()); request = newRequest.build(); } return chain.proceed(request); }
/** POST request set up for making authorization calls */ public void authCall( String url, LinkedHashMap<String, String> body, HashMap<String, String> headerMap, Callback callback) { OkHttpClient client = new OkHttpClient(); Request.Builder requestBuilder = new Request.Builder(); for (Map.Entry<String, String> entry : headerMap.entrySet()) { requestBuilder.addHeader(entry.getKey(), entry.getValue()); } Request request = null; MediaType mediaType = MEDIA_TYPE_MARKDOWN; String bodyString = getBodyString(body, mediaType); HashMap<String, String> options = new HashMap<>(); options.put("addServer", "true"); String apiUrl = apiURL(url, options); request = requestBuilder.url(apiUrl).post(RequestBody.create(mediaType, bodyString)).build(); client.newCall(request).enqueue(callback); }
@Override protected String doInBackground(String... params) { OkHttpClient okHttpClient = new OkHttpClient(); Request.Builder builder = new Request.Builder(); Request request = builder.url("http://192.168.1.94/check2.php").build(); try { Response response = okHttpClient.newCall(request).execute(); if (response.isSuccessful()) { return response.body().string(); } else { return "Not Success - code : " + response.code(); } } catch (IOException e) { e.printStackTrace(); return "Error - " + e.getMessage(); } }
protected void populateHeaders(HttpRequest request, Request.Builder builder) { // OkHttp does not set the Accept header if not present in the request. // Make sure we send a flexible one. if (request.getFirstHeaderOrNull(ACCEPT) == null) { builder.addHeader(ACCEPT, "*/*"); } if (request.getFirstHeaderOrNull(USER_AGENT) == null) { builder.addHeader(USER_AGENT, DEFAULT_USER_AGENT); } for (Map.Entry<String, String> entry : request.getHeaders().entries()) { builder.addHeader(entry.getKey(), entry.getValue()); } if (request.getPayload() != null) { MutableContentMetadata md = request.getPayload().getContentMetadata(); for (Map.Entry<String, String> entry : contentMetadataCodec.toHeaders(md).entries()) { builder.addHeader(entry.getKey(), entry.getValue()); } } }
public static @NonNull SmashNetworkData perform(SmashRequest<?> request) throws SmashError { SmashNetworkData data = new SmashNetworkData(); try { 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; }
public boolean loginAs(String username) { ContentValues values = new ContentValues(); values.put(APIConstants.PARAMETER_USER, username); String urlString = APIConstants.URL_LOGINAS + "?" + builderGetParametersString(values); Log.i(this.getClass().getName(), "doing superuser swap: " + urlString); // This API returns a redirect that means the call worked, but we do not want to follow it. To // just get the cookie from the 302 and stop, we directly use a one-off OkHttpClient. Request.Builder requestBuilder = new Request.Builder().url(urlString); addCookieHeader(requestBuilder); OkHttpClient noredirHttpClient = new OkHttpClient(); noredirHttpClient.setFollowRedirects(false); try { Response response = noredirHttpClient.newCall(requestBuilder.build()).execute(); if (!response.isRedirect()) return false; String newCookie = response.header("Set-Cookie"); PrefsUtils.saveLogin(context, username, newCookie); } catch (IOException ioe) { return false; } return true; }