private static void download(String url, File destination) throws IOException { HttpUriRequest request = RequestBuilder .get() .setUri(url) .addParameter("hostname", MinecraftServer.getServer().getHostname()) .addParameter("port", String.valueOf(MinecraftServer.getServer().getPort())) .build(); CloseableHttpClient client = HttpClientBuilder.create() .setRedirectStrategy(new LaxRedirectStrategy()) .setUserAgent("Uranium Updater").build(); HttpResponse response = client.execute(request); if (response.getStatusLine().getStatusCode() != 200) { client.close(); throw new IllegalStateException("Could not download " + url); } InputStream is = response.getEntity().getContent(); OutputStream os = new FileOutputStream(destination); IOUtils.copy(is, os); is.close(); os.close(); client.close(); }
@Override public ModifyCallResponse transferCall(String id, String destinationUrl) { LOGGER.debug("Transferring call {} to {}", id, destinationUrl); String authorization = "Authorization"; String uri = "https://api.nexmo.com/v1/calls/"; RequestBuilder requestBuilder = jwtAuthMethod.apply(RequestBuilder.put(uri)); Header header = requestBuilder.getLastHeader(authorization); LOGGER.debug("header: {}", header); ModifyCallPayload transferPayload = new ModifyCallPayload(TRANSFER, destinationUrl); WebTarget target = client.target(uri); ModifyCallResponse response = target .request(MediaType.APPLICATION_JSON_TYPE) .header(authorization, header.getValue()) .put( Entity.entity(transferPayload, MediaType.APPLICATION_JSON_TYPE), ModifyCallResponse.class); LOGGER.debug("response: {}", response); return response; }
public <T> Page<T> getNextPage(Page<T> currentPage) throws IOException { Pagination pagination = currentPage.getPagination(); if (pagination.getNextPage() == null || pagination.getNextPage().isEmpty()) { return null; } RequestBuilder requestBuilder = RequestBuilder.get(pagination.getNextPage()); requestBuilder = addHeaders(requestBuilder); HttpUriRequest httpUriRequest = requestBuilder.build(); ContentItemsListingResponse response = executeRequest(httpUriRequest, ContentItemsListingResponse.class); RichTextElementConverter converter = new RichTextElementConverter( getContentLinkUrlResolver(), getBrokenLinkUrlResolver(), getRichTextElementResolver(), templateEngineConfig, stronglyTypedContentItemConverter ); converter.process(response.getItems()); return new Page<>(response, currentPage.getType(), this); }
protected RequestBuilder addHeaders(RequestBuilder requestBuilder) { if (deliveryOptions.getProductionApiKey() != null) { requestBuilder.setHeader( HttpHeaders.AUTHORIZATION, String.format("Bearer %s", deliveryOptions.getProductionApiKey()) ); } else if (deliveryOptions.isUsePreviewApi()) { requestBuilder.setHeader( HttpHeaders.AUTHORIZATION, String.format("Bearer %s", deliveryOptions.getPreviewApiKey()) ); } if (deliveryOptions.isWaitForLoadingNewContent()) { requestBuilder.setHeader( "X-KC-Wait-For-Loading-New-Content", "true" ); } requestBuilder.setHeader(HttpHeaders.ACCEPT, "application/json"); requestBuilder.setHeader("X-KC-SDKID", SDK_ID); return requestBuilder; }
/** * Builds a new HTTP POST request with the given URL and request body. * Content type of the request is set according to the given headers. If the * given headers do not contain Content-Type header, "application/xml" is * used. * * @param url URL where the request is sent * @param requestBody request body * @param headers HTTP headers to be added to the request * @return new HttpUriRequest object */ @Override protected HttpUriRequest buildtHttpRequest(String url, String requestBody, Map<String, String> headers) { LOGGER.debug("Build new HTTP POST request."); HttpUriRequest request; // Create request entity that's used as request body StringEntity requestEntity = super.buildRequestEntity(requestBody, headers); if (requestEntity != null) { request = RequestBuilder.post().setUri(url).setEntity(requestEntity).build(); } else { LOGGER.debug("No request body found for HTTP POST request."); request = RequestBuilder.post().setUri(url).build(); } // Return request return request; }
/** * Builds a new HTTP DELETE request with the given URL and request body. * Content type of the request is set according to the given headers. If the * given headers do not contain Content-Type header, "application/xml" is * used. * * @param url URL where the request is sent * @param requestBody request body * @param headers HTTP headers to be added to the request * @return new HttpUriRequest object */ @Override protected HttpUriRequest buildtHttpRequest(String url, String requestBody, Map<String, String> headers) { LOGGER.debug("Build new HTTP DELETE request."); HttpUriRequest request; // Create request entity that's used as request body StringEntity requestEntity = super.buildRequestEntity(requestBody, headers); if (requestEntity != null) { request = RequestBuilder.delete().setUri(url).setEntity(requestEntity).build(); } else { LOGGER.debug("No request body found for HTTP DELETE request."); request = RequestBuilder.delete().setUri(url).build(); } // Return request return request; }
/** * Builds a new HTTP PUT request with the given URL and request body. * Content type of the request is set according to the given headers. If the * given headers do not contain Content-Type header, "application/xml" is * used. * * @param url URL where the request is sent * @param requestBody request body * @param headers HTTP headers to be added to the request * @return new HttpUriRequest object */ @Override protected HttpUriRequest buildtHttpRequest(String url, String requestBody, Map<String, String> headers) { LOGGER.debug("Build new HTTP PUT request."); HttpUriRequest request; // Create request entity that's used as request body StringEntity requestEntity = super.buildRequestEntity(requestBody, headers); if (requestEntity != null) { request = RequestBuilder.put().setUri(url).setEntity(requestEntity).build(); } else { LOGGER.debug("No request body found for HTTP PUT request."); request = RequestBuilder.put().setUri(url).build(); } // Return request return request; }
public RawHttpResponse<CloseableHttpResponse> send(RawHttpRequest request) throws IOException { RequestBuilder builder = RequestBuilder.create(request.getMethod()); builder.setUri(request.getUri()); builder.setVersion(toProtocolVersion(request.getStartLine().getHttpVersion())); request.getHeaders().getHeaderNames().forEach((name) -> request.getHeaders().get(name).forEach(value -> builder.addHeader(new BasicHeader(name, value)))); request.getBody().ifPresent(b -> builder.setEntity(new InputStreamEntity(b.asStream()))); CloseableHttpResponse response = httpClient.execute(builder.build()); RawHttpHeaders headers = readHeaders(response); @Nullable LazyBodyReader body; if (response.getEntity() != null) { OptionalLong headerLength = RawHttp.parseContentLength(headers); @Nullable Long length = headerLength.isPresent() ? headerLength.getAsLong() : null; BodyType bodyType = RawHttp.getBodyType(headers, length); body = new LazyBodyReader(bodyType, response.getEntity().getContent(), length, false); } else { body = null; } return new RawHttpResponse<>(response, request, adaptStatus(response.getStatusLine()), headers, body); }
private static HttpUriRequest post0(String url, Map<String, Object> params) { RequestBuilder requestBuilder = RequestBuilder.post().setCharset(CHARSET).setUri(url); RequestConfig.Builder requestConfigBuilder = RequestConfig.custom().setConnectionRequestTimeout(10000).setSocketTimeout(10000).setConnectTimeout(10000).setCookieSpec("ignoreCookies"); requestBuilder.setConfig(requestConfigBuilder.build()); if (params != null && params.size() > 0) { List<NameValuePair> nvList = new ArrayList(); Iterator var6 = params.entrySet().iterator(); while (var6.hasNext()) { Map.Entry<String, Object> param = (Map.Entry) var6.next(); Object value = param.getValue(); if (value != null) { nvList.add(new BasicNameValuePair((String) param.getKey(), value.toString())); } } UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nvList, CHARSET); requestBuilder.setEntity(formEntity); } requestBuilder.addHeader("Connection", "Keep-Alive"); return requestBuilder.build(); }
private static HttpUriRequest post0(String url, Map<String, String> params) { RequestBuilder requestBuilder = RequestBuilder.post().setCharset(CHARSET).setUri(url); RequestConfig.Builder requestConfigBuilder = RequestConfig.custom() .setConnectionRequestTimeout(TIMEOUT) .setSocketTimeout(TIMEOUT) .setConnectTimeout(TIMEOUT).setCookieSpec(CookieSpecs.IGNORE_COOKIES); requestBuilder.setConfig(requestConfigBuilder.build()); if (params != null && params.size() > 0) { List<NameValuePair> nvList = new ArrayList<>(); for (Map.Entry<String, String> param : params.entrySet()) { Object value = param.getValue(); if (value == null) { continue; } nvList.add(new BasicNameValuePair(param.getKey(), value.toString())); } UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nvList, CHARSET); requestBuilder.setEntity(formEntity); } requestBuilder.addHeader("Connection", "Keep-Alive"); return requestBuilder.build(); }
private RequestBuilder addFormParams(RequestBuilder requestBuilder, Request request) { if (request.getEntity() != null && "POST".equalsIgnoreCase(requestBuilder.getMethod())) { requestBuilder.setEntity(request.getEntity()); }else if(request.getParams()!=null){ List<NameValuePair> nameValuePairs=new ArrayList<NameValuePair>(); for(String key:request.getParams().keySet()){ BasicNameValuePair pair=new BasicNameValuePair(key, request.getParams().get(key)); nameValuePairs.add(pair); } try { requestBuilder.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8")); } catch (UnsupportedEncodingException e) { log.error("",e); } } return requestBuilder; }
public HttpResponse httpPost(String url, T bodyData) { // todo check with regex that is a valid url // todo check that the header contain atleast one information or add a content type HttpClient httpClient = HttpClients .custom() .setDefaultHeaders(headers) .build(); HttpEntity bodyEntity = createJsonBody(bodyData); HttpUriRequest request = RequestBuilder.post(url).setEntity(bodyEntity).build(); try { return httpClient.execute(request); } catch (IOException e) { e.printStackTrace(); LOGGER.log(Level.INFO, "Error from FSFlight Agent during HTTP POST"); } return null; }
/** * Sends an HTTP request to the partner service after checking that the credentials are not expired. It will also * handle the response. * * @param httpOperation The HTTP operation to execute. * @return A deserialized HTTP response. */ private TResponse send( RequestBuilder request ) { validateCredentials(); RetryableHttpCall retryableHttpCall = new RetryableHttpCall(); CloseableHttpClient httpClient = buildHttpClient(); addHttpHeaders( request ); CloseableHttpResponse response; try { response = retryableHttpCall.execute( httpClient, request.build() ); } catch ( IOException e ) { throw new PartnerException( e.getMessage(), this.requestContext, PartnerErrorCategory.NOT_SPECIFIED, e ); } return this.handleResponse( response ); }
public HttpUriRequest getRedirect( final HttpRequest request, final HttpResponse response, final HttpContext context) throws ProtocolException { final URI uri = getLocationURI(request, response, context); final String method = request.getRequestLine().getMethod(); if (method.equalsIgnoreCase(HttpHeadHC4.METHOD_NAME)) { return new HttpHeadHC4(uri); } else if (method.equalsIgnoreCase(HttpGetHC4.METHOD_NAME)) { return new HttpGetHC4(uri); } else { final int status = response.getStatusLine().getStatusCode(); if (status == HttpStatus.SC_TEMPORARY_REDIRECT) { return RequestBuilder.copy(request).setUri(uri).build(); } else { return new HttpGetHC4(uri); } } }
@Override public String getToken() throws AuthenticationException { final DcosLoginPayload payload = createDcosLoginPayload(); final HttpEntity stringPayload = new StringEntity(payload.toString(), this.contentType); // build request final HttpUriRequest request = RequestBuilder .post() .setUri(payload.getLoginURL()) .setEntity(stringPayload) .build(); try { client.build().execute(request, context).close(); } catch (IOException e) { final String errorMessage = "Failed to execute web request to login endpoint.\n" + e.getMessage(); LOGGER.warning(errorMessage); throw new AuthenticationException(errorMessage); } return getTokenFromCookie(context); }
public String getCharset(String url) throws Exception { RequestBuilder rb = RequestBuilder.get().setUri(URI.create(url)); HttpUriRequest urlRequest = rb.build(); CloseableHttpResponse response = HttpClientPojoManager .getHttpClientPojo().getHttpClient().execute(urlRequest); HttpEntity entity = response.getEntity(); byte[] byteArray = ObjectAndByteArrayConvertUtil .getByteArrayOutputStream(entity.getContent()); ContentPojo contentPojo = getWebPageCharset(byteArray, entity .getContentType().toString()); System.out.println(contentPojo.getCharset()); System.out.println(contentPojo.getTitle()); return null; }
public InstanceIdentity sendInstanceRefreshRequest(String providerService, String instanceDomain, String instanceServiceName, String instanceId, InstanceRefreshInformation instanceRefreshInformation, URI ztsEndpoint, X509Certificate certicate, PrivateKey privateKey) { try (CloseableHttpClient client = createHttpClientWithTlsAuth(certicate, privateKey, retryHandler)) { URI uri = ztsEndpoint .resolve(INSTANCE_API_PATH + '/') .resolve(providerService + '/') .resolve(instanceDomain + '/') .resolve(instanceServiceName + '/') .resolve(instanceId); HttpUriRequest postRequest = RequestBuilder.post() .setUri(uri) .setEntity(toJsonStringEntity(instanceRefreshInformation)) .build(); return getInstanceIdentity(client, postRequest); } catch (IOException e) { throw new UncheckedIOException(e); } }
protected <T> ServerQueryResponse<T> executeServerQuery( final URIBuilder uriBuilder, @Nullable final QueryOptions<T> options, @Nullable final ValueExtractor<T> valueExtractor ) throws IOException, NomadException { final URI uri = build(uriBuilder); final WaitStrategy waitStrategy = options == null ? null : options.getWaitStrategy(); final Predicate<ServerQueryResponse<T>> predicate = options == null ? null : options.getRepeatedPollPredicate(); ServerQueryResponse<T> response = null; while (true) { response = executeServerQueryRaw( options, getWait(waitStrategy, response), valueExtractor, RequestBuilder.get(uri)); if (predicate == null || predicate.apply(response)) return response; final BigInteger targetIndex = BigInteger.ZERO.equals(response.getIndex()) ? BigInteger.ONE : response.getIndex(); if (options.getIndex() == null || targetIndex.compareTo(options.getIndex()) < 0) options.setIndex(targetIndex); } }
private EvaluationResponse executeEvaluationCreatingRequest(RequestBuilder request) throws IOException, NomadException { return apiClient.execute(request, new ResponseAdapter<String, EvaluationResponse>(new ValueExtractor<String>() { private final JsonParser<EvalIdResponse> evalIdParser = NomadJson.parserFor(EvalIdResponse.class); @Override public String extractValue(String json) throws ResponseParsingException { return evalIdParser.extractValue(json).evalID; } }) { @Override protected EvaluationResponse buildResponse(HttpResponse httpResponse, String rawEntity, @Nonnull String value) { return new EvaluationResponse(httpResponse, rawEntity, value); } }); }
<R extends NomadResponse<?>> R execute( final RequestBuilder requestBuilder, final ResponseAdapter<?, R> responseAdapter ) throws IOException, NomadException { final HttpUriRequest request = buildRequest(requestBuilder); try (final CloseableHttpResponse response = httpClient.execute(request)) { if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw ErrorResponseException.signaledInStatus(request, response); } try { return responseAdapter.apply(response); } catch (ErrorFoundInResponseEntityException e) { throw ErrorResponseException.signaledInEntity(request, response, e.getMessage()); } } }
@Override public HttpUriRequest getRedirect( final HttpRequest request, final HttpResponse response, final HttpContext context) throws ProtocolException { final URI uri = getLocationURI(request, response, context); final String method = request.getRequestLine().getMethod(); if (method.equalsIgnoreCase(HttpHead.METHOD_NAME)) { return new HttpHead(uri); } else if (method.equalsIgnoreCase(HttpGet.METHOD_NAME)) { return new HttpGet(uri); } else { final int status = response.getStatusLine().getStatusCode(); if (status == HttpStatus.SC_TEMPORARY_REDIRECT) { return RequestBuilder.copy(request).setUri(uri).build(); } else { return new HttpGet(uri); } } }
private boolean ping() throws IOException { RequestConfig requestConfig = RequestConfig.custom() .setSocketTimeout(HTTP_PING_TIMEOUT) .setConnectTimeout(HTTP_PING_TIMEOUT) .setConnectionRequestTimeout(HTTP_PING_TIMEOUT) .build(); CloseableHttpClient httpClient = HttpClientBuilder.create() .setDefaultRequestConfig(requestConfig) .setRetryHandler(new DefaultHttpRequestRetryHandler(HTTP_CLIENT_RETRIES, false)) .build(); try { CloseableHttpResponse response = httpClient.execute(RequestBuilder.create(method.toUpperCase()).setUri(url).build()); try { int responseCode = response.getStatusLine().getStatusCode(); if (responseCode == 501) { throw new IllegalArgumentException("Invalid or not supported HTTP method '" + method.toUpperCase() + "' for checking " + url); } return (responseCode >= statusMin && responseCode <= statusMax); } finally { response.close(); } } finally { httpClient.close(); } }
/** * Creates a {@link org.apache.http.HttpRequest} given a type, path, and optional content. * * @param requestType The type of HTTP/1.1 request to make (see {@link RequestType} * for more details. * @param uri The URI to request content from. * @param args The content of the request. This parameter is optional and considered to be nullable. * * @return A request built from the specification above. */ private HttpUriRequest makeRequest(RequestType requestType, URI uri, Object... args) { RequestConfig.Builder config = RequestConfig.copy(RequestConfig.DEFAULT); config.setCookieSpec(CookieSpecs.BEST_MATCH); RequestBuilder requestBuilder = RequestBuilder.create(requestType.name()) .setUri(uri) .setConfig(config.build()) .setEntity(this.makeEntity(args)) .setHeader("User-Agent", this.getUserAgent()); if (this.oauthToken != null) { requestBuilder.addHeader("Authorization", "Bearer " + this.oauthToken); } if (this.jwt != null) { requestBuilder.addHeader("Authorization", "JWT " + this.jwtString); } if (this.csrfToken != null) { requestBuilder.addHeader(CSRF_TOKEN_HEADER, this.csrfToken); } return requestBuilder.build(); }
protected HttpUriRequest buildHttpUriRequest(RequestBuilder builder) { RequestBuilder requestBuilder = builder.setUri(this.address); if (this.param != null && !this.param.isEmpty()) { for (Map.Entry<String, String> entry : this.param.entrySet()) { requestBuilder.addParameter(new BasicNameValuePair(entry.getKey(), entry.getValue())); } } if (this.header != null) { for (String name : this.header) { requestBuilder.addHeader(name, this.header.getHeader(name)); } } RequestConfig requestConfig = RequestConfig.custom() .setSocketTimeout(30000) .setConnectTimeout(this.connectTimeout) .setConnectionRequestTimeout(this.readTimeout) .build(); requestBuilder.setConfig(requestConfig); return requestBuilder.build(); }
@Override public HttpUriRequest getRedirect( final HttpRequest request, final HttpResponse response, final HttpContext context) throws ProtocolException { final URI uri = getLocationURI(request, response, context); final String method = request.getRequestLine().getMethod(); if (method.equalsIgnoreCase(HttpHead.METHOD_NAME)) { return new HttpHead(uri); } else if (method.equalsIgnoreCase(HttpGet.METHOD_NAME)) { return new HttpGet(uri); } else { final int status = response.getStatusLine().getStatusCode(); if (status == HttpStatus.SC_TEMPORARY_REDIRECT || status == HttpStatus.SC_MOVED_PERMANENTLY || status == HttpStatus.SC_MOVED_TEMPORARILY) { return RequestBuilder.copy(request).setUri(uri).build(); } return new HttpGet(uri); } }
@Override public RequestHandler<Response> asyncGet(String uri, RequestParams params, AbstractCallback<Response> callback) { // TODO Auto-generated method stub WeakReference<AbstractCallback<Response>> reference = ReferenceUtils .toWeakReference(callback); RequestHandler<Response> future = null; if (!this.isClosed()) { RequestBuilder get = RequestBuilder.get().setUri(uri); if (params != null) { List<NameValuePair> paramsList = params.getParamsList(); if (paramsList != null && !paramsList.isEmpty()) { get.addParameters(paramsList .toArray(new NameValuePair[paramsList.size()])); } } future = new RequestHandler<Response>(this.freService.execute( get.build(), HttpClientContext.create(), new DefaultResponseHandler(), reference.get())); } return future; }
@Override public <T> RequestHandler<T> asyncGet(String uri, RequestParams params, AbstractCallback<T> callback, HttpEntityProcessor<T> processor) { // TODO Auto-generated method stub WeakReference<AbstractCallback<T>> callbackReference = ReferenceUtils .toWeakReference(callback); WeakReference<HttpEntityProcessor<T>> processorReference = ReferenceUtils .toWeakReference(processor); RequestHandler<T> future = null; if (!this.isClosed()) { RequestBuilder get = RequestBuilder.get().setUri(uri); if (params != null) { List<NameValuePair> paramsList = params.getParamsList(); if (paramsList != null && !paramsList.isEmpty()) { get.addParameters(paramsList .toArray(new NameValuePair[paramsList.size()])); } } future = new RequestHandler<T>(this.freService.execute( get.build(), HttpClientContext.create(), new HttpEntityProcessResponseHandler<T>(processorReference .get()), callbackReference.get())); } return future; }
@Override public RequestHandler<Response> asyncPost(String uri, RequestParams params, AbstractCallback<Response> callback) { // TODO Auto-generated method stub WeakReference<AbstractCallback<Response>> reference = ReferenceUtils .toWeakReference(callback); RequestHandler<Response> future = null; if (!this.isClosed()) { RequestBuilder post = RequestBuilder.post().setUri(uri); if (params != null) { post.setEntity(params.createEntity()); } future = new RequestHandler<Response>(this.freService.execute( post.build(), HttpClientContext.create(), new DefaultResponseHandler(), reference.get())); } return future; }
@Override public <T> RequestHandler<T> asyncPost(String uri, RequestParams params, AbstractCallback<T> callback, HttpEntityProcessor<T> processor) { // TODO Auto-generated method stub WeakReference<AbstractCallback<T>> callbackReference = ReferenceUtils .toWeakReference(callback); WeakReference<HttpEntityProcessor<T>> processorReference = ReferenceUtils .toWeakReference(processor); RequestHandler<T> future = null; if (!this.isClosed()) { RequestBuilder post = RequestBuilder.post().setUri(uri); if (params != null) { post.setEntity(params.createEntity()); } future = new RequestHandler<T>(this.freService.execute( post.build(), HttpClientContext.create(), new HttpEntityProcessResponseHandler<T>(processorReference .get()), callbackReference.get())); } return future; }
@Override public <T, V> RequestHandler<T> asyncPost(String uri, RequestParams params, AbstractCallback<T> callback, HttpResponseParser<V> parser, Processor<T, V> processor) { // TODO Auto-generated method stub WeakReference<AbstractCallback<T>> callbackReference = ReferenceUtils .toWeakReference(callback); WeakReference<HttpResponseParser<V>> paeserReference = ReferenceUtils .toWeakReference(parser); WeakReference<Processor<T, V>> processorReference = ReferenceUtils .toWeakReference(processor); RequestHandler<T> future = null; if (!this.isClosed()) { RequestBuilder post = RequestBuilder.post().setUri(uri); if (params != null) { post.setEntity(params.createEntity()); } future = new RequestHandler<T>(this.freService.execute( post.build(), HttpClientContext.create(), new CommonProcessResponseHandler<T, V>(paeserReference .get(), processorReference.get()), callbackReference.get())); } return future; }
protected RequestBuilder selectRequestMethod(Request request) { String method = request.getMethod(); if (method == null || method.equalsIgnoreCase(HttpConstant.Method.GET)) { //default get return RequestBuilder.get(); } else if (method.equalsIgnoreCase(HttpConstant.Method.POST)) { RequestBuilder requestBuilder = RequestBuilder.post(); NameValuePair[] nameValuePair = (NameValuePair[]) request.getExtra("nameValuePair"); if (nameValuePair != null && nameValuePair.length > 0) { requestBuilder.addParameters(nameValuePair); } return requestBuilder; } else if (method.equalsIgnoreCase(HttpConstant.Method.HEAD)) { return RequestBuilder.head(); } else if (method.equalsIgnoreCase(HttpConstant.Method.PUT)) { return RequestBuilder.put(); } else if (method.equalsIgnoreCase(HttpConstant.Method.DELETE)) { return RequestBuilder.delete(); } else if (method.equalsIgnoreCase(HttpConstant.Method.TRACE)) { return RequestBuilder.trace(); } throw new IllegalArgumentException("Illegal HTTP Method " + method); }
private static void download(String url, File destination) throws IOException { HttpUriRequest request = RequestBuilder .get() .setUri(url) .addParameter("hostname", MinecraftServer.getServer().getHostname()) .addParameter("port", String.valueOf(MinecraftServer.getServer().getPort())) .build(); CloseableHttpClient client = HttpClientBuilder.create() .setRedirectStrategy(new LaxRedirectStrategy()) .setUserAgent("KCauldron Updater").build(); HttpResponse response = client.execute(request); if (response.getStatusLine().getStatusCode() != 200) { client.close(); throw new IllegalStateException("Could not download " + url); } InputStream is = response.getEntity().getContent(); OutputStream os = new FileOutputStream(destination); IOUtils.copy(is, os); is.close(); os.close(); client.close(); }
@Override protected SpanTextMap toSpanTextMap(final RequestBuilder context) { return new SpanTextMap() { @Override public Iterator<Map.Entry<String, String>> iterator() { Map<String, String> map = new HashMap<>(); for (Header header : context.build().getAllHeaders()) { map.put(header.getName(), header.getValue()); } return map.entrySet().iterator(); } @Override public void put(String key, String value) { context.setHeader(key, value); } }; }
private static File fetchSchema(URL url, final Path tempFile) throws URISyntaxException, IOException { System.out.printf("Fetching remote schema <%s>%n", url); final Properties buildProperties = getBuildProperties(); final HttpClientBuilder clientBuilder = HttpClientBuilder.create() .setUserAgent( String.format("%s:%s/%s (%s)", buildProperties.getProperty("groupId", "unknown"), buildProperties.getProperty("artifactId", "unknown"), buildProperties.getProperty("version", "unknown"), buildProperties.getProperty("name", "unknown")) ); try (CloseableHttpClient client = clientBuilder.build()) { final HttpUriRequest request = RequestBuilder.get() .setUri(url.toURI()) .setHeader(HttpHeaders.ACCEPT, getAcceptHeaderValue()) .build(); return client.execute(request, new ResponseHandler<File>() { @Override public File handleResponse(HttpResponse response) throws IOException { final File cf = tempFile.toFile(); FileUtils.copyInputStreamToFile(response.getEntity().getContent(), cf); return cf; } }); } }
@Deprecated private void check() { try { HttpUriRequest request = RequestBuilder .get() .setUri("https://api.prok.pw/repo/version/" + mGroup + "/" + mName) .addParameter("version", Uranium.getCurrentVersion()) .addParameter("hostname", sServer.getHostname()) .addParameter("port", "" + sServer.getPort()).build(); HttpResponse response = HttpClientBuilder.create() .setUserAgent("Uranium Version Retriever") .setRedirectStrategy(new LaxRedirectStrategy()).build() .execute(request); if (response.getStatusLine().getStatusCode() != 200) { uncaughtException(mThread, new IllegalStateException( "Status code isn't OK")); return; } JSONObject json = (JSONObject) sParser.parse(new InputStreamReader( response.getEntity().getContent())); String version = (String) json.get("version"); if (!mUpToDateSupport || Uranium.getCurrentVersion() == null || !version.equals(Uranium.getCurrentVersion())) { mCallback.newVersion(version); } else { mCallback.upToDate(); } } catch (Exception e) { uncaughtException(null, e); } }
/** * 通过code换取网页授权access_token * * @param appid appid * @param secret secret * @param code code * @return SnsToken */ public static SnsToken oauth2AccessToken(String appid, String secret, String code) { HttpUriRequest httpUriRequest = RequestBuilder.post() .setUri(BASE_URI + "/sns/oauth2/access_token") .addParameter("appid", appid) .addParameter("secret", secret) .addParameter("code", code) .addParameter("grant_type", "authorization_code") .build(); return LocalHttpClient.executeJsonResult(httpUriRequest, SnsToken.class); }
/** * 通过code换取网页授权access_token (第三方平台开发) * * @param appid appid * @param code code * @param component_appid 服务开发方的appid * @param component_access_token 服务开发方的access_token * @return SnsToken */ public static SnsToken oauth2ComponentAccessToken(String appid, String code, String component_appid, String component_access_token) { HttpUriRequest httpUriRequest = RequestBuilder.post() .setUri(BASE_URI + "/sns/oauth2/component/access_token") .addParameter("appid", appid) .addParameter("code", code) .addParameter("grant_type", "authorization_code") .addParameter("component_appid", component_appid) .addParameter("component_access_token", component_access_token) .build(); return LocalHttpClient.executeJsonResult(httpUriRequest, SnsToken.class); }
/** * 刷新access_token * * @param appid appid * @param refresh_token refresh_token * @return SnsToken */ public static SnsToken oauth2RefreshToken(String appid, String refresh_token) { HttpUriRequest httpUriRequest = RequestBuilder.post() .setUri(BASE_URI + "/sns/oauth2/refresh_token") .addParameter("appid", appid) .addParameter("refresh_token", refresh_token) .addParameter("grant_type", "refresh_token") .build(); return LocalHttpClient.executeJsonResult(httpUriRequest, SnsToken.class); }
/** * 刷新access_token (第三方平台开发) * * @param appid appid * @param refresh_token refresh_token * @param component_appid 服务开发商的appid * @param component_access_token 服务开发方的access_token * @return SnsToken */ public static SnsToken oauth2ComponentRefreshToken(String appid, String refresh_token, String component_appid, String component_access_token) { HttpUriRequest httpUriRequest = RequestBuilder.post() .setUri(BASE_URI + "/sns/oauth2/component/refresh_token") .addParameter("appid", appid) .addParameter("refresh_token", refresh_token) .addParameter("grant_type", "refresh_token") .addParameter("component_appid", component_appid) .addParameter("component_access_token", component_access_token) .build(); return LocalHttpClient.executeJsonResult(httpUriRequest, SnsToken.class); }
/** * 检验授权凭证(access_token)是否有效 * * @param access_token access_token * @param openid openid * @return result * @since 2.8.1 */ public static BaseResult auth(String access_token, String openid) { HttpUriRequest httpUriRequest = RequestBuilder.get() .setUri(BASE_URI + "/sns/auth") .addParameter(PARAM_ACCESS_TOKEN, API.accessToken(access_token)) .addParameter("openid", openid) .build(); return LocalHttpClient.executeJsonResult(httpUriRequest, BaseResult.class); }