List of usage examples for org.apache.http.client.methods HttpRequestBase getFirstHeader
public Header getFirstHeader(String str)
From source file:com.gsma.mobileconnect.impl.CompleteSelectedOperatorDiscoveryTest.java
@Test public void completeSelectedOperatorDiscovery_withDefaults_shouldCreateExpectedRequest() throws DiscoveryException, RestException, IOException { // GIVEN//from w ww . j ava 2 s . c o m RestClient mockedRestClient = mock(RestClient.class); CaptureDiscoveryResponse captureDiscoveryResponse = new CaptureDiscoveryResponse(); Config config = new Config(); String exampleJson = buildJsonStr(); JsonNode expectedJsonObject = buildJsonObject(); final RestResponse restResponse = new RestResponse(null, 0, null, exampleJson); String expectedAccept = "application/json"; String expectedURL = "http://discovery.sandbox.mobileconnect.io/v2/discovery?Redirect_URL=http%3A%2F%2Flocalhost%2F&Selected-MCC=MCC&Selected-MNC=MNC"; final CaptureHttpRequestBase captureHttpRequestBase = new CaptureHttpRequestBase(); doAnswer(new Answer() { public Object answer(InvocationOnMock invocationOnMock) throws Throwable { Object[] args = invocationOnMock.getArguments(); HttpRequestBase requestBase = (HttpRequestBase) args[0]; captureHttpRequestBase.setValue(requestBase); return restResponse; } }).when(mockedRestClient).callRestEndPoint(any(HttpRequestBase.class), any(HttpClientContext.class), eq(30000), Matchers.<List<KeyValuePair>>any()); IDiscovery discovery = Factory.getDiscovery(null, mockedRestClient); // WHEN discovery.completeSelectedOperatorDiscovery(config, null, SELECTED_MCC, SELECTED_MNC, null, null, captureDiscoveryResponse); // THEN DiscoveryResponse discoveryResponse = captureDiscoveryResponse.getDiscoveryResponse(); assertEquals(expectedJsonObject, discoveryResponse.getResponseData()); HttpRequestBase capturedRequest = captureHttpRequestBase.getValue(); assertEquals(expectedURL, capturedRequest.getURI().toString()); assertEquals(expectedAccept, capturedRequest.getFirstHeader("accept").getValue()); }
From source file:com.gsma.mobileconnect.impl.CompleteSelectedOperatorDiscoveryTest.java
@Test public void completeSelectedOperatorDiscovery_withAllOptionsSet_shouldCreateExpectedRequest() throws DiscoveryException, RestException, IOException { // GIVEN// w w w . j av a 2 s . co m RestClient mockedRestClient = mock(RestClient.class); CaptureDiscoveryResponse captureDiscoveryResponse = new CaptureDiscoveryResponse(); Config config = new Config(); String exampleJson = buildJsonStr(); JsonNode expectedJsonObject = buildJsonObject(); final RestResponse restResponse = new RestResponse(null, 0, null, exampleJson); CompleteSelectedOperatorDiscoveryOptions options = new CompleteSelectedOperatorDiscoveryOptions(); options.setTimeout(333); String expectedAccept = "application/json"; String expectedURL = "http://discovery.sandbox.mobileconnect.io/v2/discovery?Redirect_URL=http%3A%2F%2Flocalhost%3A8080%2Fmobileconnect&Selected-MCC=MCC&Selected-MNC=MNC"; final CaptureHttpRequestBase captureHttpRequestBase = new CaptureHttpRequestBase(); doAnswer(new Answer() { public Object answer(InvocationOnMock invocationOnMock) throws Throwable { Object[] args = invocationOnMock.getArguments(); HttpRequestBase requestBase = (HttpRequestBase) args[0]; captureHttpRequestBase.setValue(requestBase); return restResponse; } }).when(mockedRestClient).callRestEndPoint(any(HttpRequestBase.class), any(HttpClientContext.class), eq(options.getTimeout()), Matchers.<List<KeyValuePair>>any()); IDiscovery discovery = Factory.getDiscovery(null, mockedRestClient); // WHEN discovery.completeSelectedOperatorDiscovery(config, Config.REDIRECT_URL, SELECTED_MCC, SELECTED_MNC, options, null, captureDiscoveryResponse); // THEN DiscoveryResponse discoveryResponse = captureDiscoveryResponse.getDiscoveryResponse(); assertEquals(expectedJsonObject, discoveryResponse.getResponseData()); HttpRequestBase capturedRequest = captureHttpRequestBase.getValue(); assertEquals(expectedURL, capturedRequest.getURI().toString()); assertEquals(expectedAccept, capturedRequest.getFirstHeader("accept").getValue()); }
From source file:com.gsma.mobileconnect.impl.StartAutomatedOperatorDiscoveryTest.java
@Test public void startAutomatedOperatorDiscovery_withAllOptionsSet_shouldCreateExpectedRequest() throws DiscoveryException, RestException, IOException { // GIVEN//from www. j a v a 2s. c o m RestClient mockedRestClient = mock(RestClient.class); CaptureDiscoveryResponse captureDiscoveryResponse = new CaptureDiscoveryResponse(); Config config = new Config(); String exampleJson = buildJsonStr(); JsonNode expectedJsonObject = buildJsonObject(); final RestResponse restResponse = new RestResponse(null, 0, null, exampleJson); DiscoveryOptions options = new DiscoveryOptions(); options.setUsingMobileData(false); options.setManuallySelect(true); options.setLocalClientIP("127.0.0.1"); options.setIdentifiedMCC("901"); options.setIdentifiedMNC("01"); options.setTimeout(333); String expectedClientIP = "10.0.0.1"; options.setClientIP(expectedClientIP); String expectedAccept = "application/json"; String expectedURL = "http://discovery.sandbox.mobileconnect.io/v2/discovery?Manually-Select=true&Identified-MCC=901&Identified-MNC=01&Using-Mobile-Data=false&Local-Client-IP=127.0.0.1&Redirect_URL=http%3A%2F%2Flocalhost%3A8080%2Fmobileconnect"; final CaptureHttpRequestBase captureHttpRequestBase = new CaptureHttpRequestBase(); doAnswer(new Answer() { public Object answer(InvocationOnMock invocationOnMock) throws Throwable { Object[] args = invocationOnMock.getArguments(); HttpRequestBase requestBase = (HttpRequestBase) args[0]; captureHttpRequestBase.setValue(requestBase); return restResponse; } }).when(mockedRestClient).callRestEndPoint(any(HttpRequestBase.class), any(HttpClientContext.class), eq(options.getTimeout()), Matchers.<List<KeyValuePair>>any()); IDiscovery discovery = Factory.getDiscovery(null, mockedRestClient); // WHEN discovery.startAutomatedOperatorDiscovery(config, Config.REDIRECT_URL, options, null, captureDiscoveryResponse); // THEN DiscoveryResponse discoveryResponse = captureDiscoveryResponse.getDiscoveryResponse(); assertEquals(expectedJsonObject, discoveryResponse.getResponseData()); HttpRequestBase capturedRequest = captureHttpRequestBase.getValue(); assertEquals(expectedURL, capturedRequest.getURI().toString()); assertEquals(expectedClientIP, capturedRequest.getFirstHeader("X-Source-IP").getValue()); assertEquals(expectedAccept, capturedRequest.getFirstHeader("accept").getValue()); }
From source file:com.gsma.mobileconnect.impl.RequestTokenTest.java
@Test public void requestToken_withDefaults_shouldCreateExpectedRequest() throws OIDCException, DiscoveryResponseExpiredException, IOException, RestException { // GIVEN/*from w w w . jav a 2s .c o m*/ RestClient mockedRestClient = mock(RestClient.class); IOIDC ioidc = Factory.getOIDC(mockedRestClient); CaptureRequestTokenResponse captureRequestTokenResponse = new CaptureRequestTokenResponse(); DiscoveryResponse discoveryResponse = new DiscoveryResponse(true, new Date(Long.MAX_VALUE), 0, null, parseJson(OPERATOR_JSON_STRING)); final CaptureHttpRequestBase captureHttpRequestBase = new CaptureHttpRequestBase(); final RestResponse restResponse = new RestResponse(null, 0, null, "{}"); doAnswer(new Answer() { public Object answer(InvocationOnMock invocationOnMock) throws Throwable { Object[] args = invocationOnMock.getArguments(); HttpRequestBase requestBase = (HttpRequestBase) args[0]; captureHttpRequestBase.setValue(requestBase); return restResponse; } }).when(mockedRestClient).callRestEndPoint(any(HttpRequestBase.class), any(HttpClientContext.class), eq(30000), Matchers.<List<KeyValuePair>>any()); // WHEN ioidc.requestToken(discoveryResponse, "", "", null, captureRequestTokenResponse); // THEN HttpRequestBase request = captureHttpRequestBase.getValue(); assertEquals(TOKEN_HREF, request.getURI().toString()); assertEquals("POST", request.getMethod()); assertEquals("application/x-www-form-urlencoded", request.getFirstHeader("Content-Type").getValue()); assertEquals("application/json", request.getFirstHeader("accept").getValue()); assertTrue(request instanceof HttpPost); HttpPost postRequest = (HttpPost) request; List<NameValuePair> contents = URLEncodedUtils.parse(postRequest.getEntity()); assertEquals("", findValueOfName(contents, "code")); assertEquals("authorization_code", findValueOfName(contents, "grant_type")); assertEquals("", findValueOfName(contents, "redirect_uri")); }
From source file:com.gsma.mobileconnect.impl.RequestTokenTest.java
@Test public void requestToken_withAllOptionsSet_shouldCreateExpectedRequest() throws OIDCException, DiscoveryResponseExpiredException, IOException, RestException { // GIVEN/*w w w . j av a 2 s . c o m*/ RestClient mockedRestClient = mock(RestClient.class); IOIDC ioidc = Factory.getOIDC(mockedRestClient); CaptureRequestTokenResponse captureRequestTokenResponse = new CaptureRequestTokenResponse(); DiscoveryResponse discoveryResponse = new DiscoveryResponse(true, new Date(Long.MAX_VALUE), 0, null, parseJson(OPERATOR_JSON_STRING)); TokenOptions options = new TokenOptions(); options.setTimeout(333); final CaptureHttpRequestBase captureHttpRequestBase = new CaptureHttpRequestBase(); final RestResponse restResponse = new RestResponse(null, 0, null, "{}"); doAnswer(new Answer() { public Object answer(InvocationOnMock invocationOnMock) throws Throwable { Object[] args = invocationOnMock.getArguments(); HttpRequestBase requestBase = (HttpRequestBase) args[0]; captureHttpRequestBase.setValue(requestBase); return restResponse; } }).when(mockedRestClient).callRestEndPoint(any(HttpRequestBase.class), any(HttpClientContext.class), eq(options.getTimeout()), Matchers.<List<KeyValuePair>>any()); String expectedRedirectURI = "expected-redirect-uri"; String expectedCode = "expected-code"; // WHEN ioidc.requestToken(discoveryResponse, expectedRedirectURI, expectedCode, options, captureRequestTokenResponse); // THEN HttpRequestBase request = captureHttpRequestBase.getValue(); assertEquals(TOKEN_HREF, request.getURI().toString()); assertEquals("POST", request.getMethod()); assertEquals("application/x-www-form-urlencoded", request.getFirstHeader("Content-Type").getValue()); assertEquals("application/json", request.getFirstHeader("accept").getValue()); assertTrue(request instanceof HttpPost); HttpPost postRequest = (HttpPost) request; List<NameValuePair> contents = URLEncodedUtils.parse(postRequest.getEntity()); assertEquals(expectedCode, findValueOfName(contents, "code")); assertEquals("authorization_code", findValueOfName(contents, "grant_type")); assertEquals(expectedRedirectURI, findValueOfName(contents, "redirect_uri")); }
From source file:com.serphacker.serposcope.scraper.http.ScrapClient.java
protected void initializeRequest(HttpRequestBase request, HttpClientContext context) { if (request.getFirstHeader("user-agent") == null) { request.setHeader("User-Agent", useragent); }/*w w w .j a va 2 s .c om*/ for (Header requestHeader : requestHeaders) { request.setHeader(requestHeader); } RequestConfig.Builder configBuilder = RequestConfig .copy(request.getConfig() == null ? RequestConfig.DEFAULT : request.getConfig()); if (timeoutMS != null) { configBuilder.setConnectTimeout(timeoutMS); configBuilder.setConnectionRequestTimeout(timeoutMS); configBuilder.setSocketTimeout(timeoutMS); } if (maxRedirect == 0) { configBuilder.setRedirectsEnabled(false); } else { configBuilder.setMaxRedirects(maxRedirect); } RequestConfig config = configBuilder.build(); context.setAttribute(HttpClientContext.REQUEST_CONFIG, config); request.setConfig(config); }
From source file:mobi.jenkinsci.ci.client.JenkinsHttpClient.java
public HttpResponse execute(final HttpRequestBase req) throws IOException { LOG.debug("Executing '" + req.getMethod() + " " + req.getURI() + "'"); if (!(httpClient instanceof JenkinsFormAuthHttpClient) && config.getUsername() != null && config.getUsername().trim().length() > 0) { ensurePreemptiveAuthRequest(req); }/*from www . j a v a 2s .c o m*/ HttpResponse response = httpContext == null ? httpClient.execute(req) : httpClient.execute(req, httpContext); if (response == null) { throw new IOException("Cannot contact URL " + req.getURI()); } final int responseStatus = response.getStatusLine().getStatusCode(); if ((responseStatus == HttpURLConnection.HTTP_UNAUTHORIZED || responseStatus == HttpURLConnection.HTTP_FORBIDDEN)) { req.releaseConnection(); httpClient = new JenkinsFormAuthHttpClient(httpClientFactory.getHttpClient(), config.getUrl(), config.getUsername(), config.getPassword(), req.getFirstHeader(Constants.X_AUTH_OTP_HEADER) != null ? req.getFirstHeader(Constants.X_AUTH_OTP_HEADER).getValue() : null); response = httpClient.execute(req); httpContext = null; } return elaborateResponse(response); }
From source file:org.dasein.cloud.azure.AzureStorageMethod.java
private String calculatedSharedKeyLiteSignature(@Nonnull HttpRequestBase method, @Nonnull Map<String, String> queryParams) throws CloudException, InternalException { fetchKeys();/*w ww .j av a 2 s .c o m*/ ProviderContext ctx = provider.getContext(); if (ctx == null) { throw new AzureConfigException("No context was specified for this request"); } Header h = method.getFirstHeader("content-type"); String contentType = (h == null ? null : h.getValue()); if (contentType == null) { contentType = ""; } StringBuilder stringToSign = new StringBuilder(); stringToSign.append(method.getMethod().toUpperCase()).append("\n"); stringToSign.append("\n"); // content-md5 stringToSign.append(contentType).append("\n"); stringToSign.append(method.getFirstHeader("date").getValue()).append("\n"); Header[] headers = method.getAllHeaders(); TreeSet<String> keys = new TreeSet<String>(); for (Header header : headers) { if (header.getName().startsWith(Header_Prefix_MS)) { keys.add(header.getName().toLowerCase()); } } for (String key : keys) { Header header = method.getFirstHeader(key); if (header != null) { Header[] all = method.getHeaders(key); stringToSign.append(key.toLowerCase().trim()).append(":"); if (all != null && all.length > 0) { for (Header current : all) { String v = (current.getValue() != null ? current.getValue() : ""); stringToSign.append(v.trim().replaceAll("\n", " ")).append(","); } } stringToSign.deleteCharAt(stringToSign.lastIndexOf(",")); } else { stringToSign.append(key.toLowerCase().trim()).append(":"); } stringToSign.append("\n"); } stringToSign.append("/").append(getStorageAccount()).append(method.getURI().getPath()); keys.clear(); for (String key : queryParams.keySet()) { if (key.equalsIgnoreCase("comp")) { key = key.toLowerCase(); keys.add(key); } } if (!keys.isEmpty()) { stringToSign.append("?"); for (String key : keys) { String value = queryParams.get(key); if (value == null) { value = ""; } stringToSign.append(key).append("=").append(value).append("&"); } stringToSign.deleteCharAt(stringToSign.lastIndexOf("&")); } try { if (logger.isDebugEnabled()) { logger.debug("BEGIN STRING TO SIGN"); logger.debug(stringToSign.toString()); logger.debug("END STRING TO SIGN"); } Mac mac = Mac.getInstance("HmacSHA256"); mac.init(new SecretKeySpec(Base64.decodeBase64(ctx.getStoragePrivate()), "HmacSHA256")); String signature = new String( Base64.encodeBase64(mac.doFinal(stringToSign.toString().getBytes("UTF-8")))); if (logger.isDebugEnabled()) { logger.debug("signature=" + signature); } return signature; } catch (UnsupportedEncodingException e) { logger.error("UTF-8 not supported: " + e.getMessage()); throw new InternalException(e); } catch (NoSuchAlgorithmException e) { logger.error("No such algorithm: " + e.getMessage()); throw new InternalException(e); } catch (InvalidKeyException e) { logger.error("Invalid key: " + e.getMessage()); throw new InternalException(e); } }
From source file:com.google.acre.servlet.ProxyPassServlet.java
/** * Executes the {@link HttpMethod} passed in and sends the proxy response * back to the client via the given {@link HttpServletResponse} * @param httpMethodProxyRequest An object representing the proxy request to be made * @param httpServletResponse An object by which we can send the proxied * response back to the client * @throws IOException Can be thrown by the {@link HttpClient}.executeMethod * @throws ServletException Can be thrown to indicate that another error has occurred *//*from www.j a v a 2 s .c o m*/ private void executeProxyRequest(HttpRequestBase httpMethodProxyRequest, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException { DefaultHttpClient client = new DefaultHttpClient(); client.getParams().setParameter(AllClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); String proxy_host = Configuration.Values.HTTP_PROXY_HOST.getValue(); int proxy_port = -1; if (!(proxy_host.length() == 0)) { proxy_port = Configuration.Values.HTTP_PROXY_PORT.getInteger(); HttpHost proxy = new HttpHost(proxy_host, proxy_port, "http"); client.getParams().setParameter(AllClientPNames.DEFAULT_PROXY, proxy); } // Execute the request HttpResponse res = client.execute(httpMethodProxyRequest); int rescode = res.getStatusLine().getStatusCode(); // Pass response headers back to the client Header[] headerArrayResponse = res.getAllHeaders(); for (Header header : headerArrayResponse) { httpServletResponse.addHeader(header.getName(), header.getValue()); } // Check if the proxy response is a redirect // The following code is adapted from org.tigris.noodle.filters.CheckForRedirect // Hooray for open source software if (rescode >= 300 && rescode < 304) { String stringStatusCode = Integer.toString(rescode); String stringLocation = httpMethodProxyRequest.getFirstHeader(STRING_LOCATION_HEADER).getValue(); if (stringLocation == null) { throw new ServletException("Recieved status code: " + stringStatusCode + " but no " + STRING_LOCATION_HEADER + " header was found in the response"); } // Modify the redirect to go to this proxy servlet rather that the proxied host String stringMyHostName = httpServletRequest.getServerName(); if (httpServletRequest.getServerPort() != 80) { stringMyHostName += ":" + httpServletRequest.getServerPort(); } stringMyHostName += httpServletRequest.getContextPath(); httpServletResponse.sendRedirect( stringLocation.replace(this.metawebAPIHostAndPort + this.metawebAPIPath, stringMyHostName)); return; } else if (rescode == 304) { // 304 needs special handling. See: // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304 // We get a 304 whenever passed an 'If-Modified-Since' // header and the data on disk has not changed; server // responds w/ a 304 saying I'm not going to send the // body because the file has not changed. httpServletResponse.setIntHeader(STRING_CONTENT_LENGTH_HEADER_NAME, 0); httpServletResponse.setStatus(304); return; } httpServletResponse.setStatus(rescode); InputStream instream = new BufferedInputStream(res.getEntity().getContent()); OutputStream outstream = httpServletResponse.getOutputStream(); IOUtils.copy(instream, outstream); instream.close(); }
From source file:org.jets3t.service.CloudFrontService.java
/** * Performs an HTTP/S request by invoking the provided HttpMethod object. If the HTTP * response code doesn't match the expected value, an exception is thrown. * * @param httpMethod the object containing a request target and all other information necessary to * perform the request * @param expectedResponseCode the HTTP response code that indicates a successful request. If the response code received * does not match this value an error must have occurred, so an exception is thrown. * @throws CloudFrontServiceException all exceptions are wrapped in a CloudFrontServiceException. Depending on the kind of error that * occurred, this exception may contain additional error information available from an XML * error response document. *//*from w w w .j a va 2 s .c om*/ protected HttpResponse performRestRequest(HttpRequestBase httpMethod, int expectedResponseCode) throws CloudFrontServiceException { // Set mandatory Request headers. if (httpMethod.getFirstHeader("Date") == null) { httpMethod.setHeader("Date", ServiceUtils.formatRfc822Date(getCurrentTimeWithOffset())); } HttpResponse response = null; boolean completedWithoutRecoverableError; int internalErrorCount = 0; try { do { completedWithoutRecoverableError = true; authorizeHttpRequest(httpMethod, null, null); response = httpClient.execute(httpMethod); int responseCode = response.getStatusLine().getStatusCode(); if (responseCode != expectedResponseCode) { if (responseCode == 500) { // Retry on Internal Server errors, up to the defined limit. long delayMs = 1000; if (++internalErrorCount < this.internalErrorRetryMax) { log.warn("Encountered " + internalErrorCount + " CloudFront Internal Server error(s), will retry in " + delayMs + "ms"); Thread.sleep(delayMs); completedWithoutRecoverableError = false; } else { throw new CloudFrontServiceException( "Encountered too many CloudFront Internal Server errors (" + internalErrorCount + "), aborting request."); } } else { // Parse XML error message. ErrorHandler handler = new CloudFrontXmlResponsesSaxParser(this.jets3tProperties) .parseErrorResponse(response.getEntity().getContent()); CloudFrontServiceException exception = new CloudFrontServiceException( "Request failed with CloudFront Service error", responseCode, handler.getType(), handler.getCode(), handler.getMessage(), handler.getDetail(), handler.getRequestId()); if ("RequestExpired".equals(exception.getErrorCode())) { // Retry on time skew errors. this.timeOffset = RestUtils.calculateTimeAdjustmentOffset(response); if (log.isWarnEnabled()) { log.warn("Adjusted time offset in response to RequestTimeTooSkewed error. " + "Local machine and service disagree on the time by approximately " + (this.timeOffset / 1000) + " seconds, please fix your system's time." + " Retrying connection."); } completedWithoutRecoverableError = false; } else { throw exception; } } } // End responseCode check } while (!completedWithoutRecoverableError); } catch (CloudFrontServiceException e) { releaseConnection(response); throw e; } catch (Exception t) { releaseConnection(response); throw new CloudFrontServiceException("CloudFront Request failed", t); } return response; }