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:org.jboss.arquillian.ce.proxy.AbstractProxy.java
License:Open Source License
public <T> T post(String url, Class<T> returnType, Object requestObject) throws Exception { final OkHttpClient httpClient = getHttpClient(); Request.Builder builder = new Request.Builder(); builder.url(url); if (requestObject != null) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try (ObjectOutputStream oos = new ObjectOutputStream(baos)) { oos.writeObject(requestObject); oos.flush();// www .ja v a 2s .c o m } catch (Exception e) { throw new RuntimeException("Error sending request Object, " + requestObject, e); } RequestBody body = RequestBody.create(MediaType.parse("application/octet-stream"), baos.toByteArray()); builder.post(body); } Request request = builder.build(); Response response = httpClient.newCall(request).execute(); int responseCode = response.code(); if (responseCode == HttpURLConnection.HTTP_OK) { Object o; try (ObjectInputStream ois = new ObjectInputStream(response.body().byteStream())) { o = ois.readObject(); } if (returnType.isInstance(o) == false) { throw new IllegalStateException( "Error reading results, expected a " + returnType.getName() + " but got " + o); } return returnType.cast(o); } else if (responseCode == HttpURLConnection.HTTP_NO_CONTENT) { return null; } else if (responseCode != HttpURLConnection.HTTP_NOT_FOUND) { throw new IllegalStateException( "Error launching test at " + url + ". Got " + responseCode + " (" + response.message() + ")"); } return null; // TODO }
From source file:org.jboss.arquillian.ce.proxy.AbstractProxy.java
License:Open Source License
public synchronized InputStream post(Map<String, String> labels, int index, int port, String path) throws Exception { String url = url(labels, index, port, path, null); OkHttpClient httpClient = getHttpClient(); Request.Builder builder = new Request.Builder(); builder.url(url); Request request = builder.build(); Response response = httpClient.newCall(request).execute(); return response.body().byteStream(); }
From source file:org.mariotaku.twidere.util.net.OkHttpRestClient.java
License:Open Source License
@NonNull @Override/*from w ww . ja v a 2s .co m*/ public RestHttpResponse execute(RestHttpRequest restHttpRequest) throws IOException { final Request.Builder builder = new Request.Builder(); builder.method(restHttpRequest.getMethod(), RestToOkBody.wrap(restHttpRequest.getBody())); builder.url(restHttpRequest.getUrl()); final List<Pair<String, String>> headers = restHttpRequest.getHeaders(); if (headers != null) { for (Pair<String, String> header : headers) { builder.addHeader(header.first, header.second); } } final Call call = client.newCall(builder.build()); return new OkRestHttpResponse(call.execute()); }
From source file:org.quantumbadger.redreader.http.okhttp.OKHTTPBackend.java
License:Open Source License
@Override public Request prepareRequest(final Context context, final RequestDetails details) { final com.squareup.okhttp.Request.Builder builder = new com.squareup.okhttp.Request.Builder(); builder.header("User-Agent", Constants.ua(context)); final List<PostField> postFields = details.getPostFields(); if (postFields != null) { builder.post(RequestBody.create(MediaType.parse("application/x-www-form-urlencoded"), PostField.encodeList(postFields))); } else {//from w w w .j a v a 2s . com builder.get(); } builder.url(details.getUrl().toString()); builder.cacheControl(CacheControl.FORCE_NETWORK); final AtomicReference<Call> callRef = new AtomicReference<>(); return new Request() { public void executeInThisThread(final Listener listener) { final Call call = mClient.newCall(builder.build()); callRef.set(call); try { final Response response; try { response = call.execute(); } catch (IOException e) { listener.onError(CacheRequest.REQUEST_FAILURE_CONNECTION, e, null); return; } final int status = response.code(); if (status == 200 || status == 202) { final ResponseBody body = response.body(); final InputStream bodyStream; final Long bodyBytes; if (body != null) { bodyStream = body.byteStream(); bodyBytes = body.contentLength(); } else { // TODO error bodyStream = null; bodyBytes = null; } final String contentType = response.header("Content-Type"); listener.onSuccess(contentType, bodyBytes, bodyStream); } else { listener.onError(CacheRequest.REQUEST_FAILURE_REQUEST, null, status); } } catch (Throwable t) { listener.onError(CacheRequest.REQUEST_FAILURE_CONNECTION, t, null); } } @Override public void cancel() { final Call call = callRef.getAndSet(null); if (call != null) { call.cancel(); } } @Override public void addHeader(final String name, final String value) { builder.addHeader(name, value); } }; }
From source file:org.whispersystems.signalservice.internal.push.PushServiceSocket.java
private Response getConnection(String urlFragment, String method, String body) throws PushNetworkException { try {//w ww. j a va2 s.c om Log.w(TAG, "Push service URL: " + serviceUrl); Log.w(TAG, "Opening URL: " + String.format("%s%s", serviceUrl, urlFragment)); SSLContext context = SSLContext.getInstance("TLS"); context.init(null, trustManagers, null); OkHttpClient okHttpClient = new OkHttpClient(); okHttpClient.setSslSocketFactory(context.getSocketFactory()); okHttpClient.setHostnameVerifier(new StrictHostnameVerifier()); Request.Builder request = new Request.Builder(); request.url(String.format("%s%s", serviceUrl, urlFragment)); if (body != null) { request.method(method, RequestBody.create(MediaType.parse("application/json"), body)); } else { request.method(method, null); } if (credentialsProvider.getPassword() != null) { request.addHeader("Authorization", getAuthorizationHeader()); } if (userAgent != null) { request.addHeader("X-Signal-Agent", userAgent); } return okHttpClient.newCall(request.build()).execute(); } catch (IOException e) { throw new PushNetworkException(e); } catch (NoSuchAlgorithmException | KeyManagementException e) { throw new AssertionError(e); } }
From source file:org.wso2.carbon.identity.authenticator.duo.DuoHttp.java
License:Open Source License
public Response executeHttpRequest() throws Exception { String url = "https://" + host + uri; String queryString = createQueryString(); Request.Builder builder = new Request.Builder(); if (method.equals("POST")) { builder.post(RequestBody.create(FORM_ENCODED, queryString)); } else if (method.equals("PUT")) { builder.put(RequestBody.create(FORM_ENCODED, queryString)); } else if (method.equals("GET")) { if (queryString.length() > 0) { url += "?" + queryString; }//from w w w.j ava 2 s.c o m builder.get(); } else if (method.equals("DELETE")) { if (queryString.length() > 0) { url += "?" + queryString; } builder.delete(); } else { throw new UnsupportedOperationException("Unsupported method: " + method); } Request request = builder.url(url).build(); // Set up client. OkHttpClient httpclient = new OkHttpClient(); if (proxy != null) { httpclient.setProxy(proxy); } httpclient.setConnectTimeout(timeout, TimeUnit.SECONDS); httpclient.setWriteTimeout(timeout, TimeUnit.SECONDS); httpclient.setReadTimeout(timeout, TimeUnit.SECONDS); // finish and execute request builder.headers(headers.build()); return httpclient.newCall(builder.build()).execute(); }
From source file:pct.droid.base.providers.media.EZTVProvider.java
License:Open Source License
@Override public Call getList(final ArrayList<Media> existingList, Filters filters, final Callback callback) { final ArrayList<Media> currentList; if (existingList == null) { currentList = new ArrayList<>(); } else {// w w w .j a v a 2 s . c o m currentList = (ArrayList<Media>) existingList.clone(); } ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new NameValuePair("limit", "30")); if (filters == null) { filters = new Filters(); } if (filters.keywords != null) { params.add(new NameValuePair("keywords", filters.keywords)); } if (filters.genre != null) { params.add(new NameValuePair("genre", filters.genre)); } if (filters.order == Filters.Order.ASC) { params.add(new NameValuePair("order", "asc")); } else { params.add(new NameValuePair("order", "desc")); } String sort = ""; switch (filters.sort) { default: case POPULARITY: sort = "popularity"; break; case TRENDING: sort = "trending"; break; case YEAR: sort = "year"; break; case DATE: sort = "updated"; break; case RATING: sort = "rating"; break; case ALPHABET: sort = "name"; break; } params.add(new NameValuePair("sort", sort)); String url = API_URL + "shows/"; if (filters.page != null) { url += filters.page; } else { url += "1"; } Request.Builder requestBuilder = new Request.Builder(); String query = buildQuery(params); requestBuilder.url(url + "?" + query); requestBuilder.tag(MEDIA_CALL); return fetchList(currentList, requestBuilder, filters, callback); }
From source file:pct.droid.base.providers.media.EZTVProvider.java
License:Open Source License
/** * Fetch the list of movies from EZTV// w w w.j av a 2s . co m * * @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) { return enqueue(requestBuilder.build(), new com.squareup.okhttp.Callback() { @Override public void onFailure(Request request, IOException e) { String url = requestBuilder.build().urlString(); if (url.equals(MIRROR_URL)) { callback.onFailure(e); } else { url = url.replace(API_URL, MIRROR_URL); requestBuilder.url(url); fetchList(currentList, requestBuilder, filters, callback); } } @Override public void onResponse(Response response) throws IOException { try { if (response.isSuccessful()) { String responseStr = response.body().string(); ArrayList<LinkedTreeMap<String, Object>> list = null; if (responseStr.isEmpty()) { list = new ArrayList<>(); } else { list = (ArrayList<LinkedTreeMap<String, Object>>) mGson.fromJson(responseStr, ArrayList.class); } EZTVReponse result = new EZTVReponse(list); if (list == null) { callback.onFailure(new NetworkErrorException("Empty response")); } else { ArrayList<Media> formattedData = result.formatListForPopcorn(currentList); callback.onSuccess(filters, formattedData, list.size() > 0); return; } } } catch (Exception e) { callback.onFailure(e); } callback.onFailure(new NetworkErrorException("Couldn't connect to EZTVAPI")); } }); }
From source file:pct.droid.base.providers.media.EZTVProvider.java
License:Open Source License
@Override public Call getDetail(String videoId, final Callback callback) { Request.Builder requestBuilder = new Request.Builder(); requestBuilder.url(API_URL + "show/" + videoId); requestBuilder.tag(MEDIA_CALL);//www.ja v a 2 s . c o m return enqueue(requestBuilder.build(), new com.squareup.okhttp.Callback() { @Override public void onFailure(Request request, IOException e) { callback.onFailure(e); } @Override public void onResponse(Response response) throws IOException { if (response.isSuccessful()) { String responseStr = response.body().string(); LinkedTreeMap<String, Object> map = mGson.fromJson(responseStr, LinkedTreeMap.class); EZTVReponse result = new EZTVReponse(map); if (map == null) { callback.onFailure(new NetworkErrorException("Empty response")); } else { ArrayList<Media> formattedData = result.formatDetailForPopcorn(); if (formattedData.size() > 0) { callback.onSuccess(null, formattedData, true); return; } callback.onFailure(new IllegalStateException("Empty list")); return; } } callback.onFailure(new NetworkErrorException("Couldn't connect to EZTVAPI")); } }); }
From source file:pct.droid.base.providers.media.HaruProvider.java
License:Open Source License
@Override public Call getList(final ArrayList<Media> existingList, Filters filters, final Callback callback) { final ArrayList<Media> currentList; if (existingList == null) { currentList = new ArrayList<>(); } else {/*from w w w. ja va 2 s .co m*/ currentList = (ArrayList<Media>) existingList.clone(); } ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new NameValuePair("limit", "30")); if (filters == null) { filters = new Filters(); } if (filters.keywords != null) { params.add(new NameValuePair("search", filters.keywords)); } if (filters.genre != null) { params.add(new NameValuePair("genres", filters.genre)); } if (filters.order == Filters.Order.DESC) { params.add(new NameValuePair("order", "desc")); } else { params.add(new NameValuePair("order", "asc")); } String sort = ""; switch (filters.sort) { default: case POPULARITY: sort = "popularity"; break; case YEAR: sort = "year"; break; case DATE: sort = "updated"; break; case RATING: sort = "rating"; break; case ALPHABET: sort = "name"; break; } params.add(new NameValuePair("sort", sort)); String url = API_URL + "list.php"; if (filters.page != null) { params.add(new NameValuePair("page", Integer.toString(filters.page - 1))); } else { params.add(new NameValuePair("page", "0")); } Request.Builder requestBuilder = new Request.Builder(); String query = buildQuery(params); requestBuilder.url(url + "?" + query); requestBuilder.tag(MEDIA_CALL); return fetchList(currentList, requestBuilder, filters, callback); }