List of usage examples for org.apache.http.client.methods HttpRequestBase getURI
public URI getURI()
From source file:com.basho.riak.client.util.ClientHelper.java
/** * Perform and HTTP request and return the resulting response using the * internal HttpClient.// w w w.j a v a 2s . com * * @param bucket * Bucket of the object receiving the request. * @param key * Key of the object receiving the request or null if the request * is for a bucket. * @param httpMethod * The HTTP request to perform; must not be null. * @param meta * Extra HTTP headers to attach to the request. Query parameters * are ignored; they should have already been used to construct * <code>httpMethod</code> and query parameters. * @param streamResponse * If true, the connection will NOT be released. Use * HttpResponse.getHttpMethod().getResponseBodyAsStream() to get * the response stream; HttpResponse.getBody() will return null. * * @return The HTTP response returned by Riak from executing * <code>httpMethod</code>. * * @throws RiakIORuntimeException * If an error occurs during communication with the Riak server * (i.e. HttpClient threw an IOException) */ HttpResponse executeMethod(String bucket, String key, HttpRequestBase httpMethod, RequestMeta meta, boolean streamResponse) { if (meta != null) { Map<String, String> headers = meta.getHeaders(); for (String header : headers.keySet()) { httpMethod.addHeader(header, headers.get(header)); } Map<String, String> queryParams = meta.getQueryParamMap(); if (!queryParams.isEmpty()) { URI originalURI = httpMethod.getURI(); List<NameValuePair> currentQuery = URLEncodedUtils.parse(originalURI, CharsetUtils.UTF_8.name()); List<NameValuePair> newQuery = new LinkedList<NameValuePair>(currentQuery); for (Map.Entry<String, String> qp : queryParams.entrySet()) { newQuery.add(new BasicNameValuePair(qp.getKey(), qp.getValue())); } // For this, HC4.1 authors, I hate you URI newURI; try { newURI = URIUtils.createURI(originalURI.getScheme(), originalURI.getHost(), originalURI.getPort(), originalURI.getPath(), URLEncodedUtils.format(newQuery, "UTF-8"), null); } catch (URISyntaxException e) { throw new RiakIORuntimeException(e); } httpMethod.setURI(newURI); } } HttpEntity entity; try { org.apache.http.HttpResponse response = httpClient.execute(httpMethod); int status = 0; if (response.getStatusLine() != null) { status = response.getStatusLine().getStatusCode(); } Map<String, String> headers = ClientUtils.asHeaderMap(response.getAllHeaders()); byte[] body = null; InputStream stream = null; entity = response.getEntity(); if (streamResponse) { stream = entity.getContent(); } else { if (null != entity) { body = EntityUtils.toByteArray(entity); } } if (!streamResponse) { EntityUtils.consume(entity); } return new DefaultHttpResponse(bucket, key, status, headers, body, stream, response, httpMethod); } catch (IOException e) { httpMethod.abort(); return toss(new RiakIORuntimeException(e)); } }
From source file:com.couchbase.cbadmin.client.CouchbaseAdmin.java
private JsonElement getResponseJson(HttpRequestBase req, int expectCode) throws RestApiException, IOException { logger.trace("{} {}", req.getMethod(), req.getURI()); CloseableHttpResponse res = cli.execute(req); try {/*from www. j a v a 2 s . co m*/ return extractResponse(res, req, expectCode); } finally { if (res.getEntity() != null) { // Ensure the content is completely removed from the stream, // so we can re-use the connection EntityUtils.consumeQuietly(res.getEntity()); } } }
From source file:com.eviware.soapui.impl.wsdl.endpoint.DefaultEndpointStrategy.java
public void filterRequest(SubmitContext context, Request wsdlRequest) { HttpRequestBase httpMethod = (HttpRequestBase) context.getProperty(BaseHttpRequestTransport.HTTP_METHOD); URI tempUri = (URI) context.getProperty(BaseHttpRequestTransport.REQUEST_URI); java.net.URI uri = null;// w w w .j a v a2 s. com try { uri = new java.net.URI(tempUri.toString()); } catch (URISyntaxException e) { SoapUI.logError(e); } if (uri == null) { uri = httpMethod.getURI(); } if (uri == null) { return; } EndpointDefaults def = defaults.get(uri.toString()); if (def == null) { synchronized (defaults) { for (String ep : defaults.keySet()) { try { URL tempUrl = new URL(PropertyExpander.expandProperties(context, ep)); if (tempUrl.toString().equals(uri.toString())) { def = defaults.get(ep); break; } } catch (Exception e) { // we can hide this exception for now, it could happen for // invalid property-expansions, etc // if the endpoint really is wrong there will be other // exception later on } } } if (def == null) return; } applyDefaultsToWsdlRequest(context, (AbstractHttpRequestInterface<?>) wsdlRequest, def); }
From source file:org.mocksy.rules.http.HttpProxyRule.java
public Response process(Request request) throws Exception { if (!(request instanceof HttpRequest)) { throw new IllegalArgumentException("ProxyRule only works for HttpRequests"); }// w ww . ja va2s. c o m HttpRequest httpRequest = (HttpRequest) request; HttpClient httpClient = new DefaultHttpClient(); HttpRequestBase method = this.getProxyMethod(httpRequest.getServletRequest()); // httpRequest.getServletRequest(); HttpResponse response = null; try { org.apache.http.HttpResponse httpResp = httpClient.execute(method); response = new HttpResponse("proxied response", httpResp.getEntity().getContent()); response.setStatusCode(httpResp.getStatusLine().getStatusCode()); // Pass response headers back to the client Header[] headerArrayResponse = httpResp.getAllHeaders(); for (Header header : headerArrayResponse) { response.setHeader(header.getName(), header.getValue()); } } catch (ConnectException e) { response = new HttpResponse("connection failed", "Proxied server at " + method.getURI() + " is unavailable."); response.setStatusCode(503); } return response; }
From source file:com.googlesource.gerrit.plugins.hooks.rtc.network.Transport.java
@SuppressWarnings("unchecked") private synchronized <T> T invoke(HttpRequestBase request, Object typeOrClass, String acceptType, String contentType) throws IOException, ClientProtocolException, ResourceNotFoundException { if (contentType != null) { request.addHeader("Content-Type", contentType); }//from w w w . jav a 2 s .c om if (acceptType != null) { request.addHeader("Accept", acceptType); } HttpResponse response = httpclient.execute(request); try { final int code = response.getStatusLine().getStatusCode(); if (code / 100 != 2) { if (code == 404) { log.debug("API call failed: " + response.getStatusLine()); throw new ResourceNotFoundException(request.getURI()); } else { log.debug("API call failed: " + response.getStatusLine()); throw new IOException("API call failed! " + response.getStatusLine()); } } String responseContentTypeString = getResponseContentType(response); String entityString = readEntityAsString(response); if (!assertValidContentType(acceptType, responseContentTypeString)) { log.error("Request to " + request.getURI() + " failed because of an invalid content returned:\n" + entityString); rtcClient.setLoggedIn(false); throw new InvalidContentTypeException("Wrong content type '" + responseContentTypeString + "' in HTTP response (Expected: " + acceptType + ")"); } if (typeOrClass != null && acceptType.endsWith("json") && responseContentTypeString.endsWith("json")) { Transport.etag.set(extractEtag(response)); if (typeOrClass instanceof ParameterizedType) { return gson.fromJson(entityString, (Type) typeOrClass); } else { return gson.fromJson(entityString, (Class<T>) typeOrClass); } } else if (typeOrClass != null && typeOrClass.equals(String.class)) { return (T) entityString; } else { if (log.isDebugEnabled()) log.debug(entityString); return null; } } finally { consumeHttpEntity(response.getEntity()); Transport.etag.set(null); } }
From source file:com.basho.riak.client.http.util.ClientHelper.java
/** * Perform and HTTP request and return the resulting response using the * internal HttpClient./*from w ww.j av a2s. com*/ * * @param bucket * Bucket of the object receiving the request. * @param key * Key of the object receiving the request or null if the request * is for a bucket. * @param httpMethod * The HTTP request to perform; must not be null. * @param meta * Extra HTTP headers to attach to the request. Query parameters * are ignored; they should have already been used to construct * <code>httpMethod</code> and query parameters. * @param streamResponse * If true, the connection will NOT be released. Use * HttpResponse.getHttpMethod().getResponseBodyAsStream() to get * the response stream; HttpResponse.getBody() will return null. * * @return The HTTP response returned by Riak from executing * <code>httpMethod</code>. * * @throws RiakIORuntimeException * If an error occurs during communication with the Riak server * (i.e. HttpClient threw an IOException) */ HttpResponse executeMethod(String bucket, String key, HttpRequestBase httpMethod, RequestMeta meta, boolean streamResponse) { if (meta != null) { Map<String, String> headers = meta.getHeaders(); for (String header : headers.keySet()) { httpMethod.addHeader(header, headers.get(header)); } Map<String, String> queryParams = meta.getQueryParamMap(); if (!queryParams.isEmpty()) { URI originalURI = httpMethod.getURI(); List<NameValuePair> currentQuery = URLEncodedUtils.parse(originalURI, CharsetUtils.UTF_8.name()); List<NameValuePair> newQuery = new LinkedList<NameValuePair>(currentQuery); for (Map.Entry<String, String> qp : queryParams.entrySet()) { newQuery.add(new BasicNameValuePair(qp.getKey(), qp.getValue())); } // For this, HC4.1 authors, I hate you URI newURI; try { newURI = new URIBuilder(originalURI).setQuery(URLEncodedUtils.format(newQuery, "UTF-8")) .build(); } catch (URISyntaxException e) { e.printStackTrace(); throw new RiakIORuntimeException(e); } httpMethod.setURI(newURI); } } HttpEntity entity = null; try { org.apache.http.HttpResponse response = httpClient.execute(httpMethod); int status = 0; if (response.getStatusLine() != null) { status = response.getStatusLine().getStatusCode(); } Map<String, String> headers = ClientUtils.asHeaderMap(response.getAllHeaders()); byte[] body = null; InputStream stream = null; entity = response.getEntity(); if (streamResponse) { stream = entity.getContent(); } else { if (null != entity) { body = EntityUtils.toByteArray(entity); } } key = extractKeyFromResponseIfItWasNotAlreadyProvided(key, response); return new DefaultHttpResponse(bucket, key, status, headers, body, stream, response, httpMethod); } catch (IOException e) { httpMethod.abort(); return toss(new RiakIORuntimeException(e)); } finally { if (!streamResponse && entity != null) { try { EntityUtils.consume(entity); } catch (IOException e) { // NO-OP } } } }
From source file:org.cloudifysource.restclient.GSRestClient.java
/** * Executes the given HTTP request and analyzes the response. Successful responses are expected to be formatted as * json strings, and are converted to a Map<String, Object> object. The map can use these keys: "status" * (success/error), "error"(reason code), "error_args" and "response". * <p/>//from w ww . ja v a 2s . c om * Errors of all types (IO, HTTP, rest etc.) are reported through an ErrorStatusException (RestException). * * @param httpMethod * The HTTP request to perform. * @return An object, the response body received from the rest service * @throws RestException * Reporting errors of all types (IO, HTTP, rest etc.) */ private Map<String, Object> readHttpAdminMethod(final HttpRequestBase httpMethod) throws RestException { InputStream instream = null; URI uri = httpMethod.getURI(); try { final HttpResponse response = httpClient.execute(httpMethod); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode != CloudifyConstants.HTTP_STATUS_CODE_OK) { final String message = uri + " response (code " + statusCode + ") " + statusLine.toString(); if (logger.isLoggable(Level.FINE)) { logger.log(Level.FINE, message); } throw new RestException(message); } final HttpEntity entity = response.getEntity(); if (entity == null) { final ErrorStatusException e = new ErrorStatusException(REASON_CODE_COMM_ERR, uri, MSG_RESPONSE_ENTITY_NULL); logger.log(Level.FINE, uri + MSG_RESPONSE_ENTITY_NULL, e); throw e; } instream = entity.getContent(); final String responseBody = StringUtils.getStringFromStream(instream); logger.finer(uri + MSG_HTTP_GET_RESPONSE + responseBody); final Map<String, Object> responseMap = GSRestClient.jsonToMap(responseBody); return responseMap; } catch (final ClientProtocolException e) { logger.log(Level.FINE, uri + MSG_REST_API_ERR, e); throw new ErrorStatusException(e, REASON_CODE_COMM_ERR, uri, MSG_REST_API_ERR); } catch (final IOException e) { logger.log(Level.FINE, uri + MSG_REST_API_ERR, e); throw new ErrorStatusException(e, REASON_CODE_COMM_ERR, uri, MSG_REST_API_ERR); } finally { if (instream != null) { try { instream.close(); } catch (final IOException e) { } } httpMethod.abort(); } }
From source file:de.wikilab.android.friendica01.TwAjax.java
private void runDefault() throws IOException { Log.v("TwAjax", "runDefault URL=" + myUrl); // Create a new HttpClient and Get/Post Header DefaultHttpClient httpclient = getNewHttpClient(); setHttpClientProxy(httpclient);// w w w . ja v a 2 s .c o m httpclient.getParams().setParameter("http.protocol.content-charset", "UTF-8"); //final HttpParams params = new BasicHttpParams(); HttpClientParams.setRedirecting(httpclient.getParams(), false); HttpRequestBase m; if (myMethod == "POST") { m = new HttpPost(myUrl); ((HttpPost) m).setEntity(new UrlEncodedFormEntity(myPostData, "utf-8")); } else { m = new HttpGet(myUrl); } m.addHeader("Host", m.getURI().getHost()); if (twSession != null) m.addHeader("Cookie", "twnetSID=" + twSession); httpclient.setCookieStore(cookieStoreManager); //generate auth header if user/pass are provided to this class if (this.myHttpAuthUser != null) { m.addHeader("Authorization", "Basic " + Base64 .encodeToString((this.myHttpAuthUser + ":" + this.myHttpAuthPass).getBytes(), Base64.NO_WRAP)); } // Execute HTTP Get/Post Request HttpResponse response = httpclient.execute(m); //InputStream is = response.getEntity().getContent(); myHttpStatus = response.getStatusLine().getStatusCode(); if (this.fetchHeader != null) { this.fetchHeaderResult = response.getHeaders(this.fetchHeader); Header[] h = response.getAllHeaders(); for (Header hh : h) Log.d(TAG, "Header " + hh.getName() + "=" + hh.getValue()); } else if (this.downloadToFile != null) { Log.v("TwAjax", "runDefault downloadToFile=" + downloadToFile); // download the file InputStream input = new BufferedInputStream(response.getEntity().getContent()); OutputStream output = new FileOutputStream(downloadToFile); byte data[] = new byte[1024]; long total = 0; int count; while ((count = input.read(data)) != -1) { total += count; // publishing the progress.... //publishProgress((int)(total*100/lenghtOfFile)); output.write(data, 0, count); } output.flush(); output.close(); input.close(); } else if (this.convertToBitmap) { myBmpResult = BitmapFactory.decodeStream(response.getEntity().getContent()); } else if (this.convertToXml) { try { myXmlDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder() .parse(response.getEntity().getContent()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); return; } } else { myResult = EntityUtils.toString(response.getEntity(), "UTF-8"); } //BufferedInputStream bis = new BufferedInputStream(is); //ByteArrayBuffer baf = new ByteArrayBuffer(50); //int current = 0; //while((current = bis.read()) != -1){ // baf.append((byte)current); //} //myResult = new String(baf.toByteArray(), "utf-8"); success = true; }
From source file:org.elasticsearch.xpack.security.authc.saml.SamlAuthenticationIT.java
private <T> T execute(CloseableHttpClient client, HttpRequestBase request, HttpContext context, CheckedFunction<HttpResponse, T, IOException> body) throws IOException { final int timeout = (int) TimeValue.timeValueSeconds(90).millis(); RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(timeout) .setConnectTimeout(timeout).setSocketTimeout(timeout).build(); request.setConfig(requestConfig);//from w w w. j ava 2 s. co m logger.info("Execute HTTP " + request.getMethod() + ' ' + request.getURI()); try (CloseableHttpResponse response = SocketAccess.doPrivileged(() -> client.execute(request, context))) { return body.apply(response); } catch (Exception e) { logger.warn(new ParameterizedMessage("HTTP Request [{}] failed", request.getURI()), e); throw e; } }
From source file:net.sourceforge.jwbf.core.actions.HttpActionClient.java
@VisibleForTesting HttpResponse execute(HttpRequestBase requestBase) { if (rateLimiter.isPresent()) { rateLimiter.get().acquire();/*from w w w . j av a 2s.c o m*/ } HttpResponse res; try { res = client.execute(requestBase); } catch (IOException e) { throw new IllegalStateException(e); } StatusLine statusLine = res.getStatusLine(); int code = statusLine.getStatusCode(); if (code >= HttpStatus.SC_BAD_REQUEST) { consume(res); throw new IllegalStateException("invalid status: " + statusLine + "; for " + requestBase.getURI()); } return res; }