List of usage examples for org.apache.http.client.methods HttpUriRequest addHeader
void addHeader(String str, String str2);
From source file:ezid.EZIDService.java
/** * Send an HTTP request to the EZID service with a request body (for POST and PUT requests). * * @param requestType the type of the service as an integer * @param uri endpoint to be accessed in the request * @param requestBody the String body to be encoded into the body of the request * * @return byte[] containing the response body *//* w w w . j a v a 2s.com*/ private byte[] sendRequest(int requestType, String uri, String requestBody) throws EZIDException { HttpUriRequest request = null; log.debug("Trying uri: " + uri); System.out.println("uri = " + uri); switch (requestType) { case GET: request = new HttpGet(uri); break; case PUT: request = new HttpPut(uri); if (requestBody != null && requestBody.length() > 0) { try { StringEntity myEntity = new StringEntity(requestBody, "UTF-8"); ((HttpPut) request).setEntity(myEntity); } catch (UnsupportedEncodingException e) { throw new EZIDException(e); } } break; case POST: request = new HttpPost(uri); if (requestBody != null && requestBody.length() > 0) { try { System.out.println("requestBody = " + requestBody); StringEntity myEntity = new StringEntity(requestBody, "UTF-8"); ((HttpPost) request).setEntity(myEntity); } catch (UnsupportedEncodingException e) { throw new EZIDException(e); } } break; case DELETE: request = new HttpDelete(uri); break; default: throw new EZIDException("Unrecognized HTTP method requested."); } request.addHeader("Accept", "text/plain"); /* HACK -- re-authorize on the fly as this was getting dropped on SI server*/ /*String auth = this.username + ":" + this.password; String encodedAuth = org.apache.commons.codec.binary.Base64.encodeBase64String(auth.getBytes()); request.addHeader("Authorization", "Basic " + encodedAuth); */ ResponseHandler<byte[]> handler = new ResponseHandler<byte[]>() { public byte[] handleResponse(HttpResponse response) throws ClientProtocolException, IOException { HttpEntity entity = response.getEntity(); if (entity != null) { return EntityUtils.toByteArray(entity); } else { return null; } } }; byte[] body = null; try { body = httpclient.execute(request, handler); } catch (ClientProtocolException e) { throw new EZIDException(e); } catch (IOException e) { throw new EZIDException(e); } return body; }
From source file:com.amazonaws.http.ApacheHttpClient.java
private HttpUriRequest createHttpRequest(HttpRequest request) { HttpUriRequest httpRequest; String method = request.getMethod(); if (method.equals("POST")) { HttpPost postRequest = new HttpPost(request.getUri()); if (request.getContent() != null) { postRequest.setEntity(new InputStreamEntity(request.getContent(), request.getContentLength())); }/*from w w w. j a v a 2 s .c o m*/ httpRequest = postRequest; } else if (method.equals("GET")) { httpRequest = new HttpGet(request.getUri()); } else if (method.equals("PUT")) { HttpPut putRequest = new HttpPut(request.getUri()); if (request.getContent() != null) { putRequest.setEntity(new InputStreamEntity(request.getContent(), request.getContentLength())); } httpRequest = putRequest; } else if (method.equals("DELETE")) { httpRequest = new HttpDelete(request.getUri()); } else if (method.equals("HEAD")) { httpRequest = new HttpHead(request.getUri()); } else { throw new UnsupportedOperationException("Unsupported method: " + method); } if (request.getHeaders() != null && !request.getHeaders().isEmpty()) { for (Map.Entry<String, String> header : request.getHeaders().entrySet()) { String key = header.getKey(); /* * HttpClient4 fills in the Content-Length header and complains * if it's already present, so we skip it here. We also skip the * Host header to avoid sending it twice, which will interfere * with some signing schemes. */ if (key.equals(HttpHeader.CONTENT_LENGTH) || key.equals(HttpHeader.HOST)) { continue; } httpRequest.addHeader(header.getKey(), header.getValue()); } } // disable redirect if (params == null) { params = new BasicHttpParams(); params.setParameter(ClientPNames.HANDLE_REDIRECTS, false); } httpRequest.setParams(params); return httpRequest; }
From source file:org.eclipse.rdf4j.http.client.SPARQLProtocolSession.java
private HttpResponse sendBooleanQueryViaHttp(HttpUriRequest method, Set<QueryResultFormat> booleanFormats) throws IOException, RDF4JException { final List<String> acceptValues = new ArrayList<>(booleanFormats.size()); for (QueryResultFormat format : booleanFormats) { // Determine a q-value that reflects the user specified preference int qValue = 10; if (preferredBQRFormat != null && !preferredBQRFormat.equals(format)) { // Prefer specified format over other formats qValue -= 2;/*from ww w . j ava 2s.co m*/ } for (String mimeType : format.getMIMETypes()) { String acceptParam = mimeType; if (qValue < 10) { acceptParam += ";q=0." + qValue; } acceptValues.add(acceptParam); } } method.addHeader(ACCEPT_PARAM_NAME, commaJoiner.join(acceptValues)); return executeOK(method); }
From source file:org.soyatec.windowsazure.management.ServiceManagementRest.java
/** * A value that uniquely identifies a request made against the management * service.//w w w . ja v a2 s .c om * * @param requestId * @param request */ private void attachHeaderForRequestId(String requestId, HttpUriRequest request) { request.addHeader(HeaderNames.ManagementRequestId, requestId); }
From source file:org.eclipse.rdf4j.http.client.SPARQLProtocolSession.java
/** * Send the tuple query via HTTP and throws an exception in case anything goes wrong, i.e. only for HTTP * 200 the method returns without exception. If HTTP status code is not equal to 200, the request is * aborted, however pooled connections are not released. * /*from w w w . ja v a2 s . c om*/ * @param method * @throws RepositoryException * @throws HttpException * @throws IOException * @throws QueryInterruptedException * @throws MalformedQueryException */ private HttpResponse sendTupleQueryViaHttp(HttpUriRequest method, Set<QueryResultFormat> tqrFormats) throws RepositoryException, IOException, QueryInterruptedException, MalformedQueryException { final List<String> acceptValues = new ArrayList<String>(tqrFormats.size()); for (QueryResultFormat format : tqrFormats) { // Determine a q-value that reflects the user specified preference int qValue = 10; if (preferredTQRFormat != null && !preferredTQRFormat.equals(format)) { // Prefer specified format over other formats qValue -= 2; } for (String mimeType : format.getMIMETypes()) { String acceptParam = mimeType; if (qValue < 10) { acceptParam += ";q=0." + qValue; } acceptValues.add(acceptParam); } } method.addHeader(ACCEPT_PARAM_NAME, commaJoiner.join(acceptValues)); try { return executeOK(method); } catch (RepositoryException | MalformedQueryException | QueryInterruptedException e) { throw e; } catch (RDF4JException e) { throw new RepositoryException(e); } }
From source file:org.jclouds.http.apachehc.ApacheHCUtils.java
public HttpUriRequest convertToApacheRequest(HttpRequest request) { HttpUriRequest apacheRequest; if (request.getMethod().equals(HttpMethod.HEAD)) { apacheRequest = new HttpHead(request.getEndpoint()); } else if (request.getMethod().equals(HttpMethod.GET)) { apacheRequest = new HttpGet(request.getEndpoint()); } else if (request.getMethod().equals(HttpMethod.DELETE)) { apacheRequest = new HttpDelete(request.getEndpoint()); } else if (request.getMethod().equals(HttpMethod.PUT)) { apacheRequest = new HttpPut(request.getEndpoint()); apacheRequest.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, true); } else if (request.getMethod().equals(HttpMethod.POST)) { apacheRequest = new HttpPost(request.getEndpoint()); } else {//from w w w . ja va2 s . c om final String method = request.getMethod(); if (request.getPayload() != null) apacheRequest = new HttpEntityEnclosingRequestBase() { @Override public String getMethod() { return method; } }; else apacheRequest = new HttpRequestBase() { @Override public String getMethod() { return method; } }; HttpRequestBase.class.cast(apacheRequest).setURI(request.getEndpoint()); } Payload payload = request.getPayload(); // Since we may remove headers, ensure they are added to the apache // request after this block if (apacheRequest instanceof HttpEntityEnclosingRequest) { if (payload != null) { addEntityForContent(HttpEntityEnclosingRequest.class.cast(apacheRequest), payload); } } else { apacheRequest.addHeader(HttpHeaders.CONTENT_LENGTH, "0"); } for (Map.Entry<String, String> entry : request.getHeaders().entries()) { String header = entry.getKey(); // apache automatically tries to add content length header if (!header.equals(HttpHeaders.CONTENT_LENGTH)) apacheRequest.addHeader(header, entry.getValue()); } apacheRequest.addHeader(HttpHeaders.USER_AGENT, USER_AGENT); return apacheRequest; }
From source file:org.dasein.cloud.terremark.TerremarkMethod.java
public Document invoke(boolean debug) throws TerremarkException, CloudException, InternalException { if (logger.isTraceEnabled()) { logger.trace("ENTER - " + TerremarkMethod.class.getName() + ".invoke(" + debug + ")"); }// w w w . j a va 2s.c om try { if (logger.isDebugEnabled()) { logger.debug("Talking to server at " + url); } if (parameters != null) { URIBuilder uri = null; try { uri = new URIBuilder(url); } catch (URISyntaxException e) { e.printStackTrace(); } for (NameValuePair parameter : parameters) { uri.addParameter(parameter.getName(), parameter.getValue()); } url = uri.toString(); } HttpUriRequest method = null; if (methodType.equals(HttpMethodName.GET)) { method = new HttpGet(url); } else if (methodType.equals(HttpMethodName.POST)) { method = new HttpPost(url); } else if (methodType.equals(HttpMethodName.DELETE)) { method = new HttpDelete(url); } else if (methodType.equals(HttpMethodName.PUT)) { method = new HttpPut(url); } else if (methodType.equals(HttpMethodName.HEAD)) { method = new HttpHead(url); } else { method = new HttpGet(url); } HttpResponse status = null; try { HttpClient client = new DefaultHttpClient(); HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, "UTF-8"); HttpProtocolParams.setUserAgent(params, "Dasein Cloud"); attempts++; String proxyHost = provider.getProxyHost(); if (proxyHost != null) { int proxyPort = provider.getProxyPort(); boolean ssl = url.startsWith("https"); params.setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost(proxyHost, proxyPort, ssl ? "https" : "http")); } for (Map.Entry<String, String> entry : headers.entrySet()) { method.addHeader(entry.getKey(), entry.getValue()); } if (body != null && body != "" && (methodType.equals(HttpMethodName.PUT) || methodType.equals(HttpMethodName.POST))) { try { HttpEntity entity = new StringEntity(body, "UTF-8"); ((HttpEntityEnclosingRequestBase) method).setEntity(entity); } catch (UnsupportedEncodingException e) { logger.warn(e); } } if (wire.isDebugEnabled()) { wire.debug(methodType.name() + " " + method.getURI()); for (Header header : method.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } if (body != null) { wire.debug(body); } } try { status = client.execute(method); if (wire.isDebugEnabled()) { wire.debug("HTTP STATUS: " + status); } } catch (IOException e) { logger.error("I/O error from server communications: " + e.getMessage()); e.printStackTrace(); throw new InternalException(e); } int statusCode = status.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED || statusCode == HttpStatus.SC_ACCEPTED) { try { InputStream input = status.getEntity().getContent(); try { return parseResponse(input); } finally { input.close(); } } catch (IOException e) { logger.error("Error parsing response from Teremark: " + e.getMessage()); e.printStackTrace(); throw new CloudException(CloudErrorType.COMMUNICATION, statusCode, null, e.getMessage()); } } else if (statusCode == HttpStatus.SC_NO_CONTENT) { logger.debug("Recieved no content in response. Creating an empty doc."); DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = null; try { docBuilder = dbfac.newDocumentBuilder(); } catch (ParserConfigurationException e) { e.printStackTrace(); } return docBuilder.newDocument(); } else if (statusCode == HttpStatus.SC_FORBIDDEN) { String msg = "OperationNotAllowed "; try { msg += parseResponseToString(status.getEntity().getContent()); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } wire.error(msg); throw new TerremarkException(statusCode, "OperationNotAllowed", msg); } else { String response = "Failed to parse response."; ParsedError parsedError = null; try { response = parseResponseToString(status.getEntity().getContent()); parsedError = parseErrorResponse(response); } catch (IllegalStateException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } if (logger.isDebugEnabled()) { logger.debug("Received " + status + " from " + url); } if (statusCode == HttpStatus.SC_SERVICE_UNAVAILABLE || statusCode == HttpStatus.SC_INTERNAL_SERVER_ERROR) { if (attempts >= 5) { String msg; wire.warn(response); if (statusCode == HttpStatus.SC_SERVICE_UNAVAILABLE) { msg = "Cloud service is currently unavailable."; } else { msg = "The cloud service encountered a server error while processing your request."; try { msg = msg + "Response from server was:\n" + response; } catch (RuntimeException runException) { logger.warn(runException); } catch (Error error) { logger.warn(error); } } wire.error(response); logger.error(msg); if (parsedError != null) { throw new TerremarkException(parsedError); } else { throw new CloudException("HTTP Status " + statusCode + msg); } } else { try { Thread.sleep(5000L); } catch (InterruptedException e) { /* ignore */ } return invoke(); } } wire.error(response); if (parsedError != null) { throw new TerremarkException(parsedError); } else { String msg = "\nResponse from server was:\n" + response; logger.error(msg); throw new CloudException("HTTP Status " + statusCode + msg); } } } finally { try { if (status != null) { EntityUtils.consume(status.getEntity()); } } catch (IOException e) { e.printStackTrace(); } } } finally { if (logger.isTraceEnabled()) { logger.trace("EXIT - " + TerremarkMethod.class.getName() + ".invoke()"); } } }
From source file:org.soyatec.windowsazure.management.ServiceManagementRest.java
/** * List all of the data center locations that are valid for your * subscription.//from w w w. j a v a 2 s .c o m * * @return a list of locations */ public List<Location> listLocations() { HttpUriRequest request = HttpUtilities.createHttpRequest(URI.create(getBaseUrl() + LOCATIONS), HttpMethod.Get); request.addHeader(HeaderNames.ApiVersion, XmsVersion.VERSION_2010_10_28); try { HttpWebResponse response = HttpUtilities.getSSLReponse(request, getSslSocketFactory()); if (isRequestAccepted(response)) { return XPathQueryHelper.parseLocationsResponse(response.getStream()); } else { HttpUtilities.processUnexpectedStatusCode(response); } } catch (StorageException we) { throw HttpUtilities.translateWebException(we); } catch (Exception e) { throw new IllegalStateException(e); } return null; }
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 a va 2 s . co 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.soyatec.windowsazure.management.ServiceManagementRest.java
/** * list the OperatingSystem' Versions/*from ww w. j av a 2 s .co m*/ * * @return a list of OperatingSystem type data */ public List<OperatingSystem> listOperatingSystems() { HttpUriRequest request = HttpUtilities.createHttpRequest(URI.create(getBaseUrl() + OPERATING_SYSTEMS), HttpMethod.Get); request.addHeader(HeaderNames.ApiVersion, XmsVersion.VERSION_2010_10_28); try { HttpWebResponse response = HttpUtilities.getSSLReponse(request, getSslSocketFactory()); if (isRequestAccepted(response)) { return XPathQueryHelper.parseOperatingSystemResponse(response.getStream()); } else { HttpUtilities.processUnexpectedStatusCode(response); } } catch (StorageException we) { throw HttpUtilities.translateWebException(we); } catch (Exception e) { throw new IllegalStateException(e); } return null; }