List of usage examples for org.apache.http.client.methods HttpRequestBase setHeader
public void setHeader(String str, String str2)
From source file:org.instagram4j.DefaultInstagramClient.java
private void setEnforceHeader(HttpRequestBase method) { if (!isSignedHeaderEnabled()) return;/*from www.j av a 2s.co m*/ if (clientSecret == null) throw new IllegalStateException("Client secret it required to use signed header"); if (clientIps == null || clientIps.length() == 0) throw new IllegalStateException("Client IP(s) required to use signed header"); try { SecretKeySpec signingKey = new SecretKeySpec(getClientSecret().getBytes(), HMAC_SHA256_ALGO); Mac mac = Mac.getInstance(HMAC_SHA256_ALGO); mac.init(signingKey); // Compute the hmac on IP address. byte[] rawHmac = mac.doFinal(clientIps.getBytes()); String digest = Hex.encodeHexString(rawHmac); method.setHeader("X-Insta-Forwarded-For", String.format("%s|%s", clientIps, digest)); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("Unexpected error creating signed header using HMAC-SHA256", e); } catch (InvalidKeyException e) { throw new IllegalStateException("Unexpected error creating signed header using HMAC-SHA256", e); } }
From source file:com.meplato.store2.ApacheHttpClient.java
/** * Execute runs a HTTP request/response with an API endpoint. * * @param method the HTTP method, e.g. POST or GET * @param uriTemplate the URI template according to RFC 6570 * @param parameters the query string parameters * @param headers the key/value pairs for the HTTP header * @param body the body of the request or {@code null} * @return the HTTP response encapsulated by {@link Response}. * @throws ServiceException if e.g. the service is unavailable. *//* w ww . j a v a 2s . com*/ @Override public Response execute(String method, String uriTemplate, Map<String, Object> parameters, Map<String, String> headers, Object body) throws ServiceException { // URI template parameters String url = UriTemplate.fromTemplate(uriTemplate).expand(parameters); // Body HttpEntity requestEntity = null; if (body != null) { Gson gson = getSerializer(); try { requestEntity = EntityBuilder.create().setText(gson.toJson(body)).setContentEncoding("UTF-8") .setContentType(ContentType.APPLICATION_JSON).build(); } catch (Exception e) { throw new ServiceException("Error serializing body", null, e); } } // Do HTTP request HttpRequestBase httpRequest = null; if (method.equalsIgnoreCase("GET")) { httpRequest = new HttpGet(url); } else if (method.equalsIgnoreCase("POST")) { HttpPost httpPost = new HttpPost(url); if (requestEntity != null) { httpPost.setEntity(requestEntity); } httpRequest = httpPost; } else if (method.equalsIgnoreCase("PUT")) { HttpPut httpPut = new HttpPut(url); if (requestEntity != null) { httpPut.setEntity(requestEntity); } httpRequest = httpPut; } else if (method.equalsIgnoreCase("DELETE")) { httpRequest = new HttpDelete(url); } else if (method.equalsIgnoreCase("PATCH")) { HttpPatch httpPatch = new HttpPatch(url); if (requestEntity != null) { httpPatch.setEntity(requestEntity); } httpRequest = httpPatch; } else if (method.equalsIgnoreCase("HEAD")) { httpRequest = new HttpHead(url); } else if (method.equalsIgnoreCase("OPTIONS")) { httpRequest = new HttpOptions(url); } else { throw new ServiceException("Invalid HTTP method: " + method, null, null); } // Headers for (Map.Entry<String, String> entry : headers.entrySet()) { httpRequest.addHeader(entry.getKey(), entry.getValue()); } httpRequest.setHeader("Accept", "application/json"); httpRequest.setHeader("Accept-Charset", "utf-8"); httpRequest.setHeader("Content-Type", "application/json; charset=utf-8"); httpRequest.setHeader("User-Agent", USER_AGENT); try (CloseableHttpResponse httpResponse = httpClient.execute(httpRequest)) { Response response = new ApacheHttpResponse(httpResponse); int statusCode = response.getStatusCode(); if (statusCode >= 200 && statusCode < 300) { return response; } throw ServiceException.fromResponse(response); } catch (ClientProtocolException e) { throw new ServiceException("Client Protocol Exception", null, e); } catch (IOException e) { throw new ServiceException("IO Exception", null, e); } }
From source file:groovyx.net.http.HTTPBuilder.java
/** * All <code>request</code> methods delegate to this method. *///from ww w . j ava 2 s. co m protected Object doRequest(final RequestConfigDelegate delegate) throws ClientProtocolException, IOException { final HttpRequestBase reqMethod = delegate.getRequest(); Object contentType = delegate.getContentType(); if (this.autoAcceptHeader) { String acceptContentTypes = contentType.toString(); if (contentType instanceof ContentType) acceptContentTypes = ((ContentType) contentType).getAcceptHeader(); reqMethod.setHeader("Accept", acceptContentTypes); } reqMethod.setURI(delegate.getUri().toURI()); if (reqMethod.getURI() == null) throw new IllegalStateException("Request URI cannot be null"); log.debug(reqMethod.getMethod() + " " + reqMethod.getURI()); // set any request headers from the delegate Map<?, ?> headers = delegate.getHeaders(); for (Object key : headers.keySet()) { Object val = headers.get(key); if (key == null) continue; if (val == null) reqMethod.removeHeaders(key.toString()); else reqMethod.setHeader(key.toString(), val.toString()); } HttpResponseDecorator resp = new HttpResponseDecorator(client.execute(reqMethod, delegate.getContext()), delegate.getContext(), null); try { int status = resp.getStatusLine().getStatusCode(); Closure responseClosure = delegate.findResponseHandler(status); log.debug("Response code: " + status + "; found handler: " + responseClosure); Object[] closureArgs = null; switch (responseClosure.getMaximumNumberOfParameters()) { case 1: closureArgs = new Object[] { resp }; break; case 2: // parse the response entity if the response handler expects it: HttpEntity entity = resp.getEntity(); try { if (entity == null || entity.getContentLength() == 0) closureArgs = new Object[] { resp, null }; else closureArgs = new Object[] { resp, parseResponse(resp, contentType) }; } catch (Exception ex) { Header h = entity.getContentType(); String respContentType = h != null ? h.getValue() : null; log.warn("Error parsing '" + respContentType + "' response", ex); throw new ResponseParseException(resp, ex); } break; default: throw new IllegalArgumentException("Response closure must accept one or two parameters"); } Object returnVal = responseClosure.call(closureArgs); log.trace("response handler result: " + returnVal); return returnVal; } finally { HttpEntity entity = resp.getEntity(); if (entity != null) entity.consumeContent(); } }
From source file:com.arangodb.http.HttpManager.java
/** * Executes the request//from w ww. ja v a2 s. c om * * @param requestEntity * the request * @return the response of the request * @throws ArangoException */ private HttpResponseEntity executeInternal(String baseUrl, HttpRequestEntity requestEntity) throws ArangoException, SocketException { String url = buildUrl(baseUrl, requestEntity); if (logger.isDebugEnabled()) { if (requestEntity.type == RequestType.POST || requestEntity.type == RequestType.PUT || requestEntity.type == RequestType.PATCH) { logger.debug("[REQ]http-{}: url={}, headers={}, body={}", new Object[] { requestEntity.type, url, requestEntity.headers, requestEntity.bodyText }); } else { logger.debug("[REQ]http-{}: url={}, headers={}", new Object[] { requestEntity.type, url, requestEntity.headers }); } } HttpRequestBase request = null; switch (requestEntity.type) { case GET: request = new HttpGet(url); break; case POST: HttpPost post = new HttpPost(url); configureBodyParams(requestEntity, post); request = post; break; case PUT: HttpPut put = new HttpPut(url); configureBodyParams(requestEntity, put); request = put; break; case PATCH: HttpPatch patch = new HttpPatch(url); configureBodyParams(requestEntity, patch); request = patch; break; case HEAD: request = new HttpHead(url); break; case DELETE: request = new HttpDelete(url); break; } // common-header String userAgent = "Mozilla/5.0 (compatible; ArangoDB-JavaDriver/1.1; +http://mt.orz.at/)"; request.setHeader("User-Agent", userAgent); // optinal-headers if (requestEntity.headers != null) { for (Entry<String, Object> keyValue : requestEntity.headers.entrySet()) { request.setHeader(keyValue.getKey(), keyValue.getValue().toString()); } } // Basic Auth Credentials credentials = null; if (requestEntity.username != null && requestEntity.password != null) { credentials = new UsernamePasswordCredentials(requestEntity.username, requestEntity.password); } else if (configure.getUser() != null && configure.getPassword() != null) { credentials = new UsernamePasswordCredentials(configure.getUser(), configure.getPassword()); } if (credentials != null) { BasicScheme basicScheme = new BasicScheme(); try { request.addHeader(basicScheme.authenticate(credentials, request, null)); } catch (AuthenticationException e) { throw new ArangoException(e); } } if (this.getHttpMode().equals(HttpMode.ASYNC)) { request.addHeader("x-arango-async", "store"); } else if (this.getHttpMode().equals(HttpMode.FIREANDFORGET)) { request.addHeader("x-arango-async", "true"); } // CURL/httpie Logger if (configure.isEnableCURLLogger()) { CURLLogger.log(url, requestEntity, userAgent, credentials); } HttpResponse response = null; if (preDefinedResponse != null) { return preDefinedResponse; } try { response = client.execute(request); if (response == null) { return null; } HttpResponseEntity responseEntity = new HttpResponseEntity(); // http status StatusLine status = response.getStatusLine(); responseEntity.statusCode = status.getStatusCode(); responseEntity.statusPhrase = status.getReasonPhrase(); logger.debug("[RES]http-{}: statusCode={}", requestEntity.type, responseEntity.statusCode); // ?? // // TODO etag??? Header etagHeader = response.getLastHeader("etag"); if (etagHeader != null) { responseEntity.etag = Long.parseLong(etagHeader.getValue().replace("\"", "")); } // Map??? responseEntity.headers = new TreeMap<String, String>(); for (Header header : response.getAllHeaders()) { responseEntity.headers.put(header.getName(), header.getValue()); } // ??? HttpEntity entity = response.getEntity(); if (entity != null) { Header contentType = entity.getContentType(); if (contentType != null) { responseEntity.contentType = contentType.getValue(); if (responseEntity.isDumpResponse()) { responseEntity.stream = entity.getContent(); logger.debug("[RES]http-{}: stream, {}", requestEntity.type, contentType.getValue()); } } // Close stream in this method. if (responseEntity.stream == null) { responseEntity.text = IOUtils.toString(entity.getContent()); logger.debug("[RES]http-{}: text={}", requestEntity.type, responseEntity.text); } } if (this.getHttpMode().equals(HttpMode.ASYNC)) { Map<String, String> map = responseEntity.getHeaders(); this.addJob(map.get("X-Arango-Async-Id"), this.getCurrentObject()); } else if (this.getHttpMode().equals(HttpMode.FIREANDFORGET)) { return null; } return responseEntity; } catch (SocketException ex) { throw ex; } catch (ClientProtocolException e) { throw new ArangoException(e); } catch (IOException e) { throw new ArangoException(e); } }
From source file:immf.ImodeNetClient.java
/** * POST????????// w w w. j a v a2s. c o m * @param req * @return * @throws IOException */ private HttpResponse executeHttp(HttpRequestBase req) throws IOException { try { for (int i = 0; i < 4; i++) { HttpResponse res = this.httpClient.execute(req); int status = res.getStatusLine().getStatusCode(); if (300 <= status && status <= 399) { req.abort(); URI location = httpClient.getRedirectHandler().getLocationURI(res, new BasicHttpContext()); //System.out.println("Redirect "+location); req = new HttpGet(location); req.setHeader("User-Agent", "Mozilla/4.0 (compatible;MSIE 7.0; Windows NT 6.0;)"); } else { return res; } } } catch (IllegalStateException e) { e.printStackTrace(); log.info("HttpClient Fatal Error. Restarting HttpCient"); HttpParams params = this.httpClient.getParams(); this.httpClient.getConnectionManager().shutdown(); this.httpClient = new DefaultHttpClient(); this.httpClient.setParams(params); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); req.abort(); } return null; }
From source file:io.apiman.test.common.util.TestPlanRunner.java
/** * Runs a single REST test./* w w w.j a v a2 s.com*/ * * @param restTest */ private void runTest(RestTest restTest) throws Error { try { String requestPath = TestUtil.doPropertyReplacement(restTest.getRequestPath()); URI uri = getUri(requestPath); HttpRequestBase request = null; if (restTest.getRequestMethod().equalsIgnoreCase("GET")) { //$NON-NLS-1$ request = new HttpGet(); } else if (restTest.getRequestMethod().equalsIgnoreCase("POST")) { //$NON-NLS-1$ request = new HttpPost(); HttpEntity entity = new StringEntity(restTest.getRequestPayload()); ((HttpPost) request).setEntity(entity); } else if (restTest.getRequestMethod().equalsIgnoreCase("PUT")) { //$NON-NLS-1$ request = new HttpPut(); HttpEntity entity = new StringEntity(restTest.getRequestPayload()); ((HttpPut) request).setEntity(entity); } else if (restTest.getRequestMethod().equalsIgnoreCase("DELETE")) { //$NON-NLS-1$ request = new HttpDelete(); } if (request == null) { Assert.fail("Unsupported method in REST Test: " + restTest.getRequestMethod()); //$NON-NLS-1$ } request.setURI(uri); Map<String, String> requestHeaders = restTest.getRequestHeaders(); for (Entry<String, String> entry : requestHeaders.entrySet()) { request.setHeader(entry.getKey(), entry.getValue()); } // Set up basic auth String authorization = createBasicAuthorization(restTest.getUsername(), restTest.getPassword()); if (authorization != null) { request.setHeader("Authorization", authorization); //$NON-NLS-1$ } HttpResponse response = client.execute(request); assertResponse(restTest, response); } catch (Error e) { logPlain("[ERROR] " + e.getMessage()); //$NON-NLS-1$ throw e; } catch (Exception e) { throw new Error(e); } }
From source file:com.appdynamics.demo.gasp.service.RESTIntentService.java
@Override protected void onHandleIntent(Intent intent) { Uri action = intent.getData();//from w ww .j a va2s . c om Bundle extras = intent.getExtras(); if (extras == null || action == null || !extras.containsKey(EXTRA_RESULT_RECEIVER)) { Log.e(TAG, "You did not pass extras or data with the Intent."); return; } int verb = extras.getInt(EXTRA_HTTP_VERB, GET); Bundle params = extras.getParcelable(EXTRA_PARAMS); Bundle headers = extras.getParcelable(EXTRA_HEADERS); ResultReceiver receiver = extras.getParcelable(EXTRA_RESULT_RECEIVER); try { HttpRequestBase request = null; // Get query params from Bundle and build URL switch (verb) { case GET: { request = new HttpGet(); attachUriWithQuery(request, action, params); } break; case DELETE: { request = new HttpDelete(); attachUriWithQuery(request, action, params); } break; case POST: { request = new HttpPost(); request.setURI(new URI(action.toString())); HttpPost postRequest = (HttpPost) request; if (params != null) { UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(paramsToList(params)); postRequest.setEntity(formEntity); } } break; case PUT: { request = new HttpPut(); request.setURI(new URI(action.toString())); HttpPut putRequest = (HttpPut) request; if (params != null) { UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(paramsToList(params)); putRequest.setEntity(formEntity); } } break; } // Get Headers from Bundle for (BasicNameValuePair header : paramsToList(headers)) { request.setHeader(header.getName(), header.getValue()); } if (request != null) { HttpClient client = new DefaultHttpClient(); Log.d(TAG, "Executing request: " + verbToString(verb) + ": " + action.toString()); HttpResponse response = client.execute(request); HttpEntity responseEntity = response.getEntity(); StatusLine responseStatus = response.getStatusLine(); int statusCode = responseStatus != null ? responseStatus.getStatusCode() : 0; if ((responseEntity != null) && (responseStatus.getStatusCode() == 200)) { Bundle resultData = new Bundle(); resultData.putString(REST_RESULT, EntityUtils.toString(responseEntity)); receiver.send(statusCode, resultData); } else { receiver.send(statusCode, null); } } } catch (URISyntaxException e) { Log.e(TAG, "URI syntax was incorrect. " + verbToString(verb) + ": " + action.toString(), e); receiver.send(0, null); } catch (UnsupportedEncodingException e) { Log.e(TAG, "A UrlEncodedFormEntity was created with an unsupported encoding.", e); receiver.send(0, null); } catch (ClientProtocolException e) { Log.e(TAG, "There was a problem when sending the request.", e); receiver.send(0, null); } catch (IOException e) { Log.e(TAG, "There was a problem when sending the request.", e); receiver.send(0, null); } catch (Exception e) { e.printStackTrace(); } }
From source file:org.fao.geonet.api.mapservers.GeoServerRest.java
/** * @param method e.g. 'POST', 'GET', 'PUT' or 'DELETE' * @param urlParams REST API parameter * @param postData XML data//from ww w. ja v a 2 s . c o m * @param file File to upload * @param contentType type of content in case of post data or file updload. */ public @CheckReturnValue int sendREST(String method, String urlParams, String postData, Path file, String contentType, Boolean saveResponse) throws IOException { response = ""; String url = this.restUrl + urlParams; if (Log.isDebugEnabled(LOGGER_NAME)) { Log.debug(LOGGER_NAME, "url:" + url); Log.debug(LOGGER_NAME, "method:" + method); if (postData != null) Log.debug(LOGGER_NAME, "postData:" + postData); } HttpRequestBase m; if (method.equals(METHOD_PUT)) { m = new HttpPut(url); if (file != null) { ((HttpPut) m) .setEntity(new PathHttpEntity(file, ContentType.create(contentType, Constants.ENCODING))); } if (postData != null) { final StringEntity entity = new StringEntity(postData, ContentType.create(contentType, Constants.ENCODING)); ((HttpPut) m).setEntity(entity); } } else if (method.equals(METHOD_DELETE)) { m = new HttpDelete(url); } else if (method.equals(METHOD_POST)) { m = new HttpPost(url); if (postData != null) { final StringEntity entity = new StringEntity(postData, ContentType.create(contentType, Constants.ENCODING)); ((HttpPost) m).setEntity(entity); } } else { m = new HttpGet(url); } if (contentType != null && !"".equals(contentType)) { m.setHeader("Content-type", contentType); } m.setConfig(RequestConfig.custom().setAuthenticationEnabled(true).build()); // apparently this is needed to preemptively send the auth, for servers that dont require it but // dont send the same data if you're authenticated or not. try { m.addHeader(new BasicScheme().authenticate(new UsernamePasswordCredentials(username, password), m)); } catch (AuthenticationException a) { Log.warning(LOGGER_NAME, "Failed to add the authentication Header, error is: " + a.getMessage()); } ; final ClientHttpResponse httpResponse = factory.execute(m, new UsernamePasswordCredentials(username, password), AuthScope.ANY); try { status = httpResponse.getRawStatusCode(); if (Log.isDebugEnabled(LOGGER_NAME)) { Log.debug(LOGGER_NAME, "status:" + status); } if (saveResponse) { this.response = IOUtils.toString(httpResponse.getBody()); } } finally { httpResponse.close(); } return status; }
From source file:eu.vital.TrustManager.connectors.dms.DMSManager.java
private String query(String dms_endpoint, String body, String method) throws SocketTimeoutException, ConnectException, IOException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException { Cookie ck;// w w w . j a va 2s . c o m //String internalToken; CloseableHttpClient httpclient; HttpRequestBase httpaction; //boolean wasEmpty; //int code; SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build()); httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); URI uri = null; try { // Prepare to forward the request to the proxy uri = new URI(dms_URL + "/" + dms_endpoint); } catch (URISyntaxException e1) { java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null, e1); } if (method.equals("GET")) { httpaction = new HttpGet(uri); } else { httpaction = new HttpPost(uri); } // Get token or authenticate if null or invalid //internalToken = client.getToken(); ck = new Cookie("vitalAccessToken", cookie.substring(17)); httpaction.setHeader("Cookie", ck.toString()); httpaction.setConfig(RequestConfig.custom().setConnectionRequestTimeout(5000).setConnectTimeout(5000) .setSocketTimeout(5000).build()); httpaction.setHeader("Content-Type", javax.ws.rs.core.MediaType.APPLICATION_JSON); StringEntity strEntity = new StringEntity(body, StandardCharsets.UTF_8); if (method.equals("POST")) { ((HttpPost) httpaction).setEntity(strEntity); } // Execute and get the response. CloseableHttpResponse response = null; try { response = httpclient.execute(httpaction); } catch (ClientProtocolException e) { java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null, e); } catch (IOException e) { try { // Try again with a higher timeout try { Thread.sleep(1000); // do not retry immediately } catch (InterruptedException e1) { java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null, e1); return ""; } httpaction.setConfig(RequestConfig.custom().setConnectionRequestTimeout(7000) .setConnectTimeout(7000).setSocketTimeout(7000).build()); response = httpclient.execute(httpaction); } catch (ClientProtocolException ea) { java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null, ea); return ""; } catch (IOException ea) { try { // Try again with a higher timeout try { Thread.sleep(1000); // do not retry immediately } catch (InterruptedException e1) { java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null, e1); return ""; } httpaction.setConfig(RequestConfig.custom().setConnectionRequestTimeout(12000) .setConnectTimeout(12000).setSocketTimeout(12000).build()); response = httpclient.execute(httpaction); } catch (ClientProtocolException eaa) { java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null, eaa); return ""; } catch (SocketTimeoutException eaa) { java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null, eaa); return ""; } catch (ConnectException eaa) { java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null, eaa); return ""; } catch (ConnectTimeoutException eaa) { java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null, eaa); return ""; } } } int statusCode = response.getStatusLine().getStatusCode(); String respString = ""; HttpEntity entity = null; if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_ACCEPTED) { entity = response.getEntity(); } else { if (statusCode == 503) { java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null, "httpStatusCode 503"); return ""; } else if (statusCode == 502) { java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null, "httpStatusCode 502"); return ""; } else if (statusCode == 401) { java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null, "httpStatusCode 401"); return ""; } else { java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null, "PPI 500"); return ""; //throw new ServiceUnavailableException(); } } if (entity != null) { try { respString = EntityUtils.toString(entity); response.close(); } catch (ParseException | IOException e) { java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null, "PPI 401"); return ""; } } return respString; }