List of usage examples for org.apache.http.client.methods HttpUriRequest addHeader
void addHeader(Header header);
From source file:org.apache.hadoop.gateway.hive.HiveDispatchUtils.java
public static void addCredentialsToRequest(HttpUriRequest request) { String principal = SubjectUtils.getCurrentEffectivePrincipalName(); if (principal != null) { UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(principal, PASSWORD_PLACEHOLDER);/*w w w.j a v a 2s . c o m*/ request.addHeader(BasicScheme.authenticate(credentials, "US-ASCII", false)); } }
From source file:com.sayar.requests.impl.HttpClientRequestHandler.java
private static HttpUriRequest addAuthentication(final HttpUriRequest request, final HttpAuthentication auth) throws AuthenticationException { // Add authentication headers. request.addHeader(auth.getHttpHeader(request)); return request; }
From source file:com.sugarcrm.candybean.webservices.WS.java
/** * Protected method to handle sending and receiving an http request * * @param request The Http request that is being send * @param headers Map of Key Value header pairs * @return Key Value pairs of the response * @throws CandybeanException If the response is null or not an acceptable HTTP code */// www. j a v a 2 s .c o m protected static Map<String, Object> handleRequest(HttpUriRequest request, Map<String, String> headers) throws CandybeanException { // Add the request headers and execute the request for (Map.Entry<String, String> header : headers.entrySet()) { request.addHeader(new BasicHeader(header.getKey(), header.getValue())); } CloseableHttpClient httpClient = HttpClientBuilder.create().build(); try { HttpResponse response = httpClient.execute(request); // Check for invalid responses or error return codes if (response == null) { throw new CandybeanException("Http Request failed: Response null"); } // Cast the response into a Map and return JSONObject parse = (JSONObject) JSONValue .parse(new InputStreamReader(response.getEntity().getContent())); @SuppressWarnings("unchecked") Map<String, Object> mapParse = (Map<String, Object>) parse; int code = response.getStatusLine().getStatusCode(); if (!ACCEPTABLE_RETURN_CODE_SET.contains(code)) { throw new CandybeanException( "HTTP request received HTTP code: " + code + "\n" + "Response: " + response.toString()); } else if (mapParse == null) { throw new CandybeanException("Could not format response\n" + "Response: " + response.toString()); } return mapParse; } catch (IOException | IllegalStateException e) { // Cast the other possible exceptions as a CandybeanException throw new CandybeanException(e); } }
From source file:com.baidu.rigel.biplatform.ac.util.HttpRequest.java
/** * ?URL??GET/*from w ww . ja v a 2 s . com*/ * * @param client httpclient * @param url ??URL * @param param ?? name1=value1&name2=value2 ? * @return URL ?? */ public static String sendGet(HttpClient client, String url, Map<String, String> params) { if (client == null || StringUtils.isBlank(url)) { throw new IllegalArgumentException("client is null"); } if (params == null) { params = new HashMap<String, String>(1); } String newUrl = processPlaceHolder(url, params); String cookie = params.remove(COOKIE_PARAM_NAME); List<String> paramList = checkUrlAndWrapParam(newUrl, params, true); String urlNameString = ""; if (newUrl.contains("?")) { paramList.add(0, newUrl); urlNameString = StringUtils.join(paramList, "&"); } else { urlNameString = newUrl + "?" + StringUtils.join(paramList, "&"); } String prefix = "", suffix = ""; String[] addresses = new String[] { urlNameString }; if (urlNameString.contains("[") && urlNameString.contains("]")) { addresses = urlNameString.substring(urlNameString.indexOf("[") + 1, urlNameString.indexOf("]")) .split(" "); prefix = urlNameString.substring(0, urlNameString.indexOf("[")); suffix = urlNameString.substring(urlNameString.indexOf("]") + 1); } LOGGER.info("start to send get:" + urlNameString); long current = System.currentTimeMillis(); Exception ex = null; for (String address : addresses) { String requestUrl = prefix + address + suffix; try { HttpUriRequest request = RequestBuilder.get().setUri(requestUrl).build(); if (StringUtils.isNotBlank(cookie)) { // ?cookie request.addHeader(new BasicHeader(COOKIE_PARAM_NAME, cookie)); } HttpResponse response = client.execute(request); String content = processHttpResponse(client, response, params, true); LOGGER.info("end send get :" + urlNameString + " cost:" + (System.currentTimeMillis() - current)); return content; } catch (Exception e) { ex = e; LOGGER.warn("send get error " + requestUrl + ",retry next one", e); } } throw new RuntimeException(ex); }
From source file:com.mashape.client.http.HttpClient.java
public static <T> MashapeResponse<T> doRequest(Class<T> clazz, HttpMethod httpMethod, String url, Map<String, Object> parameters, ContentType contentType, ResponseType responseType, List<Authentication> authenticationHandlers) { if (authenticationHandlers == null) authenticationHandlers = new ArrayList<Authentication>(); if (parameters == null) parameters = new HashMap<String, Object>(); // Sanitize null parameters Set<String> keySet = new HashSet<String>(parameters.keySet()); for (String key : keySet) { if (parameters.get(key) == null) { parameters.remove(key);/*w w w . ja v a2 s.co m*/ } } List<Header> headers = new LinkedList<Header>(); // Handle authentications for (Authentication authentication : authenticationHandlers) { if (authentication instanceof HeaderAuthentication) { headers.addAll(authentication.getHeaders()); } else { Map<String, String> queryParameters = authentication.getQueryParameters(); if (authentication instanceof QueryAuthentication) { parameters.putAll(queryParameters); } else if (authentication instanceof OAuth10aAuthentication) { if (url.endsWith("/oauth_url") == false && (queryParameters == null || queryParameters.get(OAuthAuthentication.ACCESS_SECRET) == null || queryParameters.get(OAuthAuthentication.ACCESS_TOKEN) == null)) { throw new RuntimeException( "Before consuming OAuth endpoint, invoke authorize('access_token','access_secret') with not null values"); } headers.add(new BasicHeader("x-mashape-oauth-consumerkey", queryParameters.get(OAuthAuthentication.CONSUMER_KEY))); headers.add(new BasicHeader("x-mashape-oauth-consumersecret", queryParameters.get(OAuthAuthentication.CONSUMER_SECRET))); headers.add(new BasicHeader("x-mashape-oauth-accesstoken", queryParameters.get(OAuthAuthentication.ACCESS_TOKEN))); headers.add(new BasicHeader("x-mashape-oauth-accesssecret", queryParameters.get(OAuthAuthentication.ACCESS_SECRET))); } else if (authentication instanceof OAuth2Authentication) { if (url.endsWith("/oauth_url") == false && (queryParameters == null || queryParameters.get(OAuthAuthentication.ACCESS_TOKEN) == null)) { throw new RuntimeException( "Before consuming OAuth endpoint, invoke authorize('access_token') with a not null value"); } parameters.put("access_token", queryParameters.get(OAuthAuthentication.ACCESS_TOKEN)); } } } headers.add(new BasicHeader("User-Agent", USER_AGENT)); HttpUriRequest request = null; switch (httpMethod) { case GET: request = new HttpGet(url + "?" + HttpUtils.getQueryString(parameters)); break; case POST: request = new HttpPost(url); break; case PUT: request = new HttpPut(url); break; case DELETE: request = new HttpDeleteWithBody(url); break; } for (Header header : headers) { request.addHeader(header); } if (httpMethod != HttpMethod.GET) { switch (contentType) { case BINARY: MultipartEntity entity = new MultipartEntity(); for (Entry<String, Object> parameter : parameters.entrySet()) { if (parameter.getValue() instanceof File) { entity.addPart(parameter.getKey(), new FileBody((File) parameter.getValue())); } else { try { entity.addPart(parameter.getKey(), new StringBody(parameter.getValue().toString(), Charset.forName("UTF-8"))); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } } ((HttpEntityEnclosingRequestBase) request).setEntity(entity); break; case FORM: try { ((HttpEntityEnclosingRequestBase) request) .setEntity(new UrlEncodedFormEntity(MapUtil.getList(parameters), HTTP.UTF_8)); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } break; case JSON: throw new RuntimeException("Not supported content type: JSON"); } } org.apache.http.client.HttpClient client = new DefaultHttpClient(); try { HttpResponse response = client.execute(request); MashapeResponse<T> mashapeResponse = HttpUtils.getResponse(responseType, response); return mashapeResponse; } catch (Exception e) { throw new RuntimeException(e); } }
From source file:com.baidu.rigel.biplatform.ac.util.HttpRequest.java
/** * ?URL??POST/*from w w w .j a v a 2 s .co m*/ * * @param client httpclient * @param url ??URL * @param param ?? name1=value1&name2=value2 ? * @return URL ?? */ public static String sendPost(HttpClient client, String url, Map<String, String> params) { if (client == null) { throw new IllegalArgumentException("client is null"); } if (params == null) { params = new HashMap<String, String>(1); } String requestUrl = processPlaceHolder(url, params); String cookie = params.remove(COOKIE_PARAM_NAME); if (requestUrl.contains("?")) { String[] urls = requestUrl.split("?"); requestUrl = urls[0]; String[] urlParams = urls[1].split("&"); for (String param : urlParams) { String[] paramSplit = param.split("="); params.put(paramSplit[0], paramSplit[1]); } } List<NameValuePair> nameValues = new ArrayList<NameValuePair>(); params.forEach((k, v) -> { NameValuePair nameValuePair = new BasicNameValuePair(k, v); nameValues.add(nameValuePair); }); String prefix = "", suffix = ""; String[] addresses = new String[] { requestUrl }; if (requestUrl.contains("[") && requestUrl.contains("]")) { addresses = requestUrl.substring(requestUrl.indexOf("[") + 1, requestUrl.indexOf("]")).split(" "); prefix = requestUrl.substring(0, requestUrl.indexOf("[")); suffix = requestUrl.substring(requestUrl.indexOf("]") + 1); } LOGGER.info("start to send post:" + requestUrl); long current = System.currentTimeMillis(); for (String address : addresses) { String postUrl = prefix + address + suffix; LOGGER.info("post url is : " + postUrl); try { HttpUriRequest request = RequestBuilder.post().setUri(postUrl) // .addParameters(nameValues.toArray(new NameValuePair[0])) .setEntity(new UrlEncodedFormEntity(nameValues, "utf-8")).build(); if (StringUtils.isNotBlank(cookie)) { // ?cookie request.addHeader(new BasicHeader(COOKIE_PARAM_NAME, cookie)); } // client. HttpResponse response = client.execute(request); String content = processHttpResponse(client, response, params, false); StringBuilder sb = new StringBuilder(); sb.append("end send post :").append(postUrl).append(" params:").append(nameValues).append(" cost:") .append(System.currentTimeMillis() - current); LOGGER.info(sb.toString()); return content; } catch (Exception e) { LOGGER.warn("send post error " + requestUrl + ",retry next one", e); } } throw new RuntimeException("send post failed[" + requestUrl + "]. params :" + nameValues); }
From source file:com.amalto.workbench.utils.HttpClientUtil.java
private static void authenticate(String username, String password, HttpUriRequest request, HttpContext preemptiveContext) { try {// w w w . j a v a 2 s . c o m BasicScheme basicScheme = new BasicScheme(); Header authenticateHeader = basicScheme .authenticate(new UsernamePasswordCredentials(username, password), request, preemptiveContext); request.addHeader(authenticateHeader); } catch (AuthenticationException e) { log.error(e.getMessage(), e); } }
From source file:com.betfair.cougar.client.HttpClientCougarRequestFactory.java
@Override protected void addHeaders(HttpUriRequest httpRequest, List<Header> headers) { for (Header header : headers) { if (header.getValue() != null) { httpRequest.addHeader(header); }//from w ww . ja v a 2 s . c o m } }
From source file:ch.entwine.weblounge.common.impl.util.TestUtils.java
/** * Issues the the given request./*from ww w. j av a2 s .c om*/ * * @param httpClient * the http client * @param request * the request * @param params * the request parameters * @throws Exception * if the request fails */ public static HttpResponse request(HttpClient httpClient, HttpUriRequest request, String[][] params) throws Exception { if (params != null) { if (request instanceof HttpGet) { List<NameValuePair> qparams = new ArrayList<NameValuePair>(); if (params.length > 0) { for (String[] param : params) { if (param.length < 2) continue; qparams.add(new BasicNameValuePair(param[0], param[1])); } } URI requestURI = request.getURI(); URI uri = URIUtils.createURI(requestURI.getScheme(), requestURI.getHost(), requestURI.getPort(), requestURI.getPath(), URLEncodedUtils.format(qparams, "utf-8"), null); HeaderIterator headerIterator = request.headerIterator(); request = new HttpGet(uri); while (headerIterator.hasNext()) { request.addHeader(headerIterator.nextHeader()); } } else if (request instanceof HttpPost) { List<NameValuePair> formparams = new ArrayList<NameValuePair>(); for (String[] param : params) formparams.add(new BasicNameValuePair(param[0], param[1])); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "utf-8"); ((HttpPost) request).setEntity(entity); } else if (request instanceof HttpPut) { List<NameValuePair> formparams = new ArrayList<NameValuePair>(); for (String[] param : params) formparams.add(new BasicNameValuePair(param[0], param[1])); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "utf-8"); ((HttpPut) request).setEntity(entity); } } else { if (request instanceof HttpPost || request instanceof HttpPut) { UrlEncodedFormEntity entity = new UrlEncodedFormEntity(new ArrayList<NameValuePair>(), "utf-8"); ((HttpEntityEnclosingRequestBase) request).setEntity(entity); } } return httpClient.execute(request); }
From source file:org.wso2.am.integration.tests.other.RelativeUrlLocationHeaderTestCase.java
@Test(groups = "wso2.am", description = "Check functionality of the API for relative URL location header") public void testAPIWithRelativeUrlLocationHeader() throws Exception { //Login to the API Publisher HttpResponse response;/*ww w . j av a 2s . c o m*/ response = apiPublisher.login(user.getUserName(), user.getPassword()); verifyResponse(response); String apiName = "RelativeUrlLocationHeaderAPI"; String apiVersion = "1.0.0"; String apiContext = "relative"; String endpointUrl = getAPIInvocationURLHttp("response") + "/1.0.0"; String appName = "RelativeLocHeaderAPP"; //Create the api creation request object APIRequest apiRequest; apiRequest = new APIRequest(apiName, apiContext, new URL(endpointUrl)); apiRequest.setVersion(apiVersion); apiRequest.setTiersCollection(APIMIntegrationConstants.API_TIER.UNLIMITED); apiRequest.setTier(APIMIntegrationConstants.API_TIER.UNLIMITED); //Add the API using the API publisher. response = apiPublisher.addAPI(apiRequest); verifyResponse(response); APILifeCycleStateRequest updateRequest = new APILifeCycleStateRequest(apiName, user.getUserName(), APILifeCycleState.PUBLISHED); //Publish the API response = apiPublisher.changeAPILifeCycleStatus(updateRequest); waitForAPIDeploymentSync(updateRequest.getProvider(), updateRequest.getName(), updateRequest.getVersion(), APIMIntegrationConstants.IS_API_EXISTS); verifyResponse(response); //Login to the API Store response = apiStore.login(user.getUserName(), user.getPassword()); verifyResponse(response); //Add an Application in the Store. response = apiStore.addApplication(appName, APIMIntegrationConstants.APPLICATION_TIER.UNLIMITED, "", ""); verifyResponse(response); //Subscribe the API to the DefaultApplication SubscriptionRequest subscriptionRequest = new SubscriptionRequest(apiName, apiVersion, user.getUserName(), appName, APIMIntegrationConstants.API_TIER.UNLIMITED); response = apiStore.subscribe(subscriptionRequest); verifyResponse(response); //Generate production token and invoke with that APPKeyRequestGenerator generateAppKeyRequest = new APPKeyRequestGenerator(appName); String responseString = apiStore.generateApplicationKey(generateAppKeyRequest).getData(); JSONObject responseProduction = new JSONObject(responseString); //Get the accessToken which was generated. String accessToken = responseProduction.getJSONObject("data").getJSONObject("key").getString("accessToken"); assertEquals(accessToken.isEmpty(), false, "Production access token is Empty"); //Going to access the API with the version in the request url. String apiInvocationUrl = getAPIInvocationURLHttp(apiContext, apiVersion); HttpClient httpclient = new DefaultHttpClient(); HttpUriRequest get = new HttpGet(apiInvocationUrl); get.addHeader(new BasicHeader("Authorization", "Bearer " + accessToken)); org.apache.http.HttpResponse httpResponse = httpclient.execute(get); assertEquals(httpResponse.getStatusLine().getStatusCode(), 201, "Response Code Mismatched"); }