List of usage examples for org.apache.http.client.methods HttpUriRequest getURI
URI getURI();
From source file:org.jets3t.service.impl.rest.httpclient.RestStorageService.java
/** * Authorizes an HTTP/S request by signing it with an HMAC signature compatible with * the S3 service and Google Storage (legacy) authorization techniques. * * The signature is added to the request as an Authorization header. * * @param httpMethod/*from ww w .j a v a 2s .c o m*/ * the request object * @throws ServiceException */ public void authorizeHttpRequest(HttpUriRequest httpMethod, HttpContext context) throws ServiceException { if (getProviderCredentials() != null) { if (log.isDebugEnabled()) { log.debug("Adding authorization for Access Key '" + getProviderCredentials().getAccessKey() + "'."); } } else { if (log.isDebugEnabled()) { log.debug("Service has no Credential and is un-authenticated, skipping authorization"); } return; } URI uri = httpMethod.getURI(); String hostname = uri.getHost(); /* * Determine the complete URL for the S3 resource, including any S3-specific parameters. */ // Use raw-path, otherwise escaped characters are unescaped and a wrong // signature is produced String xfullUrl = uri.getPath(); String fullUrl = uri.getRawPath(); // If we are using an alternative hostname, include the hostname/bucketname in the resource path. String s3Endpoint = this.getEndpoint(); if (hostname != null && !s3Endpoint.equals(hostname)) { int subdomainOffset = hostname.lastIndexOf("." + s3Endpoint); if (subdomainOffset > 0) { // Hostname represents an S3 sub-domain, so the bucket's name is the CNAME portion fullUrl = "/" + hostname.substring(0, subdomainOffset) + fullUrl; } else { // Hostname represents a virtual host, so the bucket's name is identical to hostname fullUrl = "/" + hostname + fullUrl; } } String queryString = uri.getRawQuery(); if (queryString != null && queryString.length() > 0) { fullUrl += "?" + queryString; } // Set/update the date timestamp to the current time // Note that this will be over-ridden if an "x-amz-date" or // "x-goog-date" header is present. httpMethod.setHeader("Date", ServiceUtils.formatRfc822Date(getCurrentTimeWithOffset())); if (log.isDebugEnabled()) { log.debug("For creating canonical string, using uri: " + fullUrl); } // Generate a canonical string representing the operation. String canonicalString = null; try { canonicalString = RestUtils.makeServiceCanonicalString(httpMethod.getMethod(), fullUrl, convertHeadersToMap(httpMethod.getAllHeaders()), null, getRestHeaderPrefix(), getResourceParameterNames()); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e.getMessage(), e); } if (log.isDebugEnabled()) { log.debug("Canonical string ('|' is a newline): " + canonicalString.replace('\n', '|')); } // Sign the canonical string. String signedCanonical = ServiceUtils.signWithHmacSha1(getProviderCredentials().getSecretKey(), canonicalString); // Add encoded authorization to connection as HTTP Authorization header. String authorizationString = getSignatureIdentifier() + " " + getProviderCredentials().getAccessKey() + ":" + signedCanonical; httpMethod.setHeader("Authorization", authorizationString); }
From source file:cn.com.loopj.android.http.AsyncHttpClient.java
/** * Puts a new request in queue as a new thread in pool to be executed * * @param client HttpClient to be used for request, can differ in single requests * @param contentType MIME body type, for POST and PUT requests, may be null * @param context Context of Android application, to hold the reference of request * @param httpContext HttpContext in which the request will be executed * @param responseHandler ResponseHandler or its subclass to put the response into * @param uriRequest instance of HttpUriRequest, which means it must be of HttpDelete, * HttpPost, HttpGet, HttpPut, etc. * @return RequestHandle of future request process *//*from ww w .j a v a 2s . co m*/ protected RequestHandle sendRequest(DefaultHttpClient client, HttpContext httpContext, HttpUriRequest uriRequest, String contentType, ResponseHandlerInterface responseHandler, Context context) { if (uriRequest == null) { throw new IllegalArgumentException("HttpUriRequest must not be null"); } if (responseHandler == null) { throw new IllegalArgumentException("ResponseHandler must not be null"); } if (responseHandler.getUseSynchronousMode() && !responseHandler.getUsePoolThread()) { throw new IllegalArgumentException( "Synchronous ResponseHandler used in AsyncHttpClient. You should create your response handler in a looper thread or use SyncHttpClient instead."); } if (contentType != null) { if (uriRequest instanceof HttpEntityEnclosingRequestBase && ((HttpEntityEnclosingRequestBase) uriRequest).getEntity() != null && uriRequest.containsHeader(HEADER_CONTENT_TYPE)) { log.w(LOG_TAG, "Passed contentType will be ignored because HttpEntity sets content type"); } else { uriRequest.setHeader(HEADER_CONTENT_TYPE, contentType); } } responseHandler.setRequestHeaders(uriRequest.getAllHeaders()); responseHandler.setRequestURI(uriRequest.getURI()); AsyncHttpRequest request = newAsyncHttpRequest(client, httpContext, uriRequest, contentType, responseHandler, context); threadPool.submit(request); RequestHandle requestHandle = new RequestHandle(request); if (context != null) { List<RequestHandle> requestList; // Add request to request map synchronized (requestMap) { requestList = requestMap.get(context); if (requestList == null) { requestList = Collections.synchronizedList(new LinkedList<RequestHandle>()); requestMap.put(context, requestList); } } requestList.add(requestHandle); Iterator<RequestHandle> iterator = requestList.iterator(); while (iterator.hasNext()) { if (iterator.next().shouldBeGarbageCollected()) { iterator.remove(); } } } return requestHandle; }
From source file:com.buffalokiwi.api.API.java
/** * Prepare the response entity for usage * @param response HTTP Response/* w ww .j a va 2s . c om*/ * @param get HTTP Get * @return The response results * @throws BrowserException * @throws RedirectException if a redirect needs to happen */ private IAPIResponse processResponse(final HttpResponse response, final HttpUriRequest get) throws APIException { if (response == null) throw new APIException("Endpoint response was null"); final HttpEntity entity = response.getEntity(); try { if (entity != null) { //..Get the charset String charset = ""; try { java.nio.charset.Charset cs = ContentType.getOrDefault(entity).getCharset(); if (cs != null) charset = cs.displayName(); } catch (ParseException | UnsupportedCharsetException e) { //..No nothing, use defaults } if ((charset == null) || (charset.isEmpty())) { charset = "UTF-8"; final Header[] headers = response.getHeaders("Content-Type"); if (headers.length > 0) { if (headers[0].getValue().equals("application/octet-stream")) charset = ""; } } //..Get content length header final Header[] clen = response.getHeaders("Content-Length"); final int contentLength = (clen.length > 0) ? Integer.valueOf(clen[0].getValue()) : 0; //..Process the stream try (final InputStream in = entity.getContent()) { final byte[] content = processEntity(in, contentLength); //..set the character set used to create the htmlBuffer if (LOG.isTraceEnabled()) { if (!charset.isEmpty()) APILog.trace(LOG, new String(content, 0, content.length, charset)); else APILog.trace(LOG, new String(content)); } final IAPIResponse res = createResponseObject(response, content, charset); APILog.debug(LOG, String.valueOf(res.getStatusLine().getStatusCode()), res.getStatusLine().getReasonPhrase(), "for", get.getURI().toString()); return res; } catch (RuntimeException e) { APILog.error(LOG, e); //..Abort get.abort(); throw new APIException(e.getMessage(), e); } } else { final IAPIResponse res = createResponseObject(response, null, ""); APILog.debug(LOG, String.valueOf(res.getStatusLine().getStatusCode()), res.getStatusLine().getReasonPhrase(), "for", get.getURI().toString()); return res; } } catch (IOException e) { APILog.error(LOG, e); throw new APIException("Failed to retrieve entity content (IOException)", e); } finally { try { EntityUtils.consume(entity); } catch (IOException e) { } } }
From source file:org.deviceconnect.android.manager.setting.ReqResDebugActivity.java
/** * Http?.//w w w.ja v a 2 s . c om * @param request * @param listener Http???? */ private void executeHttpRequest(final HttpUriRequest request, final HttpListener listener) { if (!showProgressDialog()) { return; } AsyncTask<HttpUriRequest, HttpUriRequest, String> task = new AsyncTask<HttpUriRequest, HttpUriRequest, String>() { @Override protected String doInBackground(final HttpUriRequest... params) { if (params == null || params.length < 1) { return "Illegal Parameter."; } HttpUriRequest request = params[0]; DefaultHttpClient client = new DefaultHttpClient(); try { HttpResponse response = client.execute(request); switch (response.getStatusLine().getStatusCode()) { case HttpStatus.SC_OK: try { return EntityUtils.toString(response.getEntity(), "UTF-8"); } catch (ParseException e) { return e.getMessage(); } catch (IOException e) { return e.getMessage(); } case HttpStatus.SC_NOT_FOUND: return "Not found. 404"; default: return "Http connect error."; } } catch (ClientProtocolException e) { return e.getMessage(); } catch (IOException e) { return e.getMessage(); } finally { client.getConnectionManager().shutdown(); } } @Override protected void onPostExecute(final String response) { super.onPostExecute(response); hideProgressDialog(); if (response == null) { return; } StringBuilder sb = new StringBuilder(); sb.append("Request:\n"); sb.append(request.getMethod() + " " + request.getURI() + "\n"); mListAdapter.add(sb.toString()); mListAdapter.add("Response:\n" + response); mListAdapter.notifyDataSetChanged(); if (listener != null) { listener.onReceivedResponse(response); } } }; task.execute(request); }
From source file:com.amytech.android.library.utils.asynchttp.AsyncHttpClient.java
/** * Puts a new request in queue as a new thread in pool to be executed * * @param client/* w ww . j av a2 s . com*/ * HttpClient to be used for request, can differ in single * requests * @param contentType * MIME body type, for POST and PUT requests, may be null * @param context * Context of Android application, to hold the reference of * request * @param httpContext * HttpContext in which the request will be executed * @param responseHandler * ResponseHandler or its subclass to put the response into * @param uriRequest * instance of HttpUriRequest, which means it must be of * HttpDelete, HttpPost, HttpGet, HttpPut, etc. * @return RequestHandle of future request process */ protected RequestHandle sendRequest(DefaultHttpClient client, HttpContext httpContext, HttpUriRequest uriRequest, String contentType, ResponseHandlerInterface responseHandler, Context context) { if (uriRequest == null) { throw new IllegalArgumentException("HttpUriRequest must not be null"); } if (responseHandler == null) { throw new IllegalArgumentException("ResponseHandler must not be null"); } if (responseHandler.getUseSynchronousMode() && !responseHandler.getUsePoolThread()) { throw new IllegalArgumentException( "Synchronous ResponseHandler used in AsyncHttpClient. You should create your response handler in a looper thread or use SyncHttpClient instead."); } if (contentType != null) { if (uriRequest instanceof HttpEntityEnclosingRequestBase && ((HttpEntityEnclosingRequestBase) uriRequest).getEntity() != null && uriRequest.containsHeader(HEADER_CONTENT_TYPE)) { Log.w(LOG_TAG, "Passed contentType will be ignored because HttpEntity sets content type"); } else { uriRequest.setHeader(HEADER_CONTENT_TYPE, contentType); } } responseHandler.setRequestHeaders(uriRequest.getAllHeaders()); responseHandler.setRequestURI(uriRequest.getURI()); AsyncHttpRequest request = newAsyncHttpRequest(client, httpContext, uriRequest, contentType, responseHandler, context); threadPool.submit(request); RequestHandle requestHandle = new RequestHandle(request); if (context != null) { List<RequestHandle> requestList; // Add request to request map synchronized (requestMap) { requestList = requestMap.get(context); if (requestList == null) { requestList = Collections.synchronizedList(new LinkedList<RequestHandle>()); requestMap.put(context, requestList); } } requestList.add(requestHandle); Iterator<RequestHandle> iterator = requestList.iterator(); while (iterator.hasNext()) { if (iterator.next().shouldBeGarbageCollected()) { iterator.remove(); } } } return requestHandle; }
From source file:org.olat.modules.tu.TunnelMapper.java
@Override public MediaResource handle(String relPath, HttpServletRequest hreq) { String method = hreq.getMethod(); String uri = relPath;//from w w w .j av a 2 s . c o m HttpUriRequest meth = null; try { URIBuilder builder = new URIBuilder(); builder.setScheme(proto).setHost(host).setPort(port.intValue()); if (uri == null) { uri = (startUri == null) ? "" : startUri; } if (uri.length() > 0 && uri.charAt(0) != '/') { uri = "/" + uri; } if (StringHelper.containsNonWhitespace(uri)) { builder.setPath(uri); } if (method.equals("GET")) { String queryString = hreq.getQueryString(); if (StringHelper.containsNonWhitespace(queryString)) { builder.setCustomQuery(queryString); } meth = new HttpGet(builder.build()); } else if (method.equals("POST")) { Map<String, String[]> params = hreq.getParameterMap(); HttpPost pmeth = new HttpPost(builder.build()); List<BasicNameValuePair> pairs = new ArrayList<BasicNameValuePair>(); for (String key : params.keySet()) { String vals[] = params.get(key); for (String val : vals) { pairs.add(new BasicNameValuePair(key, val)); } } HttpEntity entity = new UrlEncodedFormEntity(pairs, "UTF-8"); pmeth.setEntity(entity); meth = pmeth; } // Add olat specific headers to the request, can be used by external // applications to identify user and to get other params // test page e.g. http://cgi.algonet.se/htbin/cgiwrap/ug/test.py if ("enabled".equals( CoreSpringFactory.getImpl(BaseSecurityModule.class).getUserInfosTunnelCourseBuildingBlock())) { User u = ident.getUser(); meth.addHeader("X-OLAT-USERNAME", ident.getName()); meth.addHeader("X-OLAT-LASTNAME", u.getProperty(UserConstants.LASTNAME, null)); meth.addHeader("X-OLAT-FIRSTNAME", u.getProperty(UserConstants.FIRSTNAME, null)); meth.addHeader("X-OLAT-EMAIL", u.getProperty(UserConstants.EMAIL, null)); meth.addHeader("X-OLAT-USERIP", ipAddress); } HttpResponse response = httpClient.execute(meth); if (response == null) { // error return new NotFoundMediaResource(relPath); } // get or post successfully Header responseHeader = response.getFirstHeader("Content-Type"); if (responseHeader == null) { // error EntityUtils.consumeQuietly(response.getEntity()); return new NotFoundMediaResource(relPath); } return new HttpRequestMediaResource(response); } catch (ClientProtocolException e) { log.error("", e); return null; } catch (URISyntaxException e) { log.error("", e); return null; } catch (IOException e) { log.error("Error loading URI: " + (meth == null ? "???" : meth.getURI()), e); return null; } }
From source file:org.openrdf.http.client.SparqlSession.java
/** * Parse the response in a background thread. HTTP connections are dealt with * in the {@link BackgroundGraphResult} or (in the error-case) in this * method./* w w w. j av a 2 s .co m*/ */ protected BackgroundGraphResult getRDFBackground(HttpUriRequest method, boolean requireContext) throws IOException, RDFHandlerException, RepositoryException, MalformedQueryException, UnauthorizedException, QueryInterruptedException { boolean submitted = false; // Specify which formats we support using Accept headers Set<RDFFormat> rdfFormats = RDFParserRegistry.getInstance().getKeys(); if (rdfFormats.isEmpty()) { throw new RepositoryException("No tuple RDF parsers have been registered"); } // send the tuple query HttpResponse response = sendGraphQueryViaHttp(method, requireContext, rdfFormats); try { // if we get here, HTTP code is 200 String mimeType = getResponseMIMEType(response); try { RDFFormat format = RDFFormat.matchMIMEType(mimeType, rdfFormats); RDFParser parser = Rio.createParser(format, getValueFactory()); parser.setParserConfig(getParserConfig()); parser.setParseErrorListener(new ParseErrorLogger()); Charset charset = null; // SES-1793 : Do not attempt to check for a charset if the format is // defined not to have a charset // This prevents errors caused by people erroneously attaching a // charset to a binary formatted document HttpEntity entity = response.getEntity(); if (format.hasCharset() && entity != null && entity.getContentType() != null) { // TODO copied from SPARQLGraphQuery repository, is this // required? try { charset = ContentType.parse(entity.getContentType().getValue()).getCharset(); } catch (IllegalCharsetNameException e) { // work around for Joseki-3.2 // Content-Type: application/rdf+xml; // charset=application/rdf+xml } if (charset == null) { charset = UTF8; } } if (entity == null) { throw new RepositoryException("Server response was empty."); } String baseURI = method.getURI().toASCIIString(); BackgroundGraphResult gRes = new BackgroundGraphResult(parser, entity.getContent(), charset, baseURI); execute(gRes); submitted = true; return gRes; } catch (UnsupportedQueryResultFormatException e) { throw new RepositoryException("Server responded with an unsupported file format: " + mimeType); } } finally { if (!submitted) { EntityUtils.consumeQuietly(response.getEntity()); } } }
From source file:org.eclipse.rdf4j.http.client.SPARQLProtocolSession.java
/** * Parse the response in a background thread. HTTP connections are dealt with in the * {@link BackgroundGraphResult} or (in the error-case) in this method. *///from w w w .j a v a 2 s .com protected BackgroundGraphResult getRDFBackground(HttpUriRequest method, boolean requireContext) throws IOException, RDFHandlerException, RepositoryException, MalformedQueryException, UnauthorizedException, QueryInterruptedException { boolean submitted = false; // Specify which formats we support using Accept headers Set<RDFFormat> rdfFormats = RDFParserRegistry.getInstance().getKeys(); if (rdfFormats.isEmpty()) { throw new RepositoryException("No tuple RDF parsers have been registered"); } BackgroundGraphResult gRes = null; // send the tuple query HttpResponse response = sendGraphQueryViaHttp(method, requireContext, rdfFormats); try { // if we get here, HTTP code is 200 String mimeType = getResponseMIMEType(response); RDFFormat format = RDFFormat.matchMIMEType(mimeType, rdfFormats).orElseThrow( () -> new RepositoryException("Server responded with an unsupported file format: " + mimeType)); RDFParser parser = Rio.createParser(format, getValueFactory()); parser.setParserConfig(getParserConfig()); parser.setParseErrorListener(new ParseErrorLogger()); Charset charset = null; // SES-1793 : Do not attempt to check for a charset if the format is // defined not to have a charset // This prevents errors caused by people erroneously attaching a // charset to a binary formatted document HttpEntity entity = response.getEntity(); if (format.hasCharset() && entity != null && entity.getContentType() != null) { // TODO copied from SPARQLGraphQuery repository, is this // required? try { charset = ContentType.parse(entity.getContentType().getValue()).getCharset(); } catch (IllegalCharsetNameException e) { // work around for Joseki-3.2 // Content-Type: application/rdf+xml; // charset=application/rdf+xml } if (charset == null) { charset = UTF8; } } if (entity == null) { throw new RepositoryException("Server response was empty."); } String baseURI = method.getURI().toASCIIString(); gRes = new BackgroundGraphResult(parser, entity.getContent(), charset, baseURI); execute(gRes); submitted = true; return gRes; } finally { if (!submitted) { try { if (gRes != null) { gRes.close(); } } finally { EntityUtils.consumeQuietly(response.getEntity()); } } } }
From source file:com.fujitsu.dc.client.http.DcRequestBuilder.java
/** * This method is used to generate a HttpUriRequest object by setting the parameters in request header. * @return HttpUriRequest object that is generated * @throws DaoException Exception thrown *//*from w ww.j a v a 2 s. co m*/ public HttpUriRequest build() throws DaoException { HttpUriRequest req = null; if (HttpMethods.PUT.equals(this.methodValue)) { req = new HttpPut(this.urlValue); } else if (HttpMethods.POST.equals(this.methodValue)) { req = new HttpPost(this.urlValue); } else if (HttpMethods.DELETE.equals(this.methodValue)) { req = new HttpDelete(this.urlValue); } else if (HttpMethods.ACL.equals(this.methodValue)) { req = new HttpAclMethod(this.urlValue); } else if (HttpMethods.MKCOL.equals(this.methodValue)) { req = new HttpMkColMethod(this.urlValue); } else if (HttpMethods.PROPPATCH.equals(this.methodValue)) { req = new HttpPropPatchMethod(this.urlValue); } else if (HttpMethods.PROPFIND.equals(this.methodValue)) { req = new HttpPropfindMethod(this.urlValue); } else if (HttpMethods.GET.equals(this.methodValue)) { req = new HttpGet(this.urlValue); } else if (HttpMethods.MERGE.equals(this.methodValue)) { req = new HttpMergeMethod(this.urlValue); } if (this.tokenValue != null) { req.addHeader(HttpHeaders.AUTHORIZATION, "Bearer " + this.tokenValue); } /** include header parameters if any. */ for (String key : headers.keySet()) { String value = headers.get(key); req.addHeader(key, value); } // ???????? /** If Default header is set, configure them. */ // ????????????????????? /** * The reason you do not want to set for the first time, since the request header, would have been more than one * registration is the same name header */ if (this.defaultHeaders != null) { for (String key : this.defaultHeaders.keySet()) { String val = this.defaultHeaders.get(key); Header[] headerItems = req.getHeaders(key); if (headerItems.length == 0) { req.addHeader(key, val); } } } if (this.bodyValue != null) { HttpEntity body = null; try { if (this.getContentType() != "" && RestAdapter.CONTENT_TYPE_JSON.equals(this.getContentType())) { String bodyStr = toUniversalCharacterNames(this.bodyValue); body = new StringEntity(bodyStr); } else { body = new StringEntity(this.bodyValue, RestAdapter.ENCODE); } } catch (UnsupportedEncodingException e) { throw DaoException.create("error while request body encoding : " + e.getMessage(), 0); } ((HttpEntityEnclosingRequest) req).setEntity(body); } if (this.bodyStream != null) { InputStreamEntity body = new InputStreamEntity(this.bodyStream, -1); body.setChunked(true); this.bodyValue = "[stream]"; ((HttpEntityEnclosingRequest) req).setEntity(body); } if (req != null) { log.debug(""); log.debug("?Request " + req.getMethod() + " " + req.getURI()); Header[] allheaders = req.getAllHeaders(); for (int i = 0; i < allheaders.length; i++) { log.debug("RequestHeader[" + allheaders[i].getName() + "] : " + allheaders[i].getValue()); } log.debug("RequestBody : " + bodyValue); } return req; }