Java Code Examples for com.squareup.okhttp.Request#Builder
The following examples show how to use
com.squareup.okhttp.Request#Builder .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: QiitaBaseApi.java From Qiitanium with MIT License | 6 votes |
protected <T> ResponseDto<T> execute(Request.Builder request, Type type) { try { final Response response = execute(request); if (!response.isSuccessful()) { throw new WebAccessException(response.code(), fetchErrorMessage(response)); } final ResponseDto<T> dto = new ResponseDto<T>(); dto.body = objectify(response, type); dto.page = fetchPagenationHeader(response); return dto; } catch (IOException ioe) { throw new DataAccessException(ioe); } }
Example 2
Source File: FindWiFiImpl.java From find-client-android with MIT License | 6 votes |
@Override protected Void doInBackground(Void... params) { try { Request.Builder requestBuilder = new Request.Builder() .url(serverAddr + urlPart); switch (method) { case PUT: requestBuilder.put(RequestBody.create(MEDIA_TYPE_JSON, json)); break; case POST: requestBuilder.post(RequestBody.create(MEDIA_TYPE_JSON, json)); break; case DELETE: requestBuilder.delete(RequestBody.create(MEDIA_TYPE_JSON, json)); break; default: break; } Request request = requestBuilder.build(); httpClient.newCall(request).enqueue(new HttpCallback(callback)); } catch (Exception e) { Log.e(TAG, "IOException", e); } return null; }
Example 3
Source File: RPC.java From flickr-uploader with GNU General Public License v2.0 | 5 votes |
@Override public Response intercept(Chain chain) throws IOException { Request originalRequest = chain.request(); Request.Builder builder = originalRequest.newBuilder() .removeHeader("User-Agent") .addHeader("User-Agent", "rafali-android-rpc gzip") .addHeader("rafali-versionCode", "" + Config.VERSION) .addHeader("rafali-packageName", FlickrUploader.getAppContext().getPackageName()) .addHeader("Content-Type", "application/json;charset=UTF-8"); Request requestWithUserAgent = builder.build(); return chain.proceed(requestWithUserAgent); }
Example 4
Source File: ConcreteOneDriveSDK.java From OneDriveJavaSDK with MIT License | 5 votes |
/** * Perform the HTTP request to the OneDrive API. * * @param preparedRequest * @return OneResponse * @throws IOException */ public OneResponse makeRequest(PreparedRequest preparedRequest) throws IOException, OneDriveAuthenticationException { if(!this.session.isAuthenticated()){ throw new OneDriveAuthenticationException("Session is no longer valid. Look for a failure of the refresh Thread in the log."); } String url; RequestBody body = null; if (preparedRequest.getBody() != null) { body = RequestBody.create(null, preparedRequest.getBody()); } if (isCompleteURL(preparedRequest.getPath())) { url = preparedRequest.getPath(); } else { url = String.format("%s%s?access_token=%s", this.baseUrl, preparedRequest.getPath(), session.getAccessToken()); } logger.debug(String.format("making request to %s",url)); Request.Builder builder = new Request.Builder().method(preparedRequest.getMethod(), body).url(url); for (String key : preparedRequest.getHeader().keySet()) { builder.addHeader(key, preparedRequest.getHeader().get(key)); } //Add auth permanently to header with redirection builder.header("Authorization", "bearer " + session.getAccessToken()); Request request = builder.build(); Response getDrivesResponse = session.getClient().newCall(request).execute(); return new ConcreteOneResponse(getDrivesResponse); }
Example 5
Source File: AbstractRequestBuilderBuildMethodInterceptor.java From pinpoint with Apache License 2.0 | 5 votes |
@Override public void before(Object target, Object[] args) { if (isDebug) { logger.beforeInterceptor(target, args); } final Trace trace = traceContext.currentRawTraceObject(); if (trace == null) { return; } try { if (!(target instanceof Request.Builder)) { return; } final Request.Builder builder = ((Request.Builder) target); if (!trace.canSampled()) { if (builder != null) { this.requestTraceWriter.write(builder); } return; } final InterceptorScopeInvocation invocation = interceptorScope.getCurrentInvocation(); final Object attachment = getAttachment(invocation); if (!(attachment instanceof TraceId)) { if (isDebug) { logger.debug("Invalid interceptor scope invocation. {}", invocation); } return; } final TraceId nextId = (TraceId) attachment; final String host = toHost(target); this.requestTraceWriter.write(builder, nextId, host); } catch (Throwable t) { logger.warn("Failed to BEFORE process. {}", t.getMessage(), t); } }
Example 6
Source File: BaseApi.java From rox-android with Apache License 2.0 | 5 votes |
private Request.Builder buildRequestForJson(String url) { return new Request.Builder() .url(url) .header(Header.ACCEPT.getValue(), ContentType.APPLICATION_JSON.getMimeType()) .header(Header.ACCEPT_LANGUAGE.getValue(), Locale.getDefault().getLanguage()) .header(Header.ACCEPT_CHARSET.getValue(), Charset.UTF_8.getValue()); }
Example 7
Source File: OkHttpGetRequest.java From meiShi with Apache License 2.0 | 5 votes |
@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(); }
Example 8
Source File: WXOkHttpDispatcher.java From weex with Apache License 2.0 | 5 votes |
@Override public void handleMessage(Message msg) { int what = msg.what; switch (what) { case SUBMIT: { WXHttpTask task = (WXHttpTask) msg.obj; Request.Builder builder = new Request.Builder().header("User-Agent", "WeAppPlusPlayground/1.0").url(task.url); WXHttpResponse httpResponse = new WXHttpResponse(); try { Response response = mOkHttpClient.newCall(builder.build()).execute(); httpResponse.code = response.code(); httpResponse.data = response.body().bytes(); task.response = httpResponse; mUiHandler.sendMessage(mUiHandler.obtainMessage(1, task)); } catch (Throwable e) { e.printStackTrace(); httpResponse.code = 1000; mUiHandler.sendMessage(mUiHandler.obtainMessage(1, task)); } } break; default: break; } }
Example 9
Source File: HttpClient.java From zsync4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
Request buildRequest(URI uri, Map<String, ? extends Credentials> credentials, List<ContentRange> ranges) { final Builder builder = new Request.Builder(); builder.url(uri.toString()); if (this.basicChallengeReceived.contains(uri.getHost()) && "https".equals(uri.getScheme())) { final Credentials creds = credentials.get(uri.getHost()); if (creds != null) { builder.header("Authorization", creds.basic()); } } if (!ranges.isEmpty()) { builder.addHeader("Range", "bytes=" + on(',').join(ranges)); } return builder.build(); }
Example 10
Source File: ListProjectsTask.java From Android-nRF-Beacon-for-Eddystone with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Override protected Void doInBackground(Void... params) { final String token = mToken; Request.Builder requestBuilder = new Request.Builder() .header(AUTHORIZATION, BEARER + token) .url(url); Request request = requestBuilder.build(); httpClient.newCall(request).enqueue(new HttpCallback(callback)); return null; }
Example 11
Source File: WebApi.java From Qiitanium with MIT License | 4 votes |
protected Request.Builder delete(Uri url) { return request(url).delete(); }
Example 12
Source File: PostFileRequest.java From NewsMe with Apache License 2.0 | 4 votes |
@Override protected Request buildRequest(Request.Builder builder, RequestBody requestBody) { return builder.post(requestBody).build(); }
Example 13
Source File: WebApi.java From Qiitanium with MIT License | 4 votes |
protected Request.Builder put(Uri url, RequestBody body) { return request(url).put(body); }
Example 14
Source File: GetRequest.java From NewsMe with Apache License 2.0 | 4 votes |
@Override protected Request buildRequest(Request.Builder builder, RequestBody requestBody) { return builder.get().build(); }
Example 15
Source File: RestVolleyDownload.java From RestVolley with Apache License 2.0 | 4 votes |
/** * constructor with specified {@link RequestEngine}. * @param requestEngine {@link RequestEngine} */ public RestVolleyDownload(RequestEngine requestEngine) { mRequestBuilder = new Request.Builder(); mRequestBuilder.get(); mOkHttpClient = requestEngine.okHttpClient; }
Example 16
Source File: HttpURLConnectionImpl.java From apiman with Apache License 2.0 | 4 votes |
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); }
Example 17
Source File: WebApi.java From Qiitanium with MIT License | 4 votes |
protected Request.Builder delete(Uri.Builder url) { return request(url).delete(); }
Example 18
Source File: Api.java From materialup with Apache License 2.0 | 4 votes |
@Override public Response intercept(Chain chain) throws IOException { String host = chain.request().url().getHost(); Request.Builder builder = chain.request().newBuilder(); String xsrf = null; if (isMatchHost(host)) { Set<String> preferences = App.getPref().getStringSet(PREF_COOKIES, new HashSet<>()); boolean hasToken = false; for (String cookie : preferences) { if (TextUtils.isEmpty(cookie)) { continue; } if (cookie.contains(Api.PREF_TOKEN)) { hasToken = true; } builder.addHeader("Cookie", cookie); if (cookie.contains(CK_XSRFTOKEN)) { int start = cookie.indexOf(CK_XSRFTOKEN) + CK_XSRFTOKEN.length(); int end = cookie.indexOf(";", start); xsrf = cookie.substring(start + 1, end); xsrf = URLDecoder.decode(xsrf, "UTF-8"); if (BuildConfig.DEBUG) { Log.v("OkHttp", "XSRF: " + xsrf); // This is done so I know which headers are being added; this interceptor is used after the normal logging of OkHttp } } if (BuildConfig.DEBUG) { Log.v("OkHttp", "Adding Header: " + cookie); // This is done so I know which headers are being added; this interceptor is used after the normal logging of OkHttp } } if (!hasToken) { String token = App.getPref().getString(PREF_TOKEN, null); if (!TextUtils.isEmpty(token)) { builder.addHeader("Cookie", PREF_TOKEN + "=" + token); } } } if (!TextUtils.isEmpty(xsrf)) { builder.addHeader("X-XSRF-TOKEN", xsrf); } builder.addHeader("User-Agent", getUserAgent(App.getIns())); Response originalResponse = chain.proceed(builder.build()); // save new cookie if (isMatchHost(host)) { if (!originalResponse.headers("Set-Cookie").isEmpty()) { HashSet<String> cookies = new HashSet<>(); for (String header : originalResponse.headers("Set-Cookie")) { cookies.add(header); } App.getPref().edit() .putStringSet(PREF_COOKIES, cookies) .apply(); } } return originalResponse; }
Example 19
Source File: ApiKeyAuth.java From huaweicloud-cs-sdk with Apache License 2.0 | 4 votes |
public Request applyToParams(Request request) { if (serviceName == null || region == null || accessKey == null || secretKey == null) { return request; } DefaultRequest reqForSigner = new DefaultRequest(this.serviceName); try { reqForSigner.setEndpoint(request.uri()); reqForSigner.setHttpMethod(HttpMethodName.valueOf(request.method())); if(!projectId.isEmpty()) { reqForSigner.addHeader("X-Project-Id", projectId); } // add query string String urlString = request.urlString(); if (urlString.contains("?")) { String parameters = urlString.substring(urlString.indexOf("?") + 1); Map<String, String> parametersMap = new HashMap<>(); if (!parameters.isEmpty()) { for (String p : parameters.split("&")) { String key = p.split("=")[0]; String value = p.split("=")[1]; parametersMap.put(key, value); } reqForSigner.setParameters(parametersMap); } } // add body if (request.body() != null) { Request copy = request.newBuilder().build(); Buffer buffer = new Buffer(); copy.body().writeTo(buffer); reqForSigner.setContent(new ByteArrayInputStream(buffer.readByteArray())); } Signer signer = SignerFactory.getSigner(serviceName, region); signer.sign(reqForSigner, new BasicCredentials(this.accessKey, this.secretKey)); Request.Builder builder = request.newBuilder(); builder.headers(Headers.of(reqForSigner.getHeaders())); return builder.build(); } catch (Exception e) { e.printStackTrace(); } return request; }
Example 20
Source File: WebApi.java From Qiitanium with MIT License | 4 votes |
protected Request.Builder request(Uri.Builder url) { return request(url.build()); }