List of usage examples for org.apache.http.client.methods HttpRequestBase setHeader
public void setHeader(String str, String str2)
From source file:org.bigmouth.nvwa.network.http.HttpClientHelper.java
private static void setRequestBaseHeader(HttpRequestBase httpRequest) { httpRequest.setHeader("Connection", "keep-alive"); httpRequest.setHeader("Proxy-Connection", "keep-alive"); httpRequest.setHeader("Accept", "*/*"); httpRequest.setHeader("Accept-Encoding", "gzip,deflate,sdch"); httpRequest.setHeader("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6"); }
From source file:org.dasein.cloud.digitalocean.models.rest.DigitalOceanModelFactory.java
/** * Sent http request to the server/* w w w . ja v a 2 s .c o m*/ * @return Http response * @throws CloudException */ private static HttpResponse sendRequest(org.dasein.cloud.digitalocean.DigitalOcean provider, RESTMethod method, String token, String strUrl, DigitalOceanAction action) throws CloudException, InternalException { HttpRequestBase req = null; if (method == RESTMethod.GET) { req = new HttpGet(strUrl); } else if (method == RESTMethod.POST) { req = new HttpPost(strUrl); } else if (method == RESTMethod.PUT) { req = new HttpPut(strUrl); } else if (method == RESTMethod.DELETE) { req = new HttpDelete(strUrl); } else if (method == RESTMethod.HEAD) { req = new HttpHead(strUrl); } try { req.setHeader("Authorization", "Bearer " + token); req.setHeader("Accept", "application/json"); req.setHeader("Content-Type", "application/json;charset=UTF-8"); StringEntity requestEntity = null; if (req instanceof HttpEntityEnclosingRequestBase && action != null) { JSONObject jsonToPost = action.getParameters(); if (jsonToPost != null) { requestEntity = new StringEntity(jsonToPost.toString(), ContentType.APPLICATION_JSON); ((HttpEntityEnclosingRequestBase) req).setEntity(requestEntity); } } HttpClient httpClient = provider.getClient(); if (wire.isDebugEnabled()) { wire.debug(""); wire.debug( "--------------------------------------------------------------------------------------"); } if (wire.isDebugEnabled()) { wire.debug(req.getRequestLine().toString()); for (Header header : req.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); if (requestEntity != null) { try { wire.debug(EntityUtils.toString(requestEntity)); wire.debug(""); } catch (IOException ignore) { } } } HttpResponse response = null; int retryCount = 0; while (retryCount < 6) { response = httpClient.execute(req); if (wire.isDebugEnabled()) { wire.debug(response.getStatusLine().toString()); } if (method == RESTMethod.DELETE) { if ((response.getStatusLine().getStatusCode() == 204)) { break; } else { retryCount++; Thread.sleep(5000); } } else { break; } } if (method == RESTMethod.DELETE && (response.getStatusLine().getStatusCode() != 204)) { //Error occurred throw new CloudException("Delete method returned unexpected code, despite retrying."); } return response; } catch (JSONException e) { throw new CloudException("Problem sending request.", e); } catch (InterruptedException e) { throw new CloudException("Problem sending request.", e); } catch (ClientProtocolException e) { throw new CloudException("Problem sending request.", e); } catch (IOException e) { throw new CloudException("Problem sending request.", e); } finally { try { // req.releaseConnection(); } catch (Exception e) { } } }
From source file:org.opencastproject.kernel.security.TrustedHttpClientImpl.java
/** * Handles the necessary handshake for digest authenticaion in the case where it isn't a GET operation. * //from w ww .ja v a2 s. c o m * @param httpUriRequest * The request location to get the digest authentication for. * @param httpClient * The client to send the request through. * @throws TrustedHttpClientException * Thrown if the client cannot be shutdown. */ private void manuallyHandleDigestAuthentication(HttpUriRequest httpUriRequest, HttpClient httpClient) throws TrustedHttpClientException { HttpRequestBase digestRequest; try { digestRequest = (HttpRequestBase) httpUriRequest.getClass().newInstance(); } catch (Exception e) { throw new IllegalStateException("Can not create a new " + httpUriRequest.getClass().getName()); } digestRequest.setURI(httpUriRequest.getURI()); digestRequest.setHeader(REQUESTED_AUTH_HEADER, DIGEST_AUTH); String[] realmAndNonce = getRealmAndNonce(digestRequest); if (realmAndNonce != null) { // Set the user/pass UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, pass); // Set up the digest authentication with the required values DigestScheme digestAuth = new DigestScheme(); digestAuth.overrideParamter("realm", realmAndNonce[0]); digestAuth.overrideParamter("nonce", realmAndNonce[1]); // Add the authentication header try { httpUriRequest.setHeader(digestAuth.authenticate(creds, httpUriRequest)); } catch (Exception e) { // close the http connection(s) httpClient.getConnectionManager().shutdown(); throw new TrustedHttpClientException(e); } } }
From source file:org.opennms.netmgt.collectd.HttpCollector.java
private static HttpRequestBase buildHttpMethod(final HttpCollectionSet collectionSet) throws URISyntaxException { HttpRequestBase method; URI uri = buildUri(collectionSet); if ("GET".equals(collectionSet.getUriDef().getUrl().getMethod())) { method = buildGetMethod(uri, collectionSet); } else {/* ww w . j av a2s . c om*/ method = buildPostMethod(uri, collectionSet); } final String virtualHost = collectionSet.getUriDef().getUrl().getVirtualHost(); if (virtualHost != null && !virtualHost.trim().isEmpty()) { method.setHeader(HTTP.TARGET_HOST, virtualHost); } return method; }
From source file:ru.histone.resourceloaders.DefaultResourceLoader.java
private StreamResource loadHttpResource(URI location, Node[] args) { URI newLocation = URI.create(location.toString().replace("#fragment", "")); final Map<Object, Node> requestMap = args != null && args.length != 0 && args[0] instanceof ObjectHistoneNode ? ((ObjectHistoneNode) args[0]).getElements() : new HashMap<Object, Node>(); Node methodNode = requestMap.get("method"); final String method = methodNode != null && methodNode.isString() && methodNode.getAsString().getValue().length() != 0 ? requestMap.get("method").getAsString().getValue() : "GET"; final Map<String, String> headers = new HashMap<String, String>(); if (requestMap.containsKey("headers")) { for (Map.Entry<Object, Node> en : requestMap.get("headers").getAsObject().getElements().entrySet()) { String value = null;/* w w w.j a v a2 s. c o m*/ if (en.getValue().isUndefined()) value = "undefined"; else value = en.getValue().getAsString().getValue(); headers.put(en.getKey().toString(), value); } } final Map<String, String> filteredHeaders = filterRequestHeaders(headers); final Node data = requestMap.containsKey("data") ? (Node) requestMap.get("data") : null; // Prepare request HttpRequestBase request = new HttpGet(newLocation); if ("POST".equalsIgnoreCase(method)) { request = new HttpPost(newLocation); } else if ("PUT".equalsIgnoreCase(method)) { request = new HttpPut(newLocation); } else if ("DELETE".equalsIgnoreCase(method)) { request = new HttpDelete(newLocation); } else if ("TRACE".equalsIgnoreCase(method)) { request = new HttpTrace(newLocation); } else if ("OPTIONS".equalsIgnoreCase(method)) { request = new HttpOptions(newLocation); } else if ("PATCH".equalsIgnoreCase(method)) { request = new HttpPatch(newLocation); } else if ("HEAD".equalsIgnoreCase(method)) { request = new HttpHead(newLocation); } else if (method != null && !"GET".equalsIgnoreCase(method)) { return new StreamResource(null, location.toString(), ContentType.TEXT); } for (Map.Entry<String, String> en : filteredHeaders.entrySet()) { request.setHeader(en.getKey(), en.getValue()); } if (("POST".equalsIgnoreCase(method) || "PUT".equalsIgnoreCase(method)) && data != null) { String stringData = null; String contentType = filteredHeaders.get("content-type") == null ? "" : filteredHeaders.get("content-type"); if (data.isObject()) { stringData = ToQueryString.toQueryString(data.getAsObject(), null, "&"); contentType = "application/x-www-form-urlencoded"; } else { stringData = data.getAsString().getValue(); } if (stringData != null) { StringEntity se; try { se = new StringEntity(stringData); } catch (UnsupportedEncodingException e) { throw new ResourceLoadException(String.format("Can't encode data '%s'", stringData)); } ((HttpEntityEnclosingRequestBase) request).setEntity(se); } request.setHeader("Content-Type", contentType); } if (request.getHeaders("content-Type").length == 0) { request.setHeader("Content-Type", ""); } // Execute request HttpClient client = new DefaultHttpClient(httpClientConnectionManager); ((AbstractHttpClient) client).setRedirectStrategy(new RedirectStrategy()); InputStream input = null; try { HttpResponse response = client.execute(request); input = response.getEntity() == null ? null : response.getEntity().getContent(); } catch (IOException e) { throw new ResourceLoadException(String.format("Can't load resource '%s'", location.toString())); } finally { } return new StreamResource(input, location.toString(), ContentType.TEXT); }
From source file:st.geekli.api.GeeklistApi.java
private Object internalDoRequest(String url, HashMap<String, Object> params, HttpMethod method, boolean sign) throws GeeklistApiException { HttpRequestBase request = null; GeeklistApi.debugOut("Request", method.toString() + " " + url + " " + params.toString() + " | sign=" + sign); switch (method) { case GET:/*from w ww .ja va2 s.c o m*/ StringBuilder sb = new StringBuilder(); sb.append(url); if (params.size() > 0) { sb.append("?"); for (Iterator<Map.Entry<String, Object>> i = params.entrySet().iterator(); i.hasNext();) { Map.Entry<String, Object> param = i.next(); try { sb.append(param.getKey()); sb.append('='); sb.append(URLEncoder.encode(param.getValue().toString(), "UTF-8")); if (i.hasNext()) sb.append('&'); } catch (UnsupportedEncodingException e) { throw new GeeklistApiException(e); } } } request = new HttpGet(sb.toString()); break; case POST: request = new HttpPost(url); request.setHeader("Content-Type", "application/x-www-form-urlencoded"); ArrayList<BasicNameValuePair> postParams = new ArrayList<BasicNameValuePair>(); if (params.size() > 0) { for (Map.Entry<String, Object> param : params.entrySet()) { postParams.add(new BasicNameValuePair(param.getKey(), param.getValue().toString())); } } UrlEncodedFormEntity urlEncodedFormEntity; try { urlEncodedFormEntity = new UrlEncodedFormEntity(postParams); urlEncodedFormEntity.setContentEncoding(HTTP.UTF_8); ((HttpPost) request).setEntity(urlEncodedFormEntity); } catch (UnsupportedEncodingException e2) { throw new GeeklistApiException(e2); } break; } request.setHeader("User-Agent", mUserAgent); request.setHeader("Accept-Charset", "UTF-8"); if (sign) { try { mOAuthConsumer.sign(request); } catch (OAuthMessageSignerException e1) { throw new GeeklistApiException(e1); } catch (OAuthExpectationFailedException e1) { throw new GeeklistApiException(e1); } catch (OAuthCommunicationException e1) { throw new GeeklistApiException(e1); } } try { HttpResponse response = mClient.execute(request); GeeklistApi.debugOut("Response-Code", Integer.toString(response.getStatusLine().getStatusCode())); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK || response.getStatusLine().getStatusCode() == HttpStatus.SC_FORBIDDEN || response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { JSONObject responseObject = new JSONObject( Utils.inputStreamToString(response.getEntity().getContent())); if (responseObject.optString("status").equals("ok")) { JSONObject obj = responseObject.optJSONObject("data"); if (obj != null) { return obj; } else { return responseObject.optJSONArray("data"); } } else { throw new GeeklistApiException(responseObject.optString("error")); } } else { GeeklistApi.debugOut("Failed body length", "" + response.getEntity().getContentLength()); response.getEntity().consumeContent(); throw new GeeklistApiException(response.getStatusLine().getReasonPhrase()); } } catch (ClientProtocolException e) { throw new GeeklistApiException(e); } catch (IOException e) { throw new GeeklistApiException(e); } catch (IllegalStateException e) { throw new GeeklistApiException(e); } catch (JSONException e) { throw new GeeklistApiException(e); } }