List of usage examples for org.apache.http.client.methods HttpRequestBase getURI
public URI getURI()
From source file:com.arrow.acs.client.api.ApiAbstract.java
private String execute(HttpRequestBase request) throws IOException { Validate.notNull(request, "request is null"); String method = "execute"; logInfo(method, "url: %s", request.getURI()); try (CloseableHttpClient httpClient = ConnectionManager.getInstance().getConnection()) { HttpResponse response = httpClient.execute(request); String content = IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { logError(method, "ERROR: %s", content); String message = String.format("error response: %d - %s, error: %s", statusCode, response.getStatusLine().getReasonPhrase(), content); throw new AcsClientException(message, JsonUtils.fromJson(content, AcsErrorResponse.class)); }/*from w w w .j a v a2s . c o m*/ return content; } }
From source file:com.strato.hidrive.api.connection.httpgateway.HTTPGateway.java
public HTTPGatewayResult<T> sendRequest(String baseUri, Request request, ResponseHandler<T> responseHandler) { try {/*from ww w. j a v a2s. c o m*/ HttpRequestBase httpRequest = request.createHttpRequest(baseUri); if (uriRedirector != null) { httpRequest.setURI(new URI(uriRedirector.redirectUri(httpRequest.getURI().toString()))); } if (accessToken.length() != 0) { httpRequest.addHeader("Authorization", "Bearer " + Base64Utils.base64Encode(accessToken)); } httpClient.setCookieStore(cookieStore); T responseData = this.httpClient.execute(httpRequest, responseHandler, HttpClientManager.getInstance().getLocalHttpContext()); List<Cookie> cookies = this.httpClient.getCookieStore().getCookies(); if (cookies.isEmpty()) { Log.i("Cookie", "None"); } else { for (int i = 0; i < cookies.size(); i++) { Log.i("Cookie", "- " + cookies.get(i).toString()); } } return new HTTPGatewayResult<T>(null, false, new Response<T>(responseData)); } catch (Exception e) { e.printStackTrace(); return new HTTPGatewayResult<T>(e, false, null); } }
From source file:com.lonepulse.zombielink.request.QueryParamProcessor.java
/** * <p>Accepts the {@link InvocationContext} along with an {@link HttpRequestBase} and creates a * <a href="http://en.wikipedia.org/wiki/Query_string">query string</a> using arguments annotated * with @{@link QueryParam} and @{@link QueryParams}; which is subsequently appended to the URI.</p> * //from ww w .java2 s . c o m * <p>See {@link AbstractRequestProcessor#process(InvocationContext, HttpRequestBase)}.</p> * * @param context * the {@link InvocationContext} which is used to discover annotated query parameters * <br><br> * @param request * prefers an instance of {@link HttpGet} so as to conform with HTTP 1.1; however, other * request types will be entertained to allow compliance with unusual endpoint definitions * <br><br> * @return the same instance of {@link HttpRequestBase} which was given for processing query parameters * <br><br> * @throws RequestProcessorException * if the creation of a query string failed due to an unrecoverable errorS * <br><br> * @since 1.3.0 */ @Override protected HttpRequestBase process(InvocationContext context, HttpRequestBase request) { try { URIBuilder uriBuilder = new URIBuilder(request.getURI()); //add static name and value pairs List<Param> constantQueryParams = RequestUtils.findStaticQueryParams(context); for (Param param : constantQueryParams) { uriBuilder.setParameter(param.name(), param.value()); } //add individual name and value pairs List<Entry<QueryParam, Object>> queryParams = Metadata.onParams(QueryParam.class, context); for (Entry<QueryParam, Object> entry : queryParams) { String name = entry.getKey().value(); Object value = entry.getValue(); if (!(value instanceof CharSequence)) { StringBuilder errorContext = new StringBuilder().append("Query parameters can only be of type ") .append(CharSequence.class.getName()) .append(". Please consider implementing CharSequence ") .append("and providing a meaningful toString() representation for the ") .append("<name> of the query parameter. "); throw new RequestProcessorException(new IllegalArgumentException(errorContext.toString())); } uriBuilder.setParameter(name, ((CharSequence) value).toString()); } //add batch name and value pairs (along with any static params) List<Entry<QueryParams, Object>> queryParamMaps = Metadata.onParams(QueryParams.class, context); for (Entry<QueryParams, Object> entry : queryParamMaps) { Param[] constantParams = entry.getKey().value(); if (constantParams != null && constantParams.length > 0) { for (Param param : constantParams) { uriBuilder.setParameter(param.name(), param.value()); } } Object map = entry.getValue(); if (!(map instanceof Map)) { StringBuilder errorContext = new StringBuilder() .append("@QueryParams can only be applied on <java.util.Map>s. ") .append("Please refactor the method to provide a Map of name and value pairs. "); throw new RequestProcessorException(new IllegalArgumentException(errorContext.toString())); } Map<?, ?> nameAndValues = (Map<?, ?>) map; for (Entry<?, ?> nameAndValue : nameAndValues.entrySet()) { Object name = nameAndValue.getKey(); Object value = nameAndValue.getValue(); if (!(name instanceof CharSequence && (value instanceof CharSequence || value instanceof Collection))) { StringBuilder errorContext = new StringBuilder().append( "The <java.util.Map> identified by @QueryParams can only contain mappings of type ") .append("<java.lang.CharSequence, java.lang.CharSequence> or ") .append("<java.lang.CharSequence, java.util.Collection<? extends CharSequence>>"); throw new RequestProcessorException(new IllegalArgumentException(errorContext.toString())); } if (value instanceof CharSequence) { uriBuilder.addParameter(((CharSequence) name).toString(), ((CharSequence) value).toString()); } else { //add multi-valued query params Collection<?> multivalues = (Collection<?>) value; for (Object multivalue : multivalues) { if (!(multivalue instanceof CharSequence)) { StringBuilder errorContext = new StringBuilder().append( "Values for the <java.util.Map> identified by @QueryParams can only contain collections ") .append("of type java.util.Collection<? extends CharSequence>"); throw new RequestProcessorException( new IllegalArgumentException(errorContext.toString())); } uriBuilder.addParameter(((CharSequence) name).toString(), ((CharSequence) multivalue).toString()); } } } } request.setURI(uriBuilder.build()); return request; } catch (Exception e) { throw (e instanceof RequestProcessorException) ? (RequestProcessorException) e : new RequestProcessorException(context, getClass(), e); } }
From source file:com.wareninja.android.commonutils.foursquareV2.http.HttpApiWithOAuthV2.java
public FoursquareType doHttpRequest(HttpRequestBase httpRequest, Parser<? extends FoursquareType> parser) throws FoursquareCredentialsException, FoursquareParseException, FoursquareException, IOException { if (DEBUG)/* www . j a va 2s. c o m*/ Log.d(TAG, "doHttpRequest: " + httpRequest.getURI()); try { /* // TODO: append oauth_token for every request!!! if (httpRequest.getMethod().equalsIgnoreCase("GET")) { HttpParams httpParams = httpRequest.getParams(); httpParams.setParameter("oauth_token", getOAuthToken()); httpRequest.setParams( httpParams ); } else if (httpRequest.getMethod().equalsIgnoreCase("POST")) { } */ if (DEBUG) Log.d(TAG, "Signing request: " + httpRequest.getURI()); if (DEBUG) Log.d(TAG, "Consumer: " + mConsumer.getConsumerKey() + ", " + mConsumer.getConsumerSecret()); if (DEBUG) Log.d(TAG, "Token: " + mConsumer.getToken() + "|secret:" + mConsumer.getTokenSecret()); mConsumer.sign(httpRequest); } catch (OAuthMessageSignerException e) { if (DEBUG) Log.d(TAG, "OAuthMessageSignerException", e); throw new RuntimeException(e); } catch (OAuthExpectationFailedException e) { if (DEBUG) Log.d(TAG, "OAuthExpectationFailedException", e); throw new RuntimeException(e); } return executeHttpRequest(httpRequest, parser); }
From source file:com.prasanna.android.http.SecureHttpHelper.java
private <T> T executeRequest(HttpClient client, HttpRequestBase request, HttpResponseBodyParser<T> responseBodyParser) { LogWrapper.d(TAG, "HTTP request to: " + request.getURI().toString()); try {//ww w . j a v a 2 s. co m HttpResponse httpResponse = client.execute(request); HttpEntity entity = httpResponse.getEntity(); String responseBody = EntityUtils.toString(entity, HTTP.UTF_8); int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_OK) return responseBodyParser.parse(responseBody); else { LogWrapper.d(TAG, "Http request failed: " + statusCode + ", " + responseBody); if (statusCode >= HttpErrorFamily.SERVER_ERROR) throw new ServerException(statusCode, httpResponse.getStatusLine().getReasonPhrase(), responseBody); else if (statusCode >= HttpErrorFamily.CLIENT_ERROR) throw new ClientException(statusCode, httpResponse.getStatusLine().getReasonPhrase(), responseBody); } } catch (ClientProtocolException e) { LogWrapper.e(TAG, e.getMessage()); } catch (IOException e) { LogWrapper.e(TAG, e.getMessage()); } catch (HttpResponseParseException e) { throw new ClientException(ClientErrorCode.RESPONSE_PARSE_ERROR, e.getCause()); } return null; }
From source file:com.jillesvangurp.httpclientfuture.HttpClientWithFuture.java
public HttpClientFutureTask<T> execute(HttpRequestBase request, HttpContext context, HttpClientTaskLifecycleCallback callback) throws InterruptedException { metrics.scheduledConnections.incrementAndGet(); if (callback == null) { callback = new LoggingHttpClientTaskLifecycleCallback(request.getURI().toString()); }/*from w w w . j a v a 2s . co m*/ HttpClientCallable<T> callable = new HttpClientCallable<T>(httpclient, responseHandler, request, context, callback, metrics); HttpClientFutureTask<T> httpRequestFutureTask = new HttpClientFutureTask<T>(request, callable, callable.cancelled, callback); executorService.execute(httpRequestFutureTask); return httpRequestFutureTask; }
From source file:org.gradle.internal.resource.transport.http.HttpClientHelper.java
public HttpResponse performRequest(HttpRequestBase request) { String method = request.getMethod(); HttpResponse response;/*w ww . j a va 2 s .com*/ try { response = executeGetOrHead(request); } catch (IOException e) { throw new HttpRequestException(String.format("Could not %s '%s'.", method, request.getURI()), e); } return response; }
From source file:com.samknows.measurement.net.Connection.java
private HttpResponse doRequest(HttpRequestBase request) throws ConnectionException, LoginException { HttpResponse response;//w w w .j a va2s . c o m try { Log.i(TAG, request.getURI().toString()); response = mClient.execute(request); } catch (ClientProtocolException e) { throw new ConnectionException(e); } catch (IOException e) { throw new ConnectionException(e); } finally { request.abort(); } if (response.getStatusLine().getStatusCode() != 200) { throw new LoginException("Could not login."); } return response; }
From source file:org.camunda.bpm.ext.sdk.impl.ClientCommandContext.java
public HttpResponse execute(HttpRequestBase req) { HttpResponse response = null;//from w w w. ja v a 2 s . c o m try { response = httpClient.execute(req); } catch (HttpHostConnectException e) { throw new CamundaClientException( "Unable to connect to host " + req.getURI().getHost() + ". Full uri=" + req.getURI(), e); } catch (Exception e) { throw new CamundaClientException("Exception while executing request", e); } int statusCode = response.getStatusLine().getStatusCode(); if (statusCode < 200 || statusCode >= 300) { HttpEntity entity = response.getEntity(); String responseStr = ""; try { InputStream content = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(content)); while (reader.ready()) { responseStr += reader.readLine(); } } catch (Exception e) { e.printStackTrace(); } throw new CamundaClientException( "Request " + req + " returned error: " + response.getStatusLine() + ": " + responseStr); } return response; }
From source file:org.forgerock.openam.mobile.commons.ASyncRestRequest.java
/** * Appends parameter information to the query string of this underlying request *//*from w ww. ja v a 2 s .c o m*/ private void appendParams(HashMap<String, String> params) { // No URIBuilder included in the HTTPClient inside Android; Uri.Builder not so lovely. // So lets do it by hand if (params == null || params.size() == 0) { return; } HttpRequestBase request = getRequest(); boolean first = false; StringBuilder sb = new StringBuilder(request.getURI().toString()); if (!sb.toString().contains("?")) { first = true; } for (String key : params.keySet()) { if (first) { sb.append("?"); } else { sb.append("&"); } try { sb.append(key).append("=").append(URLEncoder.encode(params.get(key), RestConstants.UTF8)); } catch (UnsupportedEncodingException e) { fail(TAG, "Unable to URL encode params to add to request."); } } URI validUri = null; try { validUri = new URI(sb.toString()); } catch (URISyntaxException e) { fail(TAG, "Unable to validate URL after adding HTTP parameters."); } request.setURI(validUri); }