com.squareup.okhttp.Response Java Examples
The following examples show how to use
com.squareup.okhttp.Response.
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: AggregatorService.java From spring-async with MIT License | 6 votes |
public void execute(final Task task) { log.info("Started task with {} urls", task.getUrls().size()); task.start(); for(int i = 0; i < task.getUrls().size(); i++) { final int index = i; final long time = System.currentTimeMillis(); String url = task.getUrls().get(i); Request req = new Request.Builder().get().url(url).build(); client.newCall(req).enqueue(new Callback() { @Override public void onFailure(Request request, IOException e) { task.fail(index, time, request, e); } @Override public void onResponse(Response response) throws IOException { task.success(index, time, response); } }); } }
Example #2
Source File: Api.java From materialup with Apache License 2.0 | 6 votes |
@Override public Response intercept(Chain chain) throws IOException { Response originalResponse = chain.proceed(chain.request()); String host = chain.request().url().getHost(); 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 #3
Source File: ZalyHttpClient.java From openzaly with Apache License 2.0 | 6 votes |
public byte[] postBytes(String url, byte[] bytes) throws IOException { ResponseBody body = null; try { RequestBody postBody = RequestBody.create(JSON, bytes); Request request = new Request.Builder().url(url).post(postBody).build(); Response response = httpClient.newCall(request).execute(); if (response.isSuccessful()) { body = response.body(); byte[] res = body.bytes(); return res; } else { logger.error("http post error.{}", response.message()); } } finally { if (body != null) { body.close(); } } return null; }
Example #4
Source File: DOkHttp.java From Pas with Apache License 2.0 | 6 votes |
/** * 获取cookie * @param response * @param url */ private Map getCookie(Response response, String url) { Map<String, List<String>> map = new HashMap<String, List<String>>(); //获取cookie 然后打印 绑定 try { List<String> values = response.headers().values("Set-Cookie"); map = getInstance().mOkHttpClient.getCookieHandler().get(URI.create(url), response.headers().toMultimap()); // for (String key : map.keySet()) { // if ("Cookie".equals(key)) { // sessionId = map.get(key).get(0); // } // } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return map; }
Example #5
Source File: AbstractClient.java From tencentcloud-sdk-java with Apache License 2.0 | 6 votes |
private Response doRequest(String endpoint, AbstractModel request, String action) throws TencentCloudSDKException { HashMap<String, String> param = new HashMap<String, String>(); request.toMap(param, ""); String strParam = this.formatRequestData(action, param); HttpConnection conn = new HttpConnection( this.profile.getHttpProfile().getConnTimeout(), this.profile.getHttpProfile().getReadTimeout(), this.profile.getHttpProfile().getWriteTimeout()); conn.addInterceptors(log); this.trySetProxy(conn); String reqMethod = this.profile.getHttpProfile().getReqMethod(); String url = this.profile.getHttpProfile().getProtocol() + endpoint + this.path; if (reqMethod.equals(HttpProfile.REQ_GET)) { return conn.getRequest(url + "?" + strParam); } else if (reqMethod.equals(HttpProfile.REQ_POST)) { return conn.postRequest(url, strParam); } else { throw new TencentCloudSDKException("Method only support (GET, POST)"); } }
Example #6
Source File: SwaggerHubClientTest.java From swaggerhub-maven-plugin with Apache License 2.0 | 6 votes |
/** * This test defines the expected request format to be made to SwaggerHub to create an Integration plugin * The values defined as part of the request matcher are what is expected to be set due to the users configuration. * @throws JsonProcessingException */ @Test public void verifySaveIntegrationPluginOfType_postsExpectedRequestBodyWithBasePath() throws JsonProcessingException { //Given swaggerHubClient = buildSwaggerHubClient("basePath"); SaveSCMPluginConfigRequest.Builder requestBuilder = requestBuilder(); SaveSCMPluginConfigRequest saveSCMPluginConfigRequest = requestBuilder.build(); String requestUrl = String.format("/basePath/plugins/configurations/%s/%s/%s/%s?oas=%s", API_OWNER, API_NAME, API_VERSION, SCM_INTEGRATION_PROVIDER_GITHUB, OAS3); stubFor(put(requestUrl).willReturn(created())); RequestPatternBuilder putRequestPattern = putRequestPattern("/basePath/plugins/configurations/%s/%s/%s/%s"); //When Optional<Response> response = swaggerHubClient.saveIntegrationPluginOfType(saveSCMPluginConfigRequest); //Then verify(1, putRequestPattern); response.ifPresent( x -> assertEquals(201, response.get().code())); if(!response.isPresent()){ fail(); } }
Example #7
Source File: RouteRest.java From RouteDrawer with Apache License 2.0 | 6 votes |
private String getJSONDirection(LatLng start, LatLng end, TravelMode mode) throws IOException { String url = "http://maps.googleapis.com/maps/api/directions/json?" + "origin=" + start.latitude + "," + start.longitude + "&destination=" + end.latitude + "," + end.longitude + "&sensor=false&units=metric&mode=" + mode.name().toLowerCase(); Request request = new Request.Builder() .url(url) .build(); Response response = client.newCall(request).execute(); return response.body().string(); }
Example #8
Source File: ZalyHttpClient.java From openzaly with Apache License 2.0 | 6 votes |
public byte[] get(String url) throws Exception { ResponseBody body = null; try { Request request = new Request.Builder().url(url).build(); Response response = httpClient.newCall(request).execute(); if (response.isSuccessful()) { body = response.body(); byte[] res = body.bytes(); return res; } else { logger.error("http get url={} error.{}", url, response.message()); } } finally { if (body != null) { body.close(); } } return null; }
Example #9
Source File: SwaggerHubClient.java From swaggerhub-gradle-plugin with Apache License 2.0 | 6 votes |
public String getDefinition(SwaggerHubRequest swaggerHubRequest) throws GradleException { HttpUrl httpUrl = getDownloadUrl(swaggerHubRequest); MediaType mediaType = MediaType.parse("application/" + swaggerHubRequest.getFormat()); Request requestBuilder = buildGetRequest(httpUrl, mediaType); final String jsonResponse; try { final Response response = client.newCall(requestBuilder).execute(); if (!response.isSuccessful()) { throw new GradleException(String.format("Failed to download API definition: %s", response.body().string())); } else { jsonResponse = response.body().string(); } } catch (IOException e) { throw new GradleException("Failed to download API definition", e); } return jsonResponse; }
Example #10
Source File: HNewsApi.java From yahnac with Apache License 2.0 | 6 votes |
private void attemptLogin() { try { ConnectionProvider connectionProvider = Inject.connectionProvider(); Connection.Response response = connectionProvider .loginConnection(username, password) .execute(); String cookie = response.cookie("user"); String cfduid = response.cookie("_cfduid"); if (!TextUtils.isEmpty(cookie)) { subscriber.onNext(new Login(username, cookie, Login.Status.SUCCESSFUL)); } else { subscriber.onNext(new Login(username, null, Login.Status.WRONG_CREDENTIALS)); } } catch (IOException e) { subscriber.onError(e); } }
Example #11
Source File: BaseRequestTest.java From Auth0.Android with MIT License | 6 votes |
@Before public void setUp() { MockitoAnnotations.initMocks(this); HttpUrl url = HttpUrl.parse("https://auth0.com"); parameterBuilder = ParameterBuilder.newBuilder(); baseRequest = new BaseRequest<String, Auth0Exception>(url, client, new Gson(), adapter, errorBuilder, callback, headers, parameterBuilder) { @Override public String execute() throws Auth0Exception { return null; } @Override public void onResponse(Response response) { } @Override protected Request doBuildRequest() throws RequestBodyBuildException { return null; } }; }
Example #12
Source File: ZalyHttpClient.java From openzaly with Apache License 2.0 | 6 votes |
public byte[] postString(String url, String json) throws IOException { ResponseBody body = null; try { RequestBody postBody = RequestBody.create(JSON, json); Request request = new Request.Builder().url(url).post(postBody).build(); Response response = httpClient.newCall(request).execute(); if (response.isSuccessful()) { body = response.body(); byte[] res = body.bytes(); return res; } else { logger.error("http post error.{}", response.message()); } } finally { if (body != null) { body.close(); } } return null; }
Example #13
Source File: HawkularMetricsClient.java From apiman with Apache License 2.0 | 6 votes |
/** * Adds one or more data points for multiple counters all at once! * @param tenantId * @param data */ public void addMultipleCounterDataPoints(String tenantId, List<MetricLongBean> data) { try { URL endpoint = serverUrl.toURI().resolve("counters/raw").toURL(); //$NON-NLS-1$ Request request = new Request.Builder() .url(endpoint) .post(toBody(data)) .header("Hawkular-Tenant", tenantId) //$NON-NLS-1$ .build(); Response response = httpClient.newCall(request).execute(); if (response.code() >= 400) { throw hawkularMetricsError(response); } } catch (URISyntaxException | IOException e) { throw new RuntimeException(e); } }
Example #14
Source File: FontDownloader.java From fontster with Apache License 2.0 | 6 votes |
static Observable<File> downloadFile(final String url, final String path) { return Observable.create(subscriber -> { final Request request = new Request.Builder().url(url).build(); try { if (!subscriber.isUnsubscribed()) { final File file = new File(path); if (!file.exists()) { // noinspection ResultOfMethodCallIgnored file.getParentFile().mkdirs(); Timber.i("downloadFile: Downloading " + file.getName()); final Response response = sClient.newCall(request).execute(); final BufferedSink sink = Okio.buffer(Okio.sink(file)); sink.writeAll(response.body().source()); sink.close(); } else Timber.i("downloadFile: Retrieved from cache " + file.getName()); subscriber.onNext(file); subscriber.onCompleted(); } } catch (IOException e) { subscriber.onError(new DownloadException(e)); } }); }
Example #15
Source File: Api.java From materialup with Apache License 2.0 | 6 votes |
public static String getErrorMessage(retrofit.Response response) { String text = responseToString(response); try { JSONObject object = new JSONObject(text); if (object.has("errors")) { JSONArray errors = object.getJSONArray("errors"); if (errors.length() > 0) { JSONObject error = errors.getJSONObject(0); if (error.has("message")) { return error.getString("message"); } } } } catch (JSONException e) { e.printStackTrace(); } if (response.code() > 500) { return "check your network!"; } return null; }
Example #16
Source File: ProgressHelper.java From Pas with Apache License 2.0 | 6 votes |
/** * 包装OkHttpClient,用于下载文件的回调 * @param client 待包装的OkHttpClient * @param progressListener 进度回调接口 * @return 包装后的OkHttpClient,使用clone方法返回 */ public static OkHttpClient addProgressResponseListener(OkHttpClient client, final ProgressResponseListener progressListener){ //克隆 OkHttpClient clone = client.clone(); //增加拦截器 clone.networkInterceptors().add(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { //拦截 Response originalResponse = chain.proceed(chain.request()); //包装响应体并返回 return originalResponse.newBuilder() .body(new ProgressResponseBody(originalResponse.body(), progressListener)) .build(); } }); return clone; }
Example #17
Source File: Login.java From mini-hacks with MIT License | 6 votes |
public void login(View view) { String json = "{\"name\": \"" + nameInput.getText() + "\", \"password\":\"" + passwordInput.getText() + "\"}"; networkHelper.post("http://10.0.3.2:8000/smarthome/_session", json, new Callback() { @Override public void onFailure(Request request, IOException e) { } @Override public void onResponse(Response response) throws IOException { String responseStr = response.body().string(); final String messageText = "Status code : " + response.code() + "\n" + "Response body : " + responseStr; runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), messageText, Toast.LENGTH_LONG).show(); } }); } }); }
Example #18
Source File: PictureParser.java From JianDan_OkHttp with Apache License 2.0 | 6 votes |
@Nullable public ArrayList<Picture> parse(Response response) { code = wrapperCode(response.code()); if (!response.isSuccessful()) return null; try { String jsonStr = response.body().string(); jsonStr = new JSONObject(jsonStr).getJSONArray("comments").toString(); return (ArrayList<Picture>) JSONParser.toObject(jsonStr, new TypeToken<ArrayList<Picture>>() { }.getType()); } catch (Exception e) { e.printStackTrace(); return null; } }
Example #19
Source File: HawkularMetricsClient.java From apiman with Apache License 2.0 | 6 votes |
/** * Adds multiple data points to a counter. * @param tenantId * @param counterId * @param dataPoints */ public void addCounterDataPoints(String tenantId, String counterId, List<DataPointLongBean> dataPoints) { try { URL endpoint = serverUrl.toURI().resolve("counters/" + counterId + "/raw").toURL(); //$NON-NLS-1$ //$NON-NLS-2$ Request request = new Request.Builder() .url(endpoint) .post(toBody(dataPoints)) .header("Hawkular-Tenant", tenantId) //$NON-NLS-1$ .build(); Response response = httpClient.newCall(request).execute(); if (response.code() >= 400) { throw hawkularMetricsError(response); } } catch (URISyntaxException | IOException e) { throw new RuntimeException(e); } }
Example #20
Source File: AuthCookie.java From utexas-utilities with Apache License 2.0 | 6 votes |
/** * Executes a login request with the AuthCookie's OkHttpClient. This should only be called * when persistent login is activated. * @param request Request to execute * @return true if the cookie was set successfully, false if the cookie was not set * @throws IOException */ protected boolean performLogin(Request request) throws IOException { Response response = client.newCall(request).execute(); if (!response.isSuccessful()) { throw new IOException("Bad response code: " + response + " during login."); } response.body().close(); CookieManager cm = (CookieManager) CookieHandler.getDefault(); List<HttpCookie> cookies = cm.getCookieStore().getCookies(); for (HttpCookie cookie : cookies) { String cookieVal = cookie.getValue(); if (cookie.getName().equals(authCookieKey)) { setAuthCookieVal(cookieVal); return true; } } return false; }
Example #21
Source File: HNewsApi.java From yahnac with Apache License 2.0 | 5 votes |
Observable<OperationResponse> commentOnStory(final Long itemId, final String comment) { return Observable.create( new ParseHmacOnSubscribe(itemId)) .flatMap(new Func1<String, Observable<OperationResponse>>() { @Override public Observable<OperationResponse> call(final String hmac) { return Observable.create(new Observable.OnSubscribe<OperationResponse>() { @Override public void call(Subscriber<? super OperationResponse> subscriber) { try { ConnectionProvider connectionProvider = Inject.connectionProvider(); Request request = connectionProvider .commentOnStoryRequest(String.valueOf(itemId), comment, hmac); OkHttpClient client = new OkHttpClient(); Response response = client.newCall(request).execute(); if (response.code() == 200) { subscriber.onNext(OperationResponse.SUCCESS); } else { subscriber.onNext(OperationResponse.FAILURE); } } catch (IOException e) { subscriber.onError(e); } } }); } }) .subscribeOn(Schedulers.io()); }
Example #22
Source File: Trakt.java From Mizuu with Apache License 2.0 | 5 votes |
public static boolean markEpisodeAsWatched(String showId, List<com.miz.functions.TvShowEpisode> episodes, Context c, boolean watched) { SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(c); String username = settings.getString(TRAKT_USERNAME, "").trim(); String password = settings.getString(TRAKT_PASSWORD, ""); if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password) || !settings.getBoolean(SYNC_WITH_TRAKT, false) || episodes.size() == 0) return false; try { JSONObject holder = new JSONObject(); holder.put("username", username); holder.put("password", password); holder.put("imdb_id", ""); holder.put("tvdb_id", showId); holder.put("title", ""); holder.put("year", ""); JSONArray array = new JSONArray(); int count = episodes.size(); for (int i = 0; i < count; i++) { JSONObject jsonMovie = new JSONObject(); jsonMovie.put("season", episodes.get(i).getSeason()); jsonMovie.put("episode", episodes.get(i).getEpisode()); array.put(jsonMovie); } holder.put("episodes", array); Request request = MizLib.getJsonPostRequest("http://api.trakt.tv/show/episode/" + (!watched ? "un" : "") + "seen/" + getApiKey(c), holder); Response response = MizuuApplication.getOkHttpClient().newCall(request).execute(); return response.isSuccessful(); } catch (Exception e) { return false; } }
Example #23
Source File: HttpURLConnectionImpl.java From apiman with Apache License 2.0 | 5 votes |
private Headers getHeaders() throws IOException { if (responseHeaders == null) { Response response = getResponse().getResponse(); Headers headers = response.headers(); responseHeaders = headers.newBuilder() .add(Platform.get().getPrefix() + "-Response-Source", responseSourceHeader(response)) .build(); } return responseHeaders; }
Example #24
Source File: TestCaseActivity.java From NewXmPluginSDK with Apache License 2.0 | 5 votes |
public Response uploadFile(String url, String filePath) throws IOException { Log.d("test", "url:" + url); OkHttpClient client = new OkHttpClient(); client.setConnectTimeout(30, TimeUnit.SECONDS); client.setReadTimeout(15, TimeUnit.SECONDS); client.setWriteTimeout(30, TimeUnit.SECONDS); Request request = new Request.Builder() .url(url) .put(RequestBody.create(MediaType.parse(""), new File(filePath))) .build(); return client.newCall(request).execute(); }
Example #25
Source File: OkHttp2Probe.java From pre-dem-android with MIT License | 5 votes |
@Around("call(* com.squareup.okhttp.Response.Builder+.build(..))") public Object onOkHttpRespBuild(ProceedingJoinPoint joinPoint) throws Throwable { if (!Configuration.httpMonitorEnable) { return joinPoint.proceed(); } Object result = joinPoint.proceed(); if (result instanceof Response) { Response resp = (Response) result; RespBodyToRespMap.put(resp.body(), resp); } return result; }
Example #26
Source File: Trakt.java From Mizuu with Apache License 2.0 | 5 votes |
public static boolean moviesWatchlist(List<MediumMovie> movies, Context c) { SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(c); String username = settings.getString(TRAKT_USERNAME, "").trim(); String password = settings.getString(TRAKT_PASSWORD, ""); if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password) || movies.size() == 0) return false; try { JSONObject json = new JSONObject(); json.put("username", username); json.put("password", password); JSONArray array = new JSONArray(); int count = movies.size(); for (int i = 0; i < count; i++) { JSONObject jsonMovie = new JSONObject(); jsonMovie.put("tmdb_id", movies.get(i).getTmdbId()); jsonMovie.put("year", movies.get(i).getReleaseYear()); jsonMovie.put("title", movies.get(i).getTitle()); array.put(jsonMovie); } json.put("movies", array); Request request = MizLib.getJsonPostRequest((movies.get(0).toWatch() ? "http://api.trakt.tv/movie/watchlist/" : "http://api.trakt.tv/movie/unwatchlist/") + getApiKey(c), json); Response response = MizuuApplication.getOkHttpClient().newCall(request).execute(); return response.isSuccessful(); } catch (Exception e) { return false; } }
Example #27
Source File: HttpCallback.java From Android-nRF-Beacon-for-Eddystone with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Override public void onResponse(final Response response) throws IOException { handler.post(new Runnable() { @Override public void run() { try { delegate.onResponse(response); } catch (IOException e) { delegate.onFailure(null, e); } } }); }
Example #28
Source File: MultiAuthenticator.java From localization_nifi with Apache License 2.0 | 5 votes |
@Override public Request authenticateProxy(Proxy proxy, Response response) throws IOException { String credential = Credentials.basic(proxyUsername, proxyPassword); return response.request() .newBuilder() .header("Proxy-Authorization", credential) .build(); }
Example #29
Source File: InvokeHTTP.java From localization_nifi with Apache License 2.0 | 5 votes |
/** * Returns a Map of flowfile attributes from the response http headers. Multivalue headers are naively converted to comma separated strings. */ private Map<String, String> convertAttributesFromHeaders(URL url, Response responseHttp){ // create a new hashmap to store the values from the connection Map<String, String> map = new HashMap<>(); for (Map.Entry<String, List<String>> entry : responseHttp.headers().toMultimap().entrySet()) { String key = entry.getKey(); if (key == null) { continue; } List<String> values = entry.getValue(); // we ignore any headers with no actual values (rare) if (values == null || values.isEmpty()) { continue; } // create a comma separated string from the values, this is stored in the map String value = csv(values); // put the csv into the map map.put(key, value); } if ("HTTPS".equals(url.getProtocol().toUpperCase())) { map.put(REMOTE_DN, responseHttp.handshake().peerPrincipal().getName()); } return map; }
Example #30
Source File: HarborClient.java From harbor-java-client with Apache License 2.0 | 5 votes |
/** * logout</br> * <b>URL</b>: /log_out</br> * <b>Method</b>: GET * * @return HTTP Response Code * @throws IOException */ public int logout() throws IOException { String url = getBaseUrl().replace("/api", "") + "log_out"; Request request = new Request.Builder().get().url(url).build(); Response response = okhttpClient.newCall(request).execute(); int code = response.code(); logger.debug(String.format(REQUEST_RESPONSE_INFO, request, response)); return code; }