List of usage examples for org.apache.http.client.methods HttpRequestBase addHeader
public void addHeader(String str, String str2)
From source file:es.tid.fiware.fiwareconnectors.cygnus.backends.ckan.CKANRequester.java
/** * Common method to perform HTTP request using the CKAN API with payload. * @param method HTTP method//from www. ja v a2 s . c om * @param urlPath URL path to be added to the base URL * @param payload Request payload * @return CKANResponse associated to the request * @throws Exception */ public CKANResponse doCKANRequest(String method, String urlPath, String payload) throws Exception { // build the final URL String url = baseURL + urlPath; HttpRequestBase request = null; HttpResponse response = null; try { // do the post if (method.equals("GET")) { request = new HttpGet(url); } else if (method.equals("POST")) { HttpPost r = new HttpPost(url); // payload (optional) if (!payload.equals("")) { logger.debug("request payload: " + payload); r.setEntity(new StringEntity(payload, ContentType.create("application/json"))); } // if request = r; } else { throw new CygnusRuntimeError("HTTP method not supported: " + method); } // if else // headers request.addHeader("Authorization", apiKey); // execute the request logger.debug("CKAN operation: " + request.toString()); } catch (Exception e) { if (e instanceof CygnusRuntimeError || e instanceof CygnusPersistenceError || e instanceof CygnusBadConfiguration) { throw e; } else { throw new CygnusRuntimeError(e.getMessage()); } // if else } // try catch try { response = httpClient.execute(request); } catch (Exception e) { throw new CygnusPersistenceError(e.getMessage()); } // try catch try { BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String res = reader.readLine(); request.releaseConnection(); long l = response.getEntity().getContentLength(); logger.debug("CKAN response (" + l + " bytes): " + response.getStatusLine().toString()); // get the JSON encapsulated in the response logger.debug("response payload: " + res); JSONParser j = new JSONParser(); JSONObject o = (JSONObject) j.parse(res); // return result return new CKANResponse(o, response.getStatusLine().getStatusCode()); } catch (Exception e) { if (e instanceof CygnusRuntimeError || e instanceof CygnusPersistenceError || e instanceof CygnusBadConfiguration) { throw e; } else { throw new CygnusRuntimeError(e.getMessage()); } // if else } // try catch }
From source file:com.lonepulse.zombielink.request.HeaderProcessor.java
private void addHeader(HttpRequestBase request, String name, Object value) { if (value != null && !value.equals("")) { if (!(value instanceof CharSequence)) { StringBuilder errorContext = new StringBuilder().append("Header values can only be of type ") .append(CharSequence.class.getName()) .append(". Please consider using an implementation of CharSequence for the header <") .append(name)//from w w w. j a v a 2s . c o m .append("> and providing a meaningful toString() implementation for the header-value. ") .append("Furthermore, response headers should be of the specialized type ") .append(StringBuilder.class.getName()); throw new IllegalArgumentException(errorContext.toString()); } request.addHeader(name, value.toString()); } }
From source file:com.monarchapis.client.rest.BaseClient.java
/** * Sets headers to the http message./*from w w w.j av a 2 s . com*/ * * @param request * http message to set headers for */ protected void addInternalHeaders(HttpRequestBase request) { if (headers.isEmpty()) { return; } final Set<String> keySet = headers.keySet(); for (final String key : keySet) { final List<String> values = headers.get(key); for (final String value : values) { request.addHeader(key, value); } } }
From source file:net.oauth.client.httpclient4.HttpClient4.java
public HttpResponseMessage execute(HttpMessage request, Map<String, Object> parameters) throws IOException { final String method = request.method; final String url = request.url.toExternalForm(); final InputStream body = request.getBody(); final boolean isDelete = DELETE.equalsIgnoreCase(method); final boolean isPost = POST.equalsIgnoreCase(method); final boolean isPut = PUT.equalsIgnoreCase(method); byte[] excerpt = null; HttpRequestBase httpRequest; if (isPost || isPut) { HttpEntityEnclosingRequestBase entityEnclosingMethod = isPost ? new HttpPost(url) : new HttpPut(url); if (body != null) { ExcerptInputStream e = new ExcerptInputStream(body); excerpt = e.getExcerpt();//w w w . j a v a 2s . c o m String length = request.removeHeaders(HttpMessage.CONTENT_LENGTH); entityEnclosingMethod .setEntity(new InputStreamEntity(e, (length == null) ? -1 : Long.parseLong(length))); } httpRequest = entityEnclosingMethod; } else if (isDelete) { httpRequest = new HttpDelete(url); } else { httpRequest = new HttpGet(url); } for (Map.Entry<String, String> header : request.headers) { httpRequest.addHeader(header.getKey(), header.getValue()); } HttpParams params = httpRequest.getParams(); for (Map.Entry<String, Object> p : parameters.entrySet()) { String name = p.getKey(); String value = p.getValue().toString(); if (FOLLOW_REDIRECTS.equals(name)) { params.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, Boolean.parseBoolean(value)); } else if (READ_TIMEOUT.equals(name)) { params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, Integer.parseInt(value)); } else if (CONNECT_TIMEOUT.equals(name)) { params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, Integer.parseInt(value)); } } HttpClient client = clientPool.getHttpClient(new URL(httpRequest.getURI().toString())); HttpResponse httpResponse = client.execute(httpRequest); return new HttpMethodResponse(httpRequest, httpResponse, excerpt, request.getContentCharset()); }
From source file:com.k42b3.neodym.Http.java
public String request(int method, String url, Map<String, String> header, String body, boolean signed) throws Exception { // check cache (only GET) String cacheKey = url;/*ww w. j a va 2s .c om*/ if (method == Http.GET) { Cache cache = cacheManager.get(cacheKey); if (cache != null) { logger.info("Found cache for " + cacheKey + " expires in " + DateFormat.getInstance().format(cache.getExpire())); return cache.getResponse(); } } // build request HttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, 6000); DefaultHttpClient httpClient = new DefaultHttpClient(httpParams); HttpRequestBase httpRequest; if (method == Http.GET) { httpRequest = new HttpGet(url); } else if (method == Http.POST) { httpRequest = new HttpPost(url); if (body != null && !body.isEmpty()) { ((HttpPost) httpRequest).setEntity(new StringEntity(body)); } } else { throw new Exception("Invalid request method"); } // add headers if (header != null) { Set<String> keys = header.keySet(); for (String k : keys) { httpRequest.addHeader(k, header.get(k)); } } // sign request if (oauth != null && signed) { oauth.signRequest(httpRequest); } // execute request logger.info("Request: " + httpRequest.getRequestLine().toString()); HttpResponse httpResponse = httpClient.execute(httpRequest); logger.info("Response: " + httpResponse.getStatusLine().toString()); HttpEntity entity = httpResponse.getEntity(); String responseContent = EntityUtils.toString(entity); // log traffic if (trafficListener != null) { TrafficItem trafficItem = new TrafficItem(); trafficItem.setRequest(httpRequest); trafficItem.setRequestContent(body); trafficItem.setResponse(httpResponse); trafficItem.setResponseContent(responseContent); trafficListener.handleRequest(trafficItem); } // check status code int statusCode = httpResponse.getStatusLine().getStatusCode(); if (!(statusCode >= 200 && statusCode < 300)) { if (!responseContent.isEmpty()) { String message = responseContent.length() > 128 ? responseContent.substring(0, 128) + "..." : responseContent; throw new Exception(message); } else { throw new Exception("No successful status code"); } } // assign last request/response lastRequest = httpRequest; lastResponse = httpResponse; // cache response if expires header is set if (method == Http.GET) { Date expire = null; Header[] headers = httpResponse.getAllHeaders(); for (int i = 0; i < headers.length; i++) { if (headers[i].getName().toLowerCase().equals("expires")) { try { expire = DateFormat.getInstance().parse(headers[i].getValue()); } catch (Exception e) { } } } if (expire != null && expire.compareTo(new Date()) > 0) { Cache cache = new Cache(cacheKey, responseContent, expire); cacheManager.add(cache); logger.info("Add to cache " + cacheKey + " expires in " + DateFormat.getInstance().format(expire)); } } return responseContent; }
From source file:org.niord.core.keycloak.KeycloakIntegrationService.java
/** * Executes a Keycloak admin request and returns the result. * * @param request the Keycloak request to execute * @param auth whether to add a Bearer authorization header or not * @param responseHandler the response handler * @return the result//from w ww . j a v a2s .c o m */ private <R> R executeAdminRequest(HttpRequestBase request, boolean auth, KeycloakResponseHandler<R> responseHandler) throws Exception { if (auth) { KeycloakPrincipal keycloakPrincipal = userService.getCallerPrincipal(); if (keycloakPrincipal == null) { throw new Exception("Unable to execute request " + request.getURI() + ". User not authenticated"); } request.addHeader("Authorization", "Bearer " + keycloakPrincipal.getKeycloakSecurityContext().getTokenString()); } // TODO: Check if this works with https based on self-signed certificates HttpClient client = HttpClients.custom().setHostnameVerifier(new AllowAllHostnameVerifier()).build(); HttpResponse response = client.execute(request); int status = response.getStatusLine().getStatusCode(); if (status < 200 || status > 299) { try { response.getEntity().getContent().close(); } catch (Exception ignored) { } throw new Exception("Unable to execute request " + request.getURI() + ", status = " + status); } HttpEntity entity = response.getEntity(); if (entity == null) { return responseHandler.execute(null); } try (InputStream is = entity.getContent()) { return responseHandler.execute(is); } }
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);/*from w ww .ja v a2s. com*/ 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:com.funambol.platform.HttpConnectionAdapter.java
private void performRequest(HttpRequestBase req) throws IOException { // Set all the headers if (requestHeaders != null) { for (String key : requestHeaders.keySet()) { String value = requestHeaders.get(key); // The content length is set by httpclient and it is fetched // from the request stream if (!"Content-Length".equals(key)) { Log.trace(TAG_LOG, "Setting header: " + key + "=" + value); req.addHeader(key, value); }// ww w .j a v a2s . com } } HttpParams params = httpClient.getParams(); // Set the proxy if necessary if (proxyConfig != null) { ConnRouteParams.setDefaultProxy(params, new HttpHost(proxyConfig.getAddress(), proxyConfig.getPort())); httpClient.setParams(params); } else { // TODO FIXME: remove the proxy } //FIXME // Log.debug(TAG_LOG, "Setting socket buffer size"); // HttpConnectionParams.setSocketBufferSize(params, 900); try { Log.trace(TAG_LOG, "Executing request"); httpResponse = httpClient.execute(req); } catch (Exception e) { Log.error(TAG_LOG, "Exception while executing request", e); throw new IOException(e.toString()); } // Set the response StatusLine statusLine = httpResponse.getStatusLine(); responseCode = statusLine.getStatusCode(); HttpEntity respEntity = httpResponse.getEntity(); if (respEntity != null) { respInputStream = respEntity.getContent(); } responseHeaders = httpResponse.getAllHeaders(); }
From source file:org.apache.solr.client.solrj.impl.SolrClientCloudManager.java
@Override public byte[] httpRequest(String url, SolrRequest.METHOD method, Map<String, String> headers, String payload, int timeout, boolean followRedirects) throws IOException { HttpClient client = solrClient.getHttpClient(); final HttpRequestBase req; HttpEntity entity = null;/*from w ww . j a va 2 s. c o m*/ if (payload != null) { entity = new StringEntity(payload, "UTF-8"); } switch (method) { case GET: req = new HttpGet(url); break; case POST: req = new HttpPost(url); if (entity != null) { ((HttpPost) req).setEntity(entity); } break; case PUT: req = new HttpPut(url); if (entity != null) { ((HttpPut) req).setEntity(entity); } break; case DELETE: req = new HttpDelete(url); break; default: throw new IOException("Unsupported method " + method); } if (headers != null) { headers.forEach((k, v) -> req.addHeader(k, v)); } RequestConfig.Builder requestConfigBuilder = HttpClientUtil.createDefaultRequestConfigBuilder(); if (timeout > 0) { requestConfigBuilder.setSocketTimeout(timeout); requestConfigBuilder.setConnectTimeout(timeout); } requestConfigBuilder.setRedirectsEnabled(followRedirects); req.setConfig(requestConfigBuilder.build()); HttpClientContext httpClientRequestContext = HttpClientUtil.createNewHttpClientRequestContext(); HttpResponse rsp = client.execute(req, httpClientRequestContext); int statusCode = rsp.getStatusLine().getStatusCode(); if (statusCode != 200) { throw new IOException("Error sending request to " + url + ", HTTP response: " + rsp.toString()); } HttpEntity responseEntity = rsp.getEntity(); if (responseEntity != null && responseEntity.getContent() != null) { return EntityUtils.toByteArray(responseEntity); } else { return EMPTY; } }