com.squareup.okhttp.Request Java Examples
The following examples show how to use
com.squareup.okhttp.Request.
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: DOkHttp.java From Pas with Apache License 2.0 | 7 votes |
/** * 上传文件 * 也可以和数据post一起提交 监听progress * @param requestBody * @param uIchangeListener */ public void uploadPost2ServerProgress(Context context,String url, RequestBody requestBody, MyCallBack myCallBack, final UIchangeListener uIchangeListener){ ProgressRequestBody progressRequestBody=ProgressHelper.addProgressRequestListener(requestBody, new UIProgressRequestListener() { @Override public void onUIRequestProgress(long bytesWrite, long contentLength, boolean done) { uIchangeListener.progressUpdate(bytesWrite,contentLength,done); } }); Request request=new Request.Builder() .tag(context) .post(progressRequestBody) .url(url) .build(); postData2Server(request,myCallBack); }
Example #2
Source File: TokenRefreshInterceptor.java From wear-notify-for-reddit with Apache License 2.0 | 6 votes |
@NonNull private synchronized Response renewTokenAndProceed(Chain chain, Request originalRequest) throws IOException { if (mTokenStorage.hasTokenExpired()) { try { Token token = mAuthenticationService.refreshToken(Constants.GRANT_TYPE_REFRESH_TOKEN, mTokenStorage.getRefreshToken()); mTokenStorage.updateToken(token); } catch (RetrofitError error) { if (error.getResponse() == null || isServerError(error.getResponse())) { throw new RuntimeException( "Failed to renew token, empty response/server error: " + error.getCause()); } else { throw new RuntimeException("Failed to renew token, unknown cause: " + error.getCause()); } } } return addHeaderAndProceedWithChain(chain, originalRequest); }
Example #3
Source File: BaseHttp.java From MousePaint with MIT License | 6 votes |
protected void basePost(String url, Map<String, String> params, CallbackListener<T> listener) { if (params == null) { baseGet(url,listener);return; } FormEncodingBuilder builder = new FormEncodingBuilder(); Set<Map.Entry<String, String>> entrySet = params.entrySet(); for (Map.Entry<String, String> entry : entrySet) { builder.add(entry.getKey(), entry.getValue()); } RequestBody requestBody = builder.build(); Request request = new Request.Builder() .url(url) .post(requestBody) .tag(url) .build(); doRequest(request, listener); }
Example #4
Source File: OkHttp2Probe.java From pre-dem-android with MIT License | 6 votes |
@Around("call(* com.squareup.okhttp.OkHttpClient+.newCall(..))") public Object onOkHttpNew(ProceedingJoinPoint joinPoint) throws Throwable { if (!Configuration.httpMonitorEnable || joinPoint.getArgs().length != 1) { return joinPoint.proceed(); } Object[] args = joinPoint.getArgs(); Request request = (Request) args[0]; //url URL url = request.url(); if (GlobalConfig.isExcludeHost(url.getHost())) { return joinPoint.proceed(); } RespBean bean = new RespBean(); bean.setUrl(url.toString()); bean.setStartTimestamp(System.currentTimeMillis()); startTimeStamp.add(bean); return joinPoint.proceed(); }
Example #5
Source File: ZalyHttpClient.java From wind-im 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 #6
Source File: OkHttpClientHttpRequestFactory.java From lams with GNU General Public License v2.0 | 6 votes |
static Request buildRequest(HttpHeaders headers, byte[] content, URI uri, HttpMethod method) throws MalformedURLException { com.squareup.okhttp.MediaType contentType = getContentType(headers); RequestBody body = (content.length > 0 || com.squareup.okhttp.internal.http.HttpMethod.requiresRequestBody(method.name()) ? RequestBody.create(contentType, content) : null); Request.Builder builder = new Request.Builder().url(uri.toURL()).method(method.name(), body); for (Map.Entry<String, List<String>> entry : headers.entrySet()) { String headerName = entry.getKey(); for (String headerValue : entry.getValue()) { builder.addHeader(headerName, headerValue); } } return builder.build(); }
Example #7
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 #8
Source File: MyTaskService.java From android-gcmnetworkmanager with Apache License 2.0 | 6 votes |
private int fetchUrl(OkHttpClient client, String url) { Request request = new Request.Builder() .url(url) .build(); try { Response response = client.newCall(request).execute(); Log.d(TAG, "fetchUrl:response:" + response.body().string()); if (response.code() != 200) { return GcmNetworkManager.RESULT_FAILURE; } } catch (IOException e) { Log.e(TAG, "fetchUrl:error" + e.toString()); return GcmNetworkManager.RESULT_FAILURE; } return GcmNetworkManager.RESULT_SUCCESS; }
Example #9
Source File: HttpConnection.java From tencentcloud-sdk-java with Apache License 2.0 | 6 votes |
public Response postRequest(String url, String body, Headers headers) throws TencentCloudSDKException { MediaType contentType = MediaType.parse(headers.get("Content-Type")); Request request = null; try { request = new Request.Builder() .url(url) .post(RequestBody.create(contentType, body)) .headers(headers) .build(); } catch (IllegalArgumentException e) { throw new TencentCloudSDKException(e.getClass().getName() + "-" + e.getMessage()); } return this.doRequest(request); }
Example #10
Source File: SwaggerHubClient.java From swaggerhub-maven-plugin with Apache License 2.0 | 6 votes |
public Optional<Response> saveIntegrationPluginOfType(SaveSCMPluginConfigRequest saveSCMPluginConfigRequest) throws JsonProcessingException { HttpUrl httpUrl = getSaveIntegrationPluginConfigURL(saveSCMPluginConfigRequest); MediaType mediaType = MediaType.parse("application/json"); Request httpRequest = buildPutRequest(httpUrl, mediaType, saveSCMPluginConfigRequest.getRequestBody()); try { Response response = client.newCall(httpRequest).execute(); if(!response.isSuccessful()){ log.error(String.format("Error when attempting to save %s plugin integration for API %s version %s", saveSCMPluginConfigRequest.getScmProvider(), saveSCMPluginConfigRequest.getApi(),saveSCMPluginConfigRequest.getVersion())); log.error("Error response: "+response.body().string()); response.body().close(); } return Optional.ofNullable(response); } catch (IOException e) { log.error(String.format("Error when attempting to save %s plugin integration for API %s. Error message %s", saveSCMPluginConfigRequest.getScmProvider(), saveSCMPluginConfigRequest.getApi(), e.getMessage())); return Optional.empty(); } }
Example #11
Source File: HttpClient.java From zsync4j with BSD 3-Clause "New" or "Revised" License | 6 votes |
Response executeWithAuthRetry(URI uri, Map<String, ? extends Credentials> credentials, HttpTransferListener listener, List<ContentRange> ranges) throws IOException { Request request = buildRequest(uri, credentials, ranges); listener.initiating(request); Response response = this.okHttpClient.newCall(request).execute(); for (int i = 0; i < 10; i++) { final int code = response.code(); if (!((code == HTTP_UNAUTHORIZED || code == HTTP_PROXY_AUTH) && containsBasic(response.challenges()))) { break; } // if we are receiving a basic authorization challenges, set header and retry final String host = response.request().uri().getHost(); this.basicChallengeReceived.add(host); final Credentials creds = credentials.get(host); if (creds == null) { break; } final String name = code == HTTP_UNAUTHORIZED ? "Authorization" : "Proxy-Authorization"; request = response.request().newBuilder().header(name, creds.basic()).build(); response = this.okHttpClient.newCall(request).execute(); } return response; }
Example #12
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 #13
Source File: FollowersPresenterImpl.java From meiShi with Apache License 2.0 | 6 votes |
@Override public void getFollowers(String uid, int page) { model.getFollowers(uid, page, new ResultCallback<List<FollowEntity>>() { @Override public void onError(Request request, Exception e) { view.showError(); } @Override public void onResponse(List<FollowEntity> response) { view.showFollows(response); } }); }
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: HarborClient.java From harbor-java-client with Apache License 2.0 | 6 votes |
/** * Let user see the recent operation logs of the projects which he is member * of.</br> * <b>URL</b>: /logs</br> * <b>Method</b>: GET * * @param lines * (The number of logs to be shown, default is 10 if lines, * start_time, end_time are not provided) * @param startTime * (The start time of logs to be shown in unix timestap) * @param endTime * (The end time of logs to be shown in unix timestap) * @return required logs. * @throws IOException * @throws HarborClientException */ public List<Log> getLogs(String lines, String startTime, String endTime) throws IOException, HarborClientException { logger.debug("get logs lines %s, start time %s, end time %s", lines, startTime, endTime); List<NameValuePair> qparams = new ArrayList<>(); qparams.add(new BasicNameValuePair("lines", lines)); qparams.add(new BasicNameValuePair("start_time", startTime)); qparams.add(new BasicNameValuePair("end_time", endTime)); qparams.removeIf(o -> Objects.isNull(o.getValue())); String url = getBaseUrl() + "/logs?" + URLEncodedUtils.format(qparams, "UTF-8"); Request request = new Request.Builder().url(url).get().build(); Response response = okhttpClient.newCall(request).execute(); logger.debug(String.format(REQUEST_RESPONSE_INFO, request, response)); if (response.code() != 200) { throw new HarborClientException(String.valueOf(response.code()), response.message()); } return mapper.readValue(response.body().string(), new TypeReference<List<Log>>() { }); }
Example #16
Source File: WebAppHelper.java From xDrip with GNU General Public License v3.0 | 6 votes |
@Override protected Integer doInBackground(String... url) { try { Log.d(TAG, "Processing URL: " + url[0]); Request request = new Request.Builder() .header("User-Agent", "Mozilla/5.0 (jamorham)") .header("Connection", "close") .url(url[0]) .build(); client.setConnectTimeout(15, TimeUnit.SECONDS); client.setReadTimeout(30, TimeUnit.SECONDS); client.setWriteTimeout(30, TimeUnit.SECONDS); final Response response = client.newCall(request).execute(); if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); body = response.body().bytes(); } catch (Exception e) { Log.d(TAG, "Exception in background task: " + e.toString()); } return body.length; }
Example #17
Source File: SwaggerHubClient.java From swaggerhub-maven-plugin with Apache License 2.0 | 6 votes |
public String getDefinition(SwaggerHubRequest swaggerHubRequest) throws MojoExecutionException { 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 MojoExecutionException( String.format("Failed to download definition: %s", response.body().string()) ); } else { jsonResponse = response.body().string(); } } catch (IOException e) { throw new MojoExecutionException("Failed to download definition", e); } return jsonResponse; }
Example #18
Source File: SignUpPresenterImpl.java From meiShi with Apache License 2.0 | 6 votes |
@Override public void getVerifySMS(String phone, String pwd) { model.getVerifySMS(phone, pwd, new ResultCallback<String>() { @Override public void onError(Request request, Exception e) { view.showVerifyError(e.getMessage()); } @Override public void onResponse(String response) { if (response.equalsIgnoreCase("true")) { view.showVerifySuccerss(); } } }); }
Example #19
Source File: ZalyHttpClient.java From wind-im 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 #20
Source File: SwaggerHubClient.java From swaggerhub-gradle-plugin with Apache License 2.0 | 5 votes |
private Request buildPostRequest(HttpUrl httpUrl, MediaType mediaType, String content) { return new Request.Builder() .url(httpUrl) .addHeader("Content-Type", mediaType.toString()) .addHeader("Authorization", token) .addHeader("User-Agent", "swaggerhub-gradle-plugin") .post(RequestBody.create(mediaType, content)) .build(); }
Example #21
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 #22
Source File: BaseApi.java From rox-android with Apache License 2.0 | 5 votes |
protected <T> T put(String url, Object payload, Class<T> responseClass) { Log.d(TAG, url); Request.Builder requestBuilder = buildRequestForJson(url); if (payload != null) { requestBuilder.header(Header.CONTENT_TYPE.getValue(), ContentType.APPLICATION_JSON.getMimeType()) .put(RequestBody.create(JSON_MEDIA_TYPE, new Gson().toJson(payload))) .build(); } else requestBuilder.put(RequestBody.create(null, new byte[0])); return callForResult(requestBuilder.build(), responseClass); }
Example #23
Source File: TokenRefreshInterceptorTest.java From wear-notify-for-reddit with Apache License 2.0 | 5 votes |
private Matcher<Request> hasUrl(String url) { return new FeatureMatcher<Request, String>(equalTo(url), "Url", "Unexpected url") { @Override protected String featureValueOf(Request actual) { return actual.urlString(); } }; }
Example #24
Source File: OkHttpClientInstrumentation.java From apm-agent-java with Apache License 2.0 | 5 votes |
@Advice.OnMethodEnter(suppress = Throwable.class) private static void onBeforeExecute(@Advice.FieldValue(value = "originalRequest", typing = Assigner.Typing.DYNAMIC, readOnly = false) @Nullable Object originalRequest, @Advice.Local("span") Span span) { if (tracer == null || tracer.getActive() == null) { return; } final AbstractSpan<?> parent = tracer.getActive(); if (originalRequest == null) { return; } if (originalRequest instanceof com.squareup.okhttp.Request) { com.squareup.okhttp.Request request = (com.squareup.okhttp.Request) originalRequest; HttpUrl httpUrl = request.httpUrl(); span = HttpClientHelper.startHttpClientSpan(parent, request.method(), httpUrl.toString(), httpUrl.scheme(), OkHttpClientHelper.computeHostName(httpUrl.host()), httpUrl.port()); if (span != null) { span.activate(); if (headerSetterHelperManager != null) { TextHeaderSetter<Request.Builder> headerSetter = headerSetterHelperManager.getForClassLoaderOfClass(Request.class); if (headerSetter != null) { Request.Builder builder = ((com.squareup.okhttp.Request) originalRequest).newBuilder(); span.propagateTraceContext(builder, headerSetter); originalRequest = builder.build(); } } } } }
Example #25
Source File: SwaggerHubClient.java From swaggerhub-maven-plugin with Apache License 2.0 | 5 votes |
private Request buildPutRequest(HttpUrl httpUrl, MediaType mediaType, String content) { return new Request.Builder() .url(httpUrl) .addHeader("Content-Type", mediaType.toString()) .addHeader("Authorization", token) .addHeader("User-Agent", "swaggerhub-maven-plugin") .put(RequestBody.create(mediaType, content)) .build(); }
Example #26
Source File: TokenRefreshInterceptorTest.java From wear-notify-for-reddit with Apache License 2.0 | 5 votes |
private Matcher<Request> hasAuthorisationHeader(String authHeader) { return new FeatureMatcher<Request, String>(equalTo(authHeader), "Authorisation header", "Unexpected auth header") { @Override protected String featureValueOf(Request actual) { return actual.header(AUTHORIZATION); } }; }
Example #27
Source File: OkhttpTestWithRxJava.java From codeexamples-android with Eclipse Public License 1.0 | 5 votes |
@Before public void setup() { client = new OkHttpClient(); request = new Request.Builder() .url("http://www.vogella.com/index.html") .build(); }
Example #28
Source File: CacheInterceptor.java From Gank-Veaer with GNU General Public License v3.0 | 5 votes |
@Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); Response response = chain.proceed(request); return response.newBuilder() .header(CACHE_CONTROL, "public, max-age=" + 60 * 60 * 24) // 缓存一天 .build(); }
Example #29
Source File: UPnPDevice.java From Android-UPnP-Browser with Apache License 2.0 | 5 votes |
public void downloadSpecs() throws Exception { Request request = new Request.Builder() .url(mLocation) .build(); Response response = mClient.newCall(request).execute(); if (!response.isSuccessful()) { throw new IOException("Unexpected code " + response); } mRawXml = response.body().string(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); InputSource source = new InputSource(new StringReader(mRawXml)); Document doc; try { doc = db.parse(source); } catch (SAXParseException e) { return; } XPath xPath = XPathFactory.newInstance().newXPath(); mProperties.put("xml_icon_url", xPath.compile("//icon/url").evaluate(doc)); generateIconUrl(); mProperties.put("xml_friendly_name", xPath.compile("//friendlyName").evaluate(doc)); }
Example #30
Source File: UserMediasPresenterImpl.java From meiShi with Apache License 2.0 | 5 votes |
@Override public void getMedias(int uid, int page) { model.getMedias(uid, page, new ResultCallback<List<MediaEntity>>() { @Override public void onError(Request request, Exception e) { view.showError(); } @Override public void onResponse(List<MediaEntity> response) { view.showVideo(response); } }); }