List of usage examples for org.apache.http.client.methods HttpRequestBase addHeader
public void addHeader(String str, String str2)
From source file:sk.datalan.solr.impl.HttpSolrServer.java
protected NamedList<Object> executeMethod(HttpRequestBase method, final ResponseParser processor) throws SolrServerException { // // XXX client already has this set, is this needed? // method.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, // followRedirects); method.addHeader("User-Agent", AGENT); InputStream respBody = null;/*from w w w. j a va 2 s .c o m*/ boolean shouldClose = true; boolean success = false; try { // Execute the method. final HttpResponse response = httpClient.execute(method); int httpStatus = response.getStatusLine().getStatusCode(); // Read the contents respBody = response.getEntity().getContent(); Header ctHeader = response.getLastHeader("content-type"); String contentType; if (ctHeader != null) { contentType = ctHeader.getValue(); } else { contentType = ""; } // handle some http level checks before trying to parse the response switch (httpStatus) { case HttpStatus.SC_OK: case HttpStatus.SC_BAD_REQUEST: case HttpStatus.SC_CONFLICT: // 409 break; case HttpStatus.SC_MOVED_PERMANENTLY: case HttpStatus.SC_MOVED_TEMPORARILY: if (!followRedirects) { throw new SolrServerException( "Server at " + getBaseURL() + " sent back a redirect (" + httpStatus + ")."); } break; default: if (processor == null) { throw new RemoteSolrException(httpStatus, "Server at " + getBaseURL() + " returned non ok status:" + httpStatus + ", message:" + response.getStatusLine().getReasonPhrase(), null); } } if (processor == null) { // no processor specified, return raw stream NamedList<Object> rsp = new NamedList<>(); rsp.add("stream", respBody); // Only case where stream should not be closed shouldClose = false; success = true; return rsp; } String procCt = processor.getContentType(); if (procCt != null) { String procMimeType = ContentType.parse(procCt).getMimeType().trim().toLowerCase(Locale.ROOT); String mimeType = ContentType.parse(contentType).getMimeType().trim().toLowerCase(Locale.ROOT); if (!procMimeType.equals(mimeType)) { // unexpected mime type String msg = "Expected mime type " + procMimeType + " but got " + mimeType + "."; Header encodingHeader = response.getEntity().getContentEncoding(); String encoding; if (encodingHeader != null) { encoding = encodingHeader.getValue(); } else { encoding = "UTF-8"; // try UTF-8 } try { msg = msg + " " + IOUtils.toString(respBody, encoding); } catch (IOException e) { throw new RemoteSolrException(httpStatus, "Could not parse response with encoding " + encoding, e); } RemoteSolrException e = new RemoteSolrException(httpStatus, msg, null); throw e; } } // if(true) { // ByteArrayOutputStream copy = new ByteArrayOutputStream(); // IOUtils.copy(respBody, copy); // String val = new String(copy.toByteArray()); // System.out.println(">RESPONSE>"+val+"<"+val.length()); // respBody = new ByteArrayInputStream(copy.toByteArray()); // } NamedList<Object> rsp = null; ContentType ct = ContentType.getOrDefault(response.getEntity()); try { rsp = processor.processResponse(respBody, ct.getCharset().toString()); } catch (Exception e) { throw new RemoteSolrException(httpStatus, e.getMessage(), e); } if (httpStatus != HttpStatus.SC_OK) { String reason = null; try { NamedList err = (NamedList) rsp.get("error"); if (err != null) { reason = (String) err.get("msg"); if (reason == null) { reason = (String) err.get("trace"); } } } catch (Exception ex) { } if (reason == null) { StringBuilder msg = new StringBuilder(); msg.append(response.getStatusLine().getReasonPhrase()); msg.append("\n\n"); msg.append("request: ").append(method.getURI()); reason = java.net.URLDecoder.decode(msg.toString(), UTF_8); } throw new RemoteSolrException(httpStatus, reason, null); } success = true; return rsp; } catch (ConnectException e) { throw new SolrServerException("Server refused connection at: " + getBaseURL(), e); } catch (SocketTimeoutException e) { throw new SolrServerException("Timeout occured while waiting response from server at: " + getBaseURL(), e); } catch (IOException e) { throw new SolrServerException("IOException occured when talking to server at: " + getBaseURL(), e); } finally { if (respBody != null && shouldClose) { try { respBody.close(); } catch (IOException e) { log.error("", e); } finally { if (!success) { method.abort(); } } } } }
From source file:com.comcast.drivethru.client.DefaultRestClient.java
@Override public RestResponse execute(RestRequest request) throws HttpException { /* Build the URL String */ String url = request.getUrl().setDefaultBaseUrl(defaultBaseUrl).build(); /* Get our Apache RestRequest object */ Method method = request.getMethod(); HttpRequestBase req = method.getRequest(url); req.setConfig(request.getConfig());/* w w w. j a v a 2 s . c o m*/ /* Add the Body */ byte[] payload = request.getBody(); if (null != payload) { if (req instanceof HttpEntityEnclosingRequest) { HttpEntity entity = new ByteArrayEntity(payload); ((HttpEntityEnclosingRequest) req).setEntity(entity); } else { throw new HttpException("Cannot attach a body to a " + method.name() + " request"); } } /* Add all Headers */ for (Entry<String, String> pair : defaultHeaders.entrySet()) { req.addHeader(pair.getKey(), pair.getValue()); } for (Entry<String, String> pair : request.getHeaders().entrySet()) { req.addHeader(pair.getKey(), pair.getValue()); } /* If there is a security provider, sign */ if (null != securityProvider) { securityProvider.sign(req); } /* Closed in the finally block */ InputStream in = null; ByteArrayOutputStream baos = null; try { /* Finally, execute the thing */ org.apache.http.HttpResponse resp = delegate.execute(req); /* Create our response */ RestResponse response = new RestResponse(resp.getStatusLine()); /* Add all Headers */ response.addAll(resp.getAllHeaders()); /* Add the content */ HttpEntity body = resp.getEntity(); if (null != body) { in = body.getContent(); baos = new ByteArrayOutputStream(); IOUtils.copy(in, baos); response.setBody(baos.toByteArray()); } return response; } catch (RuntimeException ex) { // release resources immediately req.abort(); throw ex; } catch (HttpResponseException hrex) { throw new HttpStatusException(hrex.getStatusCode()); } catch (ClientProtocolException cpex) { throw new HttpException("HTTP Protocol error occurred.", cpex); } catch (IOException ioex) { throw new HttpException("Error establishing connection.", ioex); } finally { req.abort(); IOUtils.closeQuietly(in); IOUtils.closeQuietly(baos); } }
From source file:com.mashape.unirest.android.http.HttpClientHelper.java
private static HttpRequestBase prepareRequest(HttpRequest request, boolean async) { Object defaultHeaders = Options.getOption(Option.DEFAULT_HEADERS); if (defaultHeaders != null) { @SuppressWarnings("unchecked") Set<Entry<String, String>> entrySet = ((Map<String, String>) defaultHeaders).entrySet(); for (Entry<String, String> entry : entrySet) { request.header(entry.getKey(), entry.getValue()); }//from w w w . j av a 2s . co m } if (!request.getHeaders().containsKey(USER_AGENT_HEADER)) { request.header(USER_AGENT_HEADER, USER_AGENT); } if (!request.getHeaders().containsKey(ACCEPT_ENCODING_HEADER)) { request.header(ACCEPT_ENCODING_HEADER, "gzip"); } HttpRequestBase reqObj = null; String urlToRequest = null; try { URL url = new URL(request.getUrl()); URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), URLDecoder.decode(url.getPath(), "UTF-8"), "", url.getRef()); urlToRequest = uri.toURL().toString(); if (url.getQuery() != null && !url.getQuery().trim().equals("")) { if (!urlToRequest.substring(urlToRequest.length() - 1).equals("?")) { urlToRequest += "?"; } urlToRequest += url.getQuery(); } else if (urlToRequest.substring(urlToRequest.length() - 1).equals("?")) { urlToRequest = urlToRequest.substring(0, urlToRequest.length() - 1); } } catch (Exception e) { throw new RuntimeException(e); } switch (request.getHttpMethod()) { case GET: reqObj = new HttpGet(urlToRequest); break; case POST: reqObj = new HttpPost(urlToRequest); break; case PUT: reqObj = new HttpPut(urlToRequest); break; case DELETE: //reqObj = new HttpDeleteWithBody(urlToRequest); break; case PATCH: //reqObj = new HttpPatchWithBody(urlToRequest); break; case OPTIONS: reqObj = new HttpOptions(urlToRequest); break; case HEAD: reqObj = new HttpHead(urlToRequest); break; } Set<Entry<String, List<String>>> entrySet = request.getHeaders().entrySet(); for (Entry<String, List<String>> entry : entrySet) { List<String> values = entry.getValue(); if (values != null) { for (String value : values) { reqObj.addHeader(entry.getKey(), value); } } } // Set body if (!(request.getHttpMethod() == HttpMethod.GET || request.getHttpMethod() == HttpMethod.HEAD)) { if (request.getBody() != null) { HttpEntity entity = request.getBody().getEntity(); if (async) { if (reqObj.getHeaders(CONTENT_TYPE) == null || reqObj.getHeaders(CONTENT_TYPE).length == 0) { reqObj.setHeader(entity.getContentType()); } try { ByteArrayOutputStream output = new ByteArrayOutputStream(); entity.writeTo(output); NByteArrayEntity en = new NByteArrayEntity(output.toByteArray()); ((HttpEntityEnclosingRequestBase) reqObj).setEntity(en); } catch (IOException e) { throw new RuntimeException(e); } } else { ((HttpEntityEnclosingRequestBase) reqObj).setEntity(entity); } } } return reqObj; }
From source file:com.machinepublishers.jbrowserdriver.CookieStore.java
public void addCsrfHeaders(Settings settings, HttpRequestBase req) { final String reqHost = canonicalHost(req.getURI().getHost()); final String reqPath = canonicalPath(req.getURI().getPath()); final boolean reqSecure = isSecure(req.getURI().getScheme()); List<Cookie> list;//from w w w .ja va 2s .c o m synchronized (store) { list = store.getCookies(); } String csrfToken = null; for (Cookie cookie : list) { if ((!cookie.isSecure() || reqSecure) && reqHost.endsWith(canonicalHost(cookie.getDomain())) && reqPath.startsWith(canonicalPath(cookie.getPath()))) { if (SettingsManager.settings().getCsrfResponseToken() != null && cookie.getName().equalsIgnoreCase(SettingsManager.settings().getCsrfResponseToken())) { csrfToken = cookie.getValue(); break; } } } if (csrfToken != null) { req.addHeader(SettingsManager.settings().getCsrfRequestToken(), csrfToken); } }
From source file:com.aol.webservice_base.util.http.HttpHelper.java
/** * Http client call./*from w ww.j av a2s .c o m*/ * * callers to this are responsible for ensuring connection is closed properly - httpHelper.releaseResponse() * * @param requestMethod the request method * @param url the url * @param headers the headers * @param content the content * @return the http response * @throws HttpException the http exception */ protected HttpResponse httpClientCall(String requestMethod, String url, Map<String, String> headers, Object content) throws HttpException { HttpResponse response = null; if (!inited) { throw new Error("HttpHelper used when not initialized (call init) for " + url); } final String METHOD = "HttpHelper.httpClientCall()"; HttpRequestBase httpRequest = null; boolean success = false; int iter = 0; int status; String statusMsg; do { try { long begin = System.currentTimeMillis(); new URL(url); httpRequest = getHttpRequest(requestMethod, url, content); if (headers != null && headers.size() > 0) { for (Map.Entry<String, String> headerSet : headers.entrySet()) { httpRequest.addHeader(headerSet.getKey(), headerSet.getValue()); } } Header[] requestHeaders = httpRequest.getAllHeaders(); for (int i = 0; i < requestHeaders.length; i++) { String name = requestHeaders[i].getName(); String value = requestHeaders[i].getValue(); if (logger.isDebugEnabled()) { logger.debug("Request header " + name + " = [" + value + "]"); } } // make the request //httpRequest.setFollowRedirects(false); response = httpClient.execute(httpRequest); status = response.getStatusLine().getStatusCode(); statusMsg = response.getStatusLine().getReasonPhrase(); if (logger.isDebugEnabled()) { logger.debug(METHOD + " status=" + status + " status desc: [" + statusMsg + "] url=[" + url + "] took=" + (System.currentTimeMillis() - begin) + " ms"); } if (status == 302 || status == 301) { Header loc = httpRequest.getFirstHeader("Location"); if (loc != null) { String origUrl = url; url = loc.getValue(); if (!url.startsWith("http")) { url = addHost(origUrl, url); } continue; } } if (status != 200 /* && status != 304 */) { throw new HttpException(status, statusMsg); } if (logger.isDebugEnabled()) { Header[] responseHeaders = response.getAllHeaders(); for (int i = 0; i < responseHeaders.length; i++) { String name = responseHeaders[i].getName(); String value = responseHeaders[i].getValue(); logger.debug("Response header " + name + " = [" + value + "]"); } } success = true; return response; } catch (MalformedURLException e) { String msg = "target URL = [" + url + "] is invalid."; logger.error(msg); throw new HttpException(HttpServletResponse.SC_NOT_FOUND, msg); } catch (HttpException e) { logger.error("HttpException " + METHOD + " url=" + url + " exception=" + e.getMessage()); throw e; } catch (java.net.SocketTimeoutException e) { logger.error("SocketTimeoutException " + METHOD + " url=" + url + " exception=" + e.getMessage()); throw new HttpException(HttpServletResponse.SC_GATEWAY_TIMEOUT, "Connection or Read timeout exception: " + e); } catch (Throwable t) { logger.error("HttpException " + METHOD + " url=" + url + " exception=" + t.getMessage()); throw new HttpException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, t); } finally { // release the connection whenever we are not successful if ((!success) && (response != null)) { try { releaseResponse(response); response = null; } catch (IOException e) { logger.error("HttpHelper - problem releasing connection", e); } } } } while (!success && (++iter <= this.followRedirectMax)); throw new HttpException(status, statusMsg); }
From source file:org.forgerock.openig.http.HttpClient.java
/** * Submits the request to the remote server. Creates and populates the * response from that provided by the remote server. * * @param request The HTTP request to send. * @return The HTTP response.//from w w w .ja va 2 s . com * @throws IOException If an IO error occurred while performing the request. */ public Response execute(final Request request) throws IOException { final HttpRequestBase clientRequest = request.entity != null ? new EntityRequest(request) : new NonEntityRequest(request); clientRequest.setURI(request.uri); // connection headers to suppress final CaseInsensitiveSet suppressConnection = new CaseInsensitiveSet(); // parse request connection headers to be suppressed in request suppressConnection.addAll(new ConnectionHeader(request).getTokens()); // request headers for (final String name : request.headers.keySet()) { if (!SUPPRESS_REQUEST_HEADERS.contains(name) && !suppressConnection.contains(name)) { for (final String value : request.headers.get(name)) { clientRequest.addHeader(name, value); } } } // send request final HttpResponse clientResponse = httpClient.execute(clientRequest); final Response response = new Response(); // response entity final HttpEntity clientResponseEntity = clientResponse.getEntity(); if (clientResponseEntity != null) { response.entity = new BranchingStreamWrapper(clientResponseEntity.getContent(), storage); } // response status line final StatusLine statusLine = clientResponse.getStatusLine(); response.version = statusLine.getProtocolVersion().toString(); response.status = statusLine.getStatusCode(); response.reason = statusLine.getReasonPhrase(); // parse response connection headers to be suppressed in response suppressConnection.clear(); suppressConnection.addAll(new ConnectionHeader(response).getTokens()); // response headers for (final HeaderIterator i = clientResponse.headerIterator(); i.hasNext();) { final Header header = i.nextHeader(); final String name = header.getName(); if (!SUPPRESS_RESPONSE_HEADERS.contains(name) && !suppressConnection.contains(name)) { response.headers.add(name, header.getValue()); } } // TODO: decide if need to try-finally to call httpRequest.abort? return response; }
From source file:com.telefonica.iot.tidoop.apiext.backends.ckan.CKANBackend.java
/** * Common method to perform HTTP requests using the CKAN API with payload. * @param method HTTP method/* www .jav a2 s . co m*/ * @param url 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 url, String payload) throws Exception { 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 Exception("HTTP method not supported: " + method); } // if else // headers request.addHeader("Authorization", apiKey); // execute the request logger.debug("CKAN operation: " + request.toString()); } catch (Exception e) { throw e; } // try catch try { response = httpClientFactory.getHttpClient(ssl).execute(request); } catch (Exception e) { throw new Exception(e.getMessage()); } // try catch try { BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String res = ""; String line; while ((line = reader.readLine()) != null) { res += line; } // while 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 (IOException e) { throw e; } catch (IllegalStateException e) { throw e; } catch (ParseException e) { throw e; } // try catch }
From source file:com.uploader.Vimeo.java
private VimeoResponse apiRequest(String endpoint, String methodName, Map<String, String> params, File file) throws IOException { // try(CloseableHttpClient client = HttpClientBuilder.create().build()) { CloseableHttpClient client = HttpClientBuilder.create().build(); // CloseableHttpClient client = HttpClients.createDefault(); System.out.println("Building HTTP Client"); // try {//from w w w.j a v a 2 s. co m // client = // } catch(Exception e) { // System.out.println("Err in CloseableHttpClient"); // } // System.out.println(client); HttpRequestBase request = null; String url = null; if (endpoint.startsWith("http")) { url = endpoint; } else { url = new StringBuffer(VIMEO_SERVER).append(endpoint).toString(); } System.out.println(url); if (methodName.equals(HttpGet.METHOD_NAME)) { request = new HttpGet(url); } else if (methodName.equals(HttpPost.METHOD_NAME)) { request = new HttpPost(url); } else if (methodName.equals(HttpPut.METHOD_NAME)) { request = new HttpPut(url); } else if (methodName.equals(HttpDelete.METHOD_NAME)) { request = new HttpDelete(url); } else if (methodName.equals(HttpPatch.METHOD_NAME)) { request = new HttpPatch(url); } request.addHeader("Accept", "application/vnd.vimeo.*+json; version=3.2"); request.addHeader("Authorization", new StringBuffer(tokenType).append(" ").append(token).toString()); HttpEntity entity = null; if (params != null) { ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>(); for (String key : params.keySet()) { postParameters.add(new BasicNameValuePair(key, params.get(key))); } entity = new UrlEncodedFormEntity(postParameters); } else { if (file != null) { entity = new FileEntity(file, ContentType.MULTIPART_FORM_DATA); } } if (entity != null) { if (request instanceof HttpPost) { ((HttpPost) request).setEntity(entity); } else if (request instanceof HttpPatch) { ((HttpPatch) request).setEntity(entity); } else if (request instanceof HttpPut) { ((HttpPut) request).setEntity(entity); } } CloseableHttpResponse response = client.execute(request); String responseAsString = null; int statusCode = response.getStatusLine().getStatusCode(); if (methodName.equals(HttpPut.METHOD_NAME) || methodName.equals(HttpDelete.METHOD_NAME)) { JSONObject out = new JSONObject(); for (Header header : response.getAllHeaders()) { try { out.put(header.getName(), header.getValue()); } catch (Exception e) { System.out.println("Err in out.put"); } } responseAsString = out.toString(); } else if (statusCode != 204) { ByteArrayOutputStream out = new ByteArrayOutputStream(); response.getEntity().writeTo(out); responseAsString = out.toString("UTF-8"); out.close(); } JSONObject json = null; try { json = new JSONObject(responseAsString); } catch (Exception e) { json = new JSONObject(); } VimeoResponse vimeoResponse = new VimeoResponse(json, statusCode); response.close(); client.close(); return vimeoResponse; // } catch(IOException e) { // System.out.println("Error Building HTTP Client"); // } }
From source file:com.xively.client.http.DefaultRequestHandler.java
private <T extends DomainObject> HttpRequestBase buildRequest(HttpMethod requestMethod, String appPath, Map<String, Object> params, T... bodyObjects) { AcceptedMediaType mediaType = AppConfig.getInstance().getResponseMediaType(); HttpRequestBase request = null; switch (requestMethod) { case DELETE:/* ww w. j av a 2 s . c om*/ request = new HttpDelete(); break; case GET: request = new HttpGet(); break; case POST: request = new HttpPost(); StringEntity postEntity = getEntity(false, bodyObjects); ((HttpPost) request).setEntity(postEntity); break; case PUT: request = new HttpPut(); StringEntity putEntity = getEntity(true, bodyObjects); ((HttpPut) request).setEntity(putEntity); break; default: return null; } URIBuilder uriBuilder = buildUri(requestMethod, appPath, params, mediaType); try { request.setURI(uriBuilder.build()); } catch (URISyntaxException e) { throw new RequestInvalidException("Invalid URI requested.", e); } request.addHeader("accept", mediaType.getMediaType()); request.addHeader(HEADER_KEY_API, AppConfig.getInstance().getApiKey()); request.addHeader(HEADER_USER_AGENT, XIVELY_USER_AGENT); if (log.isDebugEnabled()) { StringBuilder sb = new StringBuilder(); for (Header header : request.getAllHeaders()) { sb.append(header.getName()).append(",").append(header.getValue()).append(";"); } log.debug(String.format("Constructed request with uri [%s], header [%s]", uriBuilder.toString(), sb.toString())); } return request; }