List of usage examples for com.squareup.okhttp Request.Builder url
HttpUrl url
To view the source code for com.squareup.okhttp Request.Builder url.
Click Source Link
From source file:cn.finalteam.okhttpfinal.HttpTask.java
License:Apache License
@Override protected ResponseData doInBackground(Void... voids) { Response response = null;//from w ww .j a va2 s . c o m ResponseData responseData = new ResponseData(); try { //OkHttpClient client = OkHttpFactory.getOkHttpClientFactory(timeout); String srcUrl = url; //Request Request.Builder builder = new Request.Builder(); switch (method) { case GET: url = Utils.getFullUrl(url, params.getUrlParams()); builder.get(); break; case DELETE: url = Utils.getFullUrl(url, params.getUrlParams()); builder.delete(); break; case HEAD: url = Utils.getFullUrl(url, params.getUrlParams()); builder.head(); break; case POST: RequestBody body = params.getRequestBody(); if (body != null) { builder.post(new ProgressRequestBody(body, callback)); } break; case PUT: RequestBody bodyPut = params.getRequestBody(); if (bodyPut != null) { builder.put(new ProgressRequestBody(bodyPut, callback)); } break; case PATCH: RequestBody bodyPatch = params.getRequestBody(); if (bodyPatch != null) { builder.put(new ProgressRequestBody(bodyPatch, callback)); } break; } builder.url(url).tag(srcUrl).headers(headers); Request request = builder.build(); if (Constants.DEBUG) { Logger.d("url=" + url + "?" + params.toString()); } // response = okHttpClient.newCall(request).execute(); } catch (Exception e) { if (Constants.DEBUG) { Logger.e("Exception=", e); } if (e instanceof SocketTimeoutException) { responseData.setTimeout(true); } else if (e instanceof InterruptedIOException && TextUtils.equals(e.getMessage(), "timeout")) { responseData.setTimeout(true); } } //? if (response != null) { responseData.setResponseNull(false); responseData.setCode(response.code()); responseData.setMessage(response.message()); responseData.setSuccess(response.isSuccessful()); String respBody = ""; try { respBody = response.body().string(); } catch (IOException e) { e.printStackTrace(); } responseData.setResponse(respBody); responseData.setHeaders(response.headers()); } else { responseData.setResponseNull(true); } return responseData; }
From source file:co.aquario.socialkit.search.youtube.YouTubeData.java
License:Open Source License
/** * Calculate the YouTube URL to load the video. Includes retrieving a token that YouTube * requires to play the video./*w ww . j a v a 2 s . c o m*/ * * @param quality quality of the video. 17=low, 18=high * @param fallback whether to fallback to lower quality in case the supplied quality is not available * @param videoId the id of the video * @return the url string that will retrieve the video * @throws java.io.IOException */ public static String calculateYouTubeUrl(String quality, boolean fallback, String videoId) throws IOException { String uriStr = ""; OkHttpClient client = VMApp.getHttpClient(); Request.Builder request = new Request.Builder(); request.url(YOUTUBE_VIDEO_INFORMATION_URL + videoId); Call call = client.newCall(request.build()); Response response = call.execute(); String infoStr = response.body().string(); String[] args = infoStr.split("&"); Map<String, String> argMap = new HashMap<String, String>(); for (String arg : args) { String[] valStrArr = arg.split("="); if (valStrArr.length >= 2) { argMap.put(valStrArr[0], URLDecoder.decode(valStrArr[1])); } } //Find out the URI string from the parameters //Populate the listStory of formats for the video String fmtList = ""; if (argMap.get("fmt_list") == null) { return ""; } else { fmtList = URLDecoder.decode(argMap.get("fmt_list"), "utf-8"); } ArrayList<co.aquario.socialkit.util.Format> formats = new ArrayList<co.aquario.socialkit.util.Format>(); if (null != fmtList) { String formatStrs[] = fmtList.split(","); for (String lFormatStr : formatStrs) { co.aquario.socialkit.util.Format format = new co.aquario.socialkit.util.Format(lFormatStr); formats.add(format); } } //Populate the listStory of streams for the video String streamList = argMap.get("url_encoded_fmt_stream_map"); if (null != streamList) { String streamStrs[] = streamList.split(","); ArrayList<VideoStream> streams = new ArrayList<VideoStream>(); for (String streamStr : streamStrs) { VideoStream lStream = new VideoStream(streamStr); streams.add(lStream); } //Search for the given format in the listStory of video formats // if it is there, select the corresponding stream // otherwise if fallback is requested, check for next lower format int formatId = Integer.parseInt(quality); co.aquario.socialkit.util.Format searchFormat = new co.aquario.socialkit.util.Format(formatId); while (!formats.contains(searchFormat) && fallback) { int oldId = searchFormat.getId(); int newId = getSupportedFallbackId(oldId); if (oldId == newId) { break; } searchFormat = new co.aquario.socialkit.util.Format(newId); } int index = formats.indexOf(searchFormat); if (index >= 0) { VideoStream searchStream = streams.get(index); uriStr = searchStream.getUrl(); } } //Return the URI string. It may be null if the format (or a fallback format if enabled) // is not found in the listStory of formats for the video return uriStr; }
From source file:co.paralleluniverse.fibers.okhttp.CallTest.java
License:Open Source License
@Test public void invalidPort() throws Exception { Request.Builder requestBuilder = new Request.Builder(); try {// w ww.jav a 2 s . c o m requestBuilder.url("http://localhost:65536/"); fail(); } catch (IllegalArgumentException expected) { assertEquals(expected.getMessage(), "unexpected url: http://localhost:65536/"); } }
From source file:com.ae.apps.pnrstatus.service.NetworkService.java
License:Open Source License
public String doPostRequest(final String targetUrl, final Map<String, String> headers, final Map<String, String> params) throws StatusException { //RequestBody requestBody = RequestBody.create(WEB_FORM, ""); try {/* ww w .j a v a2s. c o m*/ Request.Builder requestBuilder = new Request.Builder().url(targetUrl); if (null != headers) { for (String key : headers.keySet()) { requestBuilder.addHeader(key, String.valueOf(headers.get(key))); } } //-- FormEncodingBuilder formEncodingBuilder = new FormEncodingBuilder(); if (null != params) { for (String key : params.keySet()) { formEncodingBuilder.add(key, String.valueOf(params.get(key))); } } RequestBody formBody = formEncodingBuilder.build(); Request request = requestBuilder.url(targetUrl).post(formBody).build(); Response response = client.newCall(request).execute(); return response.body().string(); } catch (IOException ex) { throw new StatusException(ex.getMessage(), StatusException.ErrorCodes.URL_ERROR); } }
From source file:com.aix.city.comm.OkHttpStack.java
License:Open Source License
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { OkHttpClient client = mClient.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)); }// www . ja v a 2 s. c om 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; }
From source file:com.alibaba.weex.commons.adapter.DefaultWebSocketAdapter.java
License:Apache License
@Override public void connect(String url, @Nullable String protocol, EventListener listener) { this.eventListener = listener; OkHttpClient okHttpClient = new OkHttpClient(); Request.Builder builder = new Request.Builder(); if (protocol != null) { builder.addHeader(HEADER_SEC_WEBSOCKET_PROTOCOL, protocol); }// ww w. j a va 2s . c o m builder.url(url); WebSocketCall.create(okHttpClient, builder.build()).enqueue(new WebSocketListener() { @Override public void onOpen(WebSocket webSocket, Request request, Response response) throws IOException { ws = webSocket; eventListener.onOpen(); } @Override public void onMessage(BufferedSource payload, WebSocket.PayloadType type) throws IOException { eventListener.onMessage(payload.readUtf8()); payload.close(); } @Override public void onPong(Buffer payload) { } @Override public void onClose(int code, String reason) { eventListener.onClose(code, reason, true); } @Override public void onFailure(IOException e) { e.printStackTrace(); if (e instanceof EOFException) { eventListener.onClose(WebSocketCloseCodes.CLOSE_NORMAL.getCode(), WebSocketCloseCodes.CLOSE_NORMAL.name(), true); } else { eventListener.onError(e.getMessage()); } } }); }
From source file:com.apothesource.pillfill.service.drug.impl.DefaultDrugAlertServiceImpl.java
License:Open Source License
@Override public Observable<DrugAlertType> checkForRxNormInteractions(Collection<PrescriptionType> rxList) { HashSet<String> cuiSet = new HashSet<>(); Observable<String> rxNormIdList = Observable.from(rxList).filter(rx -> rx.getRxNormId() != null) .map(PrescriptionType::getRxNormId); cuiSet.addAll(rxNormIdList.toList().toBlocking().first()); return subscribeIoObserveImmediate(Observable.create(subscriber -> { if (cuiSet.size() < 2) { log.fine("Not processing drug interaction set size of " + cuiSet.size()); subscriber.onCompleted();//from w w w. j a v a 2 s . c om } else { // Check to see if this set has been queried before ArrayList<String> cuiList = new ArrayList<>(cuiSet); Collections.sort(cuiList); String param = Joiner.on("+").join(cuiList); final String url = String.format(PFServiceEndpoints.EXT_RXNORM_INTERACTIONS_URL, param); Optional<String> cachedResult = cache.getCachedData(url); if (cachedResult.isPresent()) { log.fine("Returning cached result for URL query: " + url); List<DrugAlertType> alertList = deserializeDrugAlerts(rxList, cachedResult.get()); Observable.from(alertList).forEach(subscriber::onNext); subscriber.onCompleted(); } else { log.fine("Requesting Interaction URL: " + url); Request.Builder rxNormInteractionCheckRequest = new Request.Builder(); Request req = rxNormInteractionCheckRequest.url(url).build(); try { Response responseObject = externalHttpClient.newCall(req).execute(); String responseMsg = responseObject.body().string(); cache.setCachedData(url, responseMsg); List<DrugAlertType> drugAlerts = deserializeDrugAlerts(rxList, responseMsg); Observable.from(drugAlerts).forEach(subscriber::onNext); subscriber.onCompleted(); } catch (IOException e) { log.log(Level.WARNING, "Error processing drug interaction response.", e); subscriber.onError(new RuntimeException(e)); } } } })); }
From source file:com.baasbox.android.net.OkClient.java
License:Apache License
@Override public HttpResponse execute(HttpRequest request) throws BaasException { String contentType = request.headers.get("Content-Type"); Request.Builder okRequestBuilder = new Request.Builder(); boolean contentLengthSet = false; for (String name : request.headers.keySet()) { if (!contentLengthSet && "Content-Length".equals(name)) { contentLengthSet = true;/*www. java2s . c o m*/ } okRequestBuilder.addHeader(name, request.headers.get(name)); } if (!contentLengthSet) { okRequestBuilder.addHeader("Content-Length", "0"); } RequestBody rb; switch (request.method) { case HttpRequest.GET: okRequestBuilder.get(); break; case HttpRequest.POST: rb = buildBody(contentType, request.body); //InputRequestBody rb = new InputRequestBody(contentType,request.body); okRequestBuilder.post(rb); break; case HttpRequest.PUT: rb = buildBody(contentType, request.body); okRequestBuilder.put(rb); break; case HttpRequest.DELETE: okRequestBuilder.delete(); break; case HttpRequest.PATCH: rb = buildBody(contentType, request.body); okRequestBuilder.patch(rb); break; } okRequestBuilder.url(request.url); Request okRequest = okRequestBuilder.build(); try { Response resp = mOkHttp.newCall(okRequest).execute(); Protocol protocol = resp.protocol(); ProtocolVersion pv; switch (protocol) { case HTTP_1_0: pv = new ProtocolVersion("HTTP", 1, 0); break; case HTTP_1_1: pv = new ProtocolVersion("HTTP", 1, 1); break; case HTTP_2: pv = new ProtocolVersion("HTTP", 2, 0); break; case SPDY_3: pv = new ProtocolVersion("spdy", 3, 1); break; default: throw new BaasIOException("Invalid protocol"); } StatusLine line = new BasicStatusLine(pv, resp.code(), resp.message()); BasicHttpResponse bresp = new BasicHttpResponse(line); bresp.setEntity(asEntity(resp)); for (String name : resp.headers().names()) { String val = resp.headers().get(name); bresp.addHeader(name, val); } return bresp; } catch (IOException e) { throw new BaasIOException(e); } }
From source file:com.cdancy.artifactory.rest.config.ArtifactoryOkHttpCommandExecutorService.java
License:Apache License
@Override protected Request convert(HttpRequest request) throws IOException, InterruptedException { Request.Builder builder = new Request.Builder(); builder.url(request.getEndpoint().toString()); populateHeaders(request, builder);/*w w w. j av a 2 s . co m*/ RequestBody body = null; Payload payload = request.getPayload(); if (payload != null) { Long length = checkNotNull(payload.getContentMetadata().getContentLength(), "payload.getContentLength"); if (length > 0) { body = generateRequestBody(request, payload); } } builder.method(request.getMethod(), body); return builder.build(); }
From source file:com.cinchapi.concourse.http.HttpTest.java
License:Apache License
/** * Perform a DELETE request// w ww. j a va 2s . c om * * @param route * @param args - include a {@link Headers} object to set the request headers * @return the response */ protected Response delete(String route, Object... args) { try { Request.Builder builder = new Request.Builder(); args = filterArgs(builder, args); args = cleanUrlArgs(args); route = MessageFormat.format(route, args); Request request = builder.url(base + route).delete().build(); Response response = http.newCall(request).execute(); long ts = response.hashCode(); Variables.register("request_" + ts, request); Variables.register("response_" + ts, response); return response; } catch (IOException e) { throw Throwables.propagate(e); } }