@Test public void testOAuthStepTwo() throws IOException { //Create the mock response HttpResponse postResponse = new BasicHttpResponse(new ProtocolVersion("TEST", 0, 0), 200, "TEST"); postResponse.setEntity(new StringEntity(oauthStepTwoTestJSON)); //Set the call providers mock response callProvider.setPostResponse(postResponse); //Perform mock oauth step 2 Credentials credentials = client.oauthStepTwo(null, null); //Check null is not returned assertNotNull(credentials); //Check the info is what it should be assertEquals("access_token", credentials.getAccessToken()); assertEquals("refresh_token", credentials.getRefreshToken()); assertEquals("1234567890", credentials.getDateGenerated()); }
/** * Checks to make sure that tokens and dates are refreshed given a valid response from google * Gives a mock response from google with "new" access code * @throws IOException */ @Test public void checkRefreshToken() throws IOException { long dateGenerated = Instant.now().getEpochSecond() - (3600*2); credentials = new Credentials(jsonWithoutDate, dateGenerated); //Create mock response MockCall callProvider = new MockCall(); HttpResponse postResponse = new BasicHttpResponse(new ProtocolVersion("TEST", 0, 0), 200, "TEST"); postResponse.setEntity(new StringEntity("{ \"access_token\":\"new_access_token\", \"expires_in\":3920, \"token_type\":\"Bearer\" }")); callProvider.setPostResponse(postResponse); //Make assertions assertTrue(credentials.refreshToken(null, null, callProvider)); assertEquals("new_access_token", credentials.getAccessToken()); assertNotEquals(String.valueOf(dateGenerated), credentials.getDateGenerated()); }
public void testResponseProcessing() throws Exception { ContentDecoder contentDecoder = mock(ContentDecoder.class); IOControl ioControl = mock(IOControl.class); HttpContext httpContext = mock(HttpContext.class); HeapBufferedAsyncResponseConsumer consumer = spy(new HeapBufferedAsyncResponseConsumer(TEST_BUFFER_LIMIT)); ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); StatusLine statusLine = new BasicStatusLine(protocolVersion, 200, "OK"); HttpResponse httpResponse = new BasicHttpResponse(statusLine); httpResponse.setEntity(new StringEntity("test", ContentType.TEXT_PLAIN)); //everything goes well consumer.responseReceived(httpResponse); consumer.consumeContent(contentDecoder, ioControl); consumer.responseCompleted(httpContext); verify(consumer).releaseResources(); verify(consumer).buildResult(httpContext); assertTrue(consumer.isDone()); assertSame(httpResponse, consumer.getResult()); consumer.responseCompleted(httpContext); verify(consumer, times(1)).releaseResources(); verify(consumer, times(1)).buildResult(httpContext); }
private static void bufferLimitTest(HeapBufferedAsyncResponseConsumer consumer, int bufferLimit) throws Exception { ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); StatusLine statusLine = new BasicStatusLine(protocolVersion, 200, "OK"); consumer.onResponseReceived(new BasicHttpResponse(statusLine)); final AtomicReference<Long> contentLength = new AtomicReference<>(); HttpEntity entity = new StringEntity("", ContentType.APPLICATION_JSON) { @Override public long getContentLength() { return contentLength.get(); } }; contentLength.set(randomLong(bufferLimit)); consumer.onEntityEnclosed(entity, ContentType.APPLICATION_JSON); contentLength.set(randomLongBetween(bufferLimit + 1, MAX_TEST_BUFFER_SIZE)); try { consumer.onEntityEnclosed(entity, ContentType.APPLICATION_JSON); } catch(ContentTooLongException e) { assertEquals("entity content is too long [" + entity.getContentLength() + "] for the configured buffer limit [" + bufferLimit + "]", e.getMessage()); } }
@Before @SuppressWarnings("unchecked") public void createRestClient() throws IOException { CloseableHttpAsyncClient httpClient = mock(CloseableHttpAsyncClient.class); when(httpClient.<HttpResponse>execute(any(HttpAsyncRequestProducer.class), any(HttpAsyncResponseConsumer.class), any(HttpClientContext.class), any(FutureCallback.class))).thenAnswer(new Answer<Future<HttpResponse>>() { @Override public Future<HttpResponse> answer(InvocationOnMock invocationOnMock) throws Throwable { HttpAsyncRequestProducer requestProducer = (HttpAsyncRequestProducer) invocationOnMock.getArguments()[0]; HttpUriRequest request = (HttpUriRequest)requestProducer.generateRequest(); HttpHost httpHost = requestProducer.getTarget(); HttpClientContext context = (HttpClientContext) invocationOnMock.getArguments()[2]; assertThat(context.getAuthCache().get(httpHost), instanceOf(BasicScheme.class)); FutureCallback<HttpResponse> futureCallback = (FutureCallback<HttpResponse>) invocationOnMock.getArguments()[3]; //return the desired status code or exception depending on the path if (request.getURI().getPath().equals("/soe")) { futureCallback.failed(new SocketTimeoutException(httpHost.toString())); } else if (request.getURI().getPath().equals("/coe")) { futureCallback.failed(new ConnectTimeoutException(httpHost.toString())); } else if (request.getURI().getPath().equals("/ioe")) { futureCallback.failed(new IOException(httpHost.toString())); } else { int statusCode = Integer.parseInt(request.getURI().getPath().substring(1)); StatusLine statusLine = new BasicStatusLine(new ProtocolVersion("http", 1, 1), statusCode, ""); futureCallback.completed(new BasicHttpResponse(statusLine)); } return null; } }); int numHosts = RandomNumbers.randomIntBetween(getRandom(), 2, 5); httpHosts = new HttpHost[numHosts]; for (int i = 0; i < numHosts; i++) { httpHosts[i] = new HttpHost("localhost", 9200 + i); } failureListener = new HostsTrackingFailureListener(); restClient = new RestClient(httpClient, 10000, new Header[0], httpHosts, null, failureListener); }
public BasicRequestLine(final String method, final String uri, final ProtocolVersion version) { super(); if (method == null) { throw new IllegalArgumentException ("Method must not be null."); } if (uri == null) { throw new IllegalArgumentException ("URI must not be null."); } if (version == null) { throw new IllegalArgumentException ("Protocol version must not be null."); } this.method = method; this.uri = uri; this.protoversion = version; }
public final static ProtocolVersion parseProtocolVersion(String value, LineParser parser) throws ParseException { if (value == null) { throw new IllegalArgumentException ("Value to parse may not be null."); } if (parser == null) parser = BasicLineParser.DEFAULT; CharArrayBuffer buffer = new CharArrayBuffer(value.length()); buffer.append(value); ParserCursor cursor = new ParserCursor(0, value.length()); return parser.parseProtocolVersion(buffer, cursor); }
/** * Creates a new status line with the given version, status, and reason. * * @param version the protocol version of the response * @param statusCode the status code of the response * @param reasonPhrase the reason phrase to the status code, or * <code>null</code> */ public BasicStatusLine(final ProtocolVersion version, int statusCode, final String reasonPhrase) { super(); if (version == null) { throw new IllegalArgumentException ("Protocol version may not be null."); } if (statusCode < 0) { throw new IllegalArgumentException ("Status code may not be negative."); } this.protoVersion = version; this.statusCode = statusCode; this.reasonPhrase = reasonPhrase; }
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { if (request == null) { throw new IllegalArgumentException("HTTP request may not be null"); } if (request instanceof HttpEntityEnclosingRequest) { HttpEntity entity = ((HttpEntityEnclosingRequest)request).getEntity(); // Do not send the expect header if request body is known to be empty if (entity != null && entity.getContentLength() != 0) { ProtocolVersion ver = request.getRequestLine().getProtocolVersion(); if (HttpProtocolParams.useExpectContinue(request.getParams()) && !ver.lessEquals(HttpVersion.HTTP_1_0)) { request.addHeader(HTTP.EXPECT_DIRECTIVE, HTTP.EXPECT_CONTINUE); } } } }
@Test public void testMap() throws Exception { assertEquals("Message. 500 reason. Please contact your web hosting service provider for assistance.", new SwiftExceptionMappingService().map( new GenericException("message", null, new StatusLine() { @Override public ProtocolVersion getProtocolVersion() { throw new UnsupportedOperationException(); } @Override public int getStatusCode() { return 500; } @Override public String getReasonPhrase() { return "reason"; } })).getDetail()); }
@Test public void post_whenResponseIsFailure_logsException() throws IOException { ArgumentCaptor<HttpPost> requestCaptor = ArgumentCaptor.forClass(HttpPost.class); HttpClient httpClient = mock(HttpClient.class); BasicHttpResponse response = new BasicHttpResponse(new BasicStatusLine(new ProtocolVersion("http", 1, 1), 400, "")); response.setEntity(new StringEntity("failure reason here")); when(httpClient.execute(requestCaptor.capture())).thenReturn(response); MsTeamsNotification w = factory.getMsTeamsNotification(httpClient); MsTeamsNotificationPayloadContent content = new MsTeamsNotificationPayloadContent(); content.setBuildDescriptionWithLinkSyntax("http://foo"); content.setCommits(new ArrayList<Commit>()); w.setPayload(content); w.setEnabled(true); w.post(); assertNotNull(w.getResponse()); assertFalse(w.getResponse().getOk()); }
private ProtocolVersion toProtocolVersion(String httpVersion) { switch (httpVersion) { case "HTTP/0.9": case "0.9": return HttpVersion.HTTP_0_9; case "HTTP/1.0": case "1.0": return HttpVersion.HTTP_1_0; case "HTTP/1.1": case "1.1": return HttpVersion.HTTP_1_1; default: throw new IllegalArgumentException("Invalid HTTP version: " + httpVersion); } }
@Override public HttpResponse execute(HttpUriRequest request, HttpContext context) { requestExecuted = request; StatusLine statusLine = new BasicStatusLine( new ProtocolVersion("HTTP", 1, 1), mStatusCode, ""); HttpResponse response = new BasicHttpResponse(statusLine); response.setEntity(mResponseEntity); return response; }
private static ProtocolVersion parseProtocol(final Protocol p) { switch (p) { case HTTP_1_0: return new ProtocolVersion("HTTP", 1, 0); case HTTP_1_1: return new ProtocolVersion("HTTP", 1, 1); case SPDY_3: return new ProtocolVersion("SPDY", 3, 1); case HTTP_2: return new ProtocolVersion("HTTP", 2, 0); } throw new IllegalAccessError("Unkwown protocol"); }
@Test public void testVerifyCredentialsExpired() throws IOException { //Create the mock response HttpResponse postResponse = new BasicHttpResponse(new ProtocolVersion("TEST", 0, 0), 200,"TEST"); postResponse.setEntity(new StringEntity(verifyCredsTestResponseJSON)); callProvider.setPostResponse(postResponse); //Create credentials with date generated that will cause it to try to refresh the token Credentials credentials = new Credentials(verifyCredsTestDefaultJSON, (Instant.now().getEpochSecond() - 3600*2)); //Verify that credentials should be valid assertTrue(client.verifyCredentials(credentials)); }
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { String url = request.getUrl(); HashMap<String, String> map = new HashMap<String, String>(); map.putAll(request.getHeaders()); map.putAll(additionalHeaders); if (mUrlRewriter != null) { String rewritten = mUrlRewriter.rewriteUrl(url); if (rewritten == null) { throw new IOException("URL blocked by rewriter: " + url); } url = rewritten; } URL parsedUrl = new URL(url); HttpURLConnection connection = openConnection(parsedUrl, request); for (String headerName : map.keySet()) { connection.addRequestProperty(headerName, map.get(headerName)); } setConnectionParametersForRequest(connection, request); // Initialize HttpResponse with data from the HttpURLConnection. ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); int responseCode = connection.getResponseCode(); if (responseCode == -1) { // -1 is returned by getResponseCode() if the response code could not be retrieved. // Signal to the caller that something was wrong with the connection. throw new IOException("Could not retrieve response code from HttpUrlConnection."); } StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(), connection.getResponseMessage()); BasicHttpResponse response = new BasicHttpResponse(responseStatus); if (hasResponseBody(request.getMethod(), responseStatus.getStatusCode())) { response.setEntity(entityFromConnection(connection)); } for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) { if (header.getKey() != null) { Header h = new BasicHeader(header.getKey(), header.getValue().get(0)); response.addHeader(h); } } return response; }
private static Response mockResponse() { ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); RequestLine requestLine = new BasicRequestLine("GET", "/", protocolVersion); StatusLine statusLine = new BasicStatusLine(protocolVersion, 200, "OK"); HttpResponse httpResponse = new BasicHttpResponse(statusLine); return new Response(requestLine, new HttpHost("localhost", 9200), httpResponse); }
private Action echo() { return r -> { HttpEntity entity = ((HttpEntityEnclosingRequestBase) r.getHttpRequest()).getEntity(); BasicHttpResponse response = new BasicHttpResponse(new ProtocolVersion("http", 1, 1), 200, "ok"); response.setEntity(entity); return response; }; }
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { String url = request.getUrl(); HashMap<String, String> map = new HashMap<String, String>(); map.putAll(request.getHeaders()); map.putAll(additionalHeaders); if (mUrlRewriter != null) { String rewritten = mUrlRewriter.rewriteUrl(url); if (rewritten == null) { throw new IOException("URL blocked by rewriter: " + url); } url = rewritten; } URL parsedUrl = new URL(url); HttpURLConnection connection = openConnection(parsedUrl, request); for (String headerName : map.keySet()) { connection.addRequestProperty(headerName, map.get(headerName)); } setConnectionParametersForRequest(connection, request); // Initialize HttpResponse with data from the HttpURLConnection. ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); int responseCode = connection.getResponseCode(); if (responseCode == -1) { // -1 is returned by getResponseCode() if the response code could not be retrieved. // Signal to the caller that something was wrong with the connection. throw new IOException("Could not retrieve response code from HttpUrlConnection."); } StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(), connection.getResponseMessage()); BasicHttpResponse response = new BasicHttpResponse(responseStatus); response.setEntity(entityFromConnection(connection)); for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) { if (header.getKey() != null) { Header h = new BasicHeader(header.getKey(), header.getValue().get(0)); response.addHeader(h); } } return response; }
public RequestLine getRequestLine() { String method = getMethod(); ProtocolVersion ver = getProtocolVersion(); URI uri = getURI(); String uritext = null; if (uri != null) { uritext = uri.toASCIIString(); } if (uritext == null || uritext.length() == 0) { uritext = "/"; } return new BasicRequestLine(method, uritext, ver); }
/** * Creates the CONNECT request for tunnelling. * Called by {@link #createTunnelToTarget createTunnelToTarget}. * * @param route the route to establish * @param context the context for request execution * * @return the CONNECT request for tunnelling */ protected HttpRequest createConnectRequest(HttpRoute route, HttpContext context) { // see RFC 2817, section 5.2 and // INTERNET-DRAFT: Tunneling TCP based protocols through // Web proxy servers HttpHost target = route.getTargetHost(); String host = target.getHostName(); int port = target.getPort(); if (port < 0) { Scheme scheme = connManager.getSchemeRegistry(). getScheme(target.getSchemeName()); port = scheme.getDefaultPort(); } StringBuilder buffer = new StringBuilder(host.length() + 6); buffer.append(host); buffer.append(':'); buffer.append(Integer.toString(port)); String authority = buffer.toString(); ProtocolVersion ver = HttpProtocolParams.getVersion(params); HttpRequest req = new BasicHttpRequest ("CONNECT", authority, ver); return req; }
public RequestLine getRequestLine() { String method = getMethod(); ProtocolVersion ver = getProtocolVersion(); String uritext = null; if (uri != null) { uritext = uri.toASCIIString(); } if (uritext == null || uritext.length() == 0) { uritext = "/"; } return new BasicRequestLine(method, uritext, ver); }
/** * Returns the request line of this request. If an HTTP protocol version * was not explicitly set at the construction time, this method will obtain * it from the {@link HttpParams} instance associated with the object. * * @see #BasicHttpRequest(String, String) */ public RequestLine getRequestLine() { if (this.requestline == null) { ProtocolVersion ver = HttpProtocolParams.getVersion(getParams()); this.requestline = new BasicRequestLine(this.method, this.uri, ver); } return this.requestline; }
/** * Obtains value of the {@link CoreProtocolPNames#PROTOCOL_VERSION} parameter. * If not set, defaults to {@link HttpVersion#HTTP_1_1}. * * @param params HTTP parameters. * @return HTTP protocol version. */ public static ProtocolVersion getVersion(final HttpParams params) { if (params == null) { throw new IllegalArgumentException("HTTP parameters may not be null"); } Object param = params.getParameter (CoreProtocolPNames.PROTOCOL_VERSION); if (param == null) { return HttpVersion.HTTP_1_1; } return (ProtocolVersion)param; }
public HttpResponse newHttpResponse(final ProtocolVersion ver, final int status, HttpContext context) { if (ver == null) { throw new IllegalArgumentException("HTTP version may not be null"); } final Locale loc = determineLocale(context); final String reason = reasonCatalog.getReason(status, loc); StatusLine statusline = new BasicStatusLine(ver, status, reason); return new BasicHttpResponse(statusline, reasonCatalog, loc); }
@Test public void testLoginFailure() throws Exception { final GenericException f = new GenericException( "message", new Header[]{}, new BasicStatusLine(new ProtocolVersion("http", 1, 1), 403, "Forbidden")); assertTrue(new SwiftExceptionMappingService().map(f) instanceof AccessDeniedException); assertEquals("Access denied", new SwiftExceptionMappingService().map(f).getMessage()); assertEquals("Message. 403 Forbidden. Please contact your web hosting service provider for assistance.", new SwiftExceptionMappingService().map(f).getDetail()); }
@Before public void setUp() throws Exception { HttpClient httpClient = mock(HttpClient.class); BasicHttpResponse response = new BasicHttpResponse(new BasicStatusLine(new ProtocolVersion("http", 1, 1), 200, "")); PostMessageResponse successfulResponse = new PostMessageResponse(); successfulResponse.setOk(true); successfulResponse.setError("channel_not_found"); response.setEntity(new StringEntity(successfulResponse.toJson())); when(httpClient.execute(isA(HttpUriRequest.class))).thenReturn(response); msteamsNotificationImpl = new MsTeamsNotificationImpl(httpClient); spyMsTeamsNotification = spy(msteamsNotificationImpl); whl = new MsTeamsNotificationListener(sBuildServer, settings, configSettings, manager, factory); projSettings = new MsTeamsNotificationProjectSettings(); when(factory.getMsTeamsNotification()).thenReturn(spyMsTeamsNotification); //when(manager.isRegisteredFormat("JSON")).thenReturn(true); // when(manager.getFormat("JSON")).thenReturn(payload); //when(manager.getServer()).thenReturn(sBuildServer); when(sBuildServer.getProjectManager()).thenReturn(projectManager); when(projectManager.findProjectById("project1")).thenReturn(sProject); when(sBuildServer.getHistory()).thenReturn(buildHistory); when(sBuildServer.getRootUrl()).thenReturn("http://test.server"); when(previousSuccessfulBuild.getBuildStatus()).thenReturn(Status.NORMAL); when(previousSuccessfulBuild.isPersonal()).thenReturn(false); when(previousFailedBuild.getBuildStatus()).thenReturn(Status.FAILURE); when(previousFailedBuild.isPersonal()).thenReturn(false); finishedSuccessfulBuilds.add(previousSuccessfulBuild); finishedFailedBuilds.add(previousFailedBuild); sBuildType.setProject(sProject); when(settings.getSettings(sRunningBuild.getProjectId(), "msteamsNotifications")).thenReturn(projSettings); whl.register(); }
@Test public void post_whenResponseIsOk_doesNotThrow() throws IOException { ArgumentCaptor<HttpPost> requestCaptor = ArgumentCaptor.forClass(HttpPost.class); HttpClient httpClient = mock(HttpClient.class); BasicHttpResponse response = new BasicHttpResponse(new BasicStatusLine(new ProtocolVersion("http", 1, 1), 200, "")); PostMessageResponse successfulResponse = new PostMessageResponse(); successfulResponse.setOk(true); successfulResponse.setError("channel_not_found"); response.setEntity(new StringEntity(successfulResponse.toJson())); when(httpClient.execute(requestCaptor.capture())).thenReturn(response); MsTeamsNotification w = factory.getMsTeamsNotification(httpClient); MsTeamsNotificationPayloadContent content = new MsTeamsNotificationPayloadContent(); content.setBuildDescriptionWithLinkSyntax("http://foo"); content.setCommits(new ArrayList<Commit>()); w.setPayload(content); w.setEnabled(true); w.post(); List<HttpPost> capturedRequests = requestCaptor.getAllValues(); HttpPost request = capturedRequests.get(0); assertNotNull(w.getResponse()); assertTrue(w.getResponse().getOk()); }
private DefaultBotSession getDefaultBotSession() throws IOException { HttpResponse response = new BasicHttpResponse(new BasicStatusLine( new ProtocolVersion("HTTP", 1, 1), 200, "")); response.setStatusCode(200); response.setEntity(new StringEntity("{}")); HttpClient mockHttpClient = Mockito.mock(HttpClient.class); Mockito.when(mockHttpClient.execute(Mockito.any(HttpPost.class))) .thenReturn(response); DefaultBotSession session = new DefaultBotSession(); session.setCallback(new FakeLongPollingBot()); session.setOptions(new DefaultBotOptions()); return session; }
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { String url = request.getUrl(); HashMap<String, String> map = new HashMap(); map.putAll(request.getHeaders()); map.putAll(additionalHeaders); if (this.mUrlRewriter != null) { String rewritten = this.mUrlRewriter.rewriteUrl(url); if (rewritten == null) { throw new IOException("URL blocked by rewriter: " + url); } url = rewritten; } HttpURLConnection connection = openConnection(new URL(url), request); for (String headerName : map.keySet()) { connection.addRequestProperty(headerName, (String) map.get(headerName)); } setConnectionParametersForRequest(connection, request); ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); if (connection.getResponseCode() == -1) { throw new IOException("Could not retrieve response code from HttpUrlConnection."); } StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection .getResponseCode(), connection.getResponseMessage()); BasicHttpResponse response = new BasicHttpResponse(responseStatus); if (hasResponseBody(request.getMethod(), responseStatus.getStatusCode())) { response.setEntity(entityFromConnection(connection)); } for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) { if (header.getKey() != null) { response.addHeader(new BasicHeader((String) header.getKey(), (String) ((List) header.getValue()).get(0))); } } return response; }
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { String url = request.getUrl(); HashMap<String, String> map = new HashMap(); map.putAll(request.getHeaders()); map.putAll(additionalHeaders); if (this.mUrlRewriter != null) { String rewritten = this.mUrlRewriter.rewriteUrl(url); if (rewritten == null) { throw new IOException("URL blocked by rewriter: " + url); } url = rewritten; } HttpURLConnection connection = openConnection(new URL(url), request); for (String headerName : map.keySet()) { connection.addRequestProperty(headerName, (String) map.get(headerName)); } setConnectionParametersForRequest(connection, request); ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); if (connection.getResponseCode() == -1) { throw new IOException("Could not retrieve response code from HttpUrlConnection."); } BasicHttpResponse response = new BasicHttpResponse(new BasicStatusLine(protocolVersion, connection.getResponseCode(), connection.getResponseMessage())); response.setEntity(entityFromConnection(connection)); for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) { if (header.getKey() != null) { response.addHeader(new BasicHeader((String) header.getKey(), (String) ((List) header.getValue()).get(0))); } } return response; }
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { String url = request.getUrl(); HashMap<String, String> map = new HashMap(); map.putAll(request.getHeaders()); map.putAll(additionalHeaders); if (this.mUrlRewriter != null) { String rewritten = this.mUrlRewriter.rewriteUrl(url); if (rewritten == null) { throw new IOException("URL blocked by rewriter: " + url); } url = rewritten; } HttpURLConnection connection = openConnection(new URL(url), request); for (String headerName : map.keySet()) { connection.addRequestProperty(headerName, (String) map.get(headerName)); } setConnectionParametersForRequest(connection, request); ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); if (connection.getResponseCode() == -1) { throw new IOException("Could not retrieve response code from HttpUrlConnection."); } StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(), connection.getResponseMessage()); BasicHttpResponse response = new BasicHttpResponse(responseStatus); if (hasResponseBody(request.getMethod(), responseStatus.getStatusCode())) { response.setEntity(entityFromConnection(connection)); } for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) { if (header.getKey() != null) { response.addHeader(new BasicHeader((String) header.getKey(), (String) ((List) header.getValue()).get(0))); } } return response; }
public static DummyResponseServerBehavior build(int statusCode, String statusMessage, String content) { HttpResponse response = new BasicHttpResponse( new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), statusCode, statusMessage)); setEntity(response, content); response.addHeader("Content-Length", String.valueOf(content.getBytes().length)); response.addHeader("Connection", "close"); return new DummyResponseServerBehavior(response); }
private static HttpResponseProxy createHttpResponseProxy(HttpEntity entity) { ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); BasicStatusLine statusLine = new BasicStatusLine(protocolVersion, 200, "mock response"); BasicHttpResponse response = new BasicHttpResponse(statusLine); response.setEntity(entity); return new HttpResponseProxy(response); }