/** * Sets the <tt>Expect</tt> header if it has not already been set, * in addition to the "standard" set of headers. * * @param state the {@link HttpState state} information associated with this method * @param conn the {@link HttpConnection connection} used to execute * this HTTP method * * @throws IOException if an I/O (transport) error occurs. Some transport exceptions * can be recovered from. * @throws HttpException if a protocol exception occurs. Usually protocol exceptions * cannot be recovered from. */ protected void addRequestHeaders(HttpState state, HttpConnection conn) throws IOException, HttpException { LOG.trace("enter ExpectContinueMethod.addRequestHeaders(HttpState, HttpConnection)"); super.addRequestHeaders(state, conn); // If the request is being retried, the header may already be present boolean headerPresent = (getRequestHeader("Expect") != null); // See if the expect header should be sent // = HTTP/1.1 or higher // = request body present if (getParams().isParameterTrue(HttpMethodParams.USE_EXPECT_CONTINUE) && getEffectiveVersion().greaterEquals(HttpVersion.HTTP_1_1) && hasRequestContent()) { if (!headerPresent) { setRequestHeader("Expect", "100-continue"); } } else { if (headerPresent) { removeRequestHeader("Expect"); } } }
/** * Generates <tt>Content-Length</tt> or <tt>Transfer-Encoding: Chunked</tt> * request header, as long as no <tt>Content-Length</tt> request header * already exists. * * @param state current state of http requests * @param conn the connection to use for I/O * * @throws IOException when errors occur reading or writing to/from the * connection * @throws HttpException when a recoverable error occurs */ protected void addContentLengthRequestHeader(HttpState state, HttpConnection conn) throws IOException, HttpException { LOG.trace("enter EntityEnclosingMethod.addContentLengthRequestHeader(" + "HttpState, HttpConnection)"); if ((getRequestHeader("content-length") == null) && (getRequestHeader("Transfer-Encoding") == null)) { long len = getRequestContentLength(); if (len < 0) { if (getEffectiveVersion().greaterEquals(HttpVersion.HTTP_1_1)) { addRequestHeader("Transfer-Encoding", "chunked"); } else { throw new ProtocolException(getEffectiveVersion() + " does not support chunk encoding"); } } else { addRequestHeader("Content-Length", String.valueOf(len)); } } }
public boolean processRequest( final SimpleHttpServerConnection conn, final SimpleRequest request) throws IOException { HttpVersion ver = request.getRequestLine().getHttpVersion(); if (ver.equals(HttpVersion.HTTP_1_0)) { return false; } else { SimpleResponse response = new SimpleResponse(); response.setStatusLine(ver, HttpStatus.SC_HTTP_VERSION_NOT_SUPPORTED); response.addHeader(new Header("Proxy-Connection", "close")); conn.setKeepAlive(false); // Make sure the request body is fully consumed request.getBodyBytes(); conn.writeResponse(response); return true; } }
/** * Tests ability to use HTTP/1.0 to execute CONNECT method and HTTP/1.1 to * execute methods once the tunnel is established. */ public void testTunnellingParamsHostHTTP10AndMethodHTTP11() throws IOException { this.proxy.addHandler(new HttpVersionHandler()); this.server.setHttpService(new FeedbackService()); this.client.getHostConfiguration().getParams().setParameter( HttpMethodParams.PROTOCOL_VERSION, HttpVersion.HTTP_1_0); GetMethod httpget = new GetMethod("/test/"); httpget.getParams().setVersion(HttpVersion.HTTP_1_1); try { this.client.executeMethod(httpget); assertNotNull(httpget.getStatusLine()); assertEquals(HttpStatus.SC_OK, httpget.getStatusLine().getStatusCode()); assertEquals(HttpVersion.HTTP_1_1, httpget.getEffectiveVersion()); } finally { httpget.releaseConnection(); } }
public boolean process(final SimpleRequest request, final SimpleResponse response) throws IOException { String uri = request.getRequestLine().getUri(); HttpVersion httpversion = request.getRequestLine().getHttpVersion(); if ("/miss/".equals(uri)) { response.setStatusLine(httpversion, HttpStatus.SC_MOVED_TEMPORARILY); response.addHeader(new Header("Location", "/hit/")); response.setBodyString("Missed!"); } else if ("/hit/".equals(uri)) { response.setStatusLine(httpversion, HttpStatus.SC_OK); response.setBodyString("Hit!"); } else { response.setStatusLine(httpversion, HttpStatus.SC_NOT_FOUND); response.setBodyString(uri + " not found"); } return true; }
public static SimpleResponse getResponse(int statusCode) { Integer code = new Integer(statusCode); SimpleResponse response = (SimpleResponse)responses.get(code); if (response == null) { response = new SimpleResponse(); response.setStatusLine(HttpVersion.HTTP_1_0, statusCode); response.setHeader(new Header("Content-Type", "text/plain; charset=US-ASCII")); String s = HttpStatus.getStatusText(statusCode); if (s == null) { s = "Error " + statusCode; } response.setBodyString(s); response.addHeader(new Header("Connection", "close")); response.addHeader(new Header("Content-Lenght", Integer.toString(s.length()))); responses.put(code, response); } return response; }
@Test(groups = "wso2.esb", description = "Sending HTTP1.0 message") public void sendingHTTP10Message() throws Exception { PostMethod post = new PostMethod(getProxyServiceURLHttp("StockQuoteProxyTestHTTPVersion")); RequestEntity entity = new StringRequestEntity(getPayload(), "text/xml", "UTF-8"); post.setRequestEntity(entity); post.setRequestHeader("SOAPAction", "urn:getQuote"); HttpMethodParams params = new HttpMethodParams(); params.setVersion(HttpVersion.HTTP_1_0); post.setParams(params); HttpClient httpClient = new HttpClient(); String httpVersion = ""; try { httpClient.executeMethod(post); post.getResponseBodyAsString(); httpVersion = post.getStatusLine().getHttpVersion(); } finally { post.releaseConnection(); } Assert.assertEquals(httpVersion, HttpVersion.HTTP_1_0.toString(), "Http version mismatched"); }
@Test(groups = "wso2.esb", description = "Sending HTTP1.1 message") public void sendingHTTP11Message() throws Exception { PostMethod post = new PostMethod(getProxyServiceURLHttp("StockQuoteProxyTestHTTPVersion")); RequestEntity entity = new StringRequestEntity(getPayload(), "text/xml", "UTF-8"); post.setRequestEntity(entity); post.setRequestHeader("SOAPAction", "urn:getQuote"); HttpMethodParams params = new HttpMethodParams(); params.setVersion(HttpVersion.HTTP_1_1); post.setParams(params); HttpClient httpClient = new HttpClient(); String httpVersion = ""; try { httpClient.executeMethod(post); post.getResponseBodyAsString(); httpVersion = post.getStatusLine().getHttpVersion(); } finally { post.releaseConnection(); } Assert.assertEquals(httpVersion, HttpVersion.HTTP_1_1.toString(), "Http version mismatched"); }
@HandlesEvent("getOnkiHttp") public Resolution getOnkiHttp() throws HttpException, IOException { String json = ""; String language = getUserLocale().toLanguageTag().split("-")[0]; HttpClient httpClient = new HttpClient(); httpClient.getParams().setParameter("http.protocol.version", HttpVersion.HTTP_1_1); httpClient.getParams().setParameter("http.protocol.content-charset", "UTF-8"); GetMethod get = new GetMethod("http://onki.fi/key-"+this.getOnkiAccessKey()+"/api/v2/http/onto/" + ontologyId + "/search?q=" + term + "&l=" + language); httpClient.executeMethod(get); if (get.getStatusCode() == 200) { json = get.getResponseBodyAsString(); } //logger.info("getOnkiHttp(): "+json); return new StreamingResolution(MIME_JS, json); }
@Test public void transformMessage_normal_relevantPropertiesRetained() throws Exception { HttpRequest request = new HttpRequest(new RequestLine("GET", REQUEST, HttpVersion.HTTP_1_1), new Header[]{new Header("testHeader", "testValue")}, ENCODING); MuleMessage message = new HttpMuleMessageFactory(context()).create(request, "UTF-8"); retainer.retainRequestProperties(message); Map<String, Object> retainedProperties = message.getInvocationProperty(RequestPropertiesRetainer.INITIAL_REQUEST_PROPERTY); assertThat(retainedProperties.size(), is(7)); @SuppressWarnings("unchecked") Map<String, String> headers = (Map<String, String>) retainedProperties.get(HttpConnector.HTTP_HEADERS); assertThat(headers.get("testHeader"), is("testValue")); assertThat(retainedProperties.get(HttpConnector.HTTP_METHOD_PROPERTY).toString(), is("GET")); assertThat(retainedProperties.get(HttpConnector.HTTP_VERSION_PROPERTY).toString(), is("HTTP/1.1")); assertThat(retainedProperties.get(HttpConnector.HTTP_REQUEST_PROPERTY).toString(), is(REQUEST)); assertThat(retainedProperties.get(HttpConnector.HTTP_QUERY_STRING).toString(), is("query=value")); }
/** * Returns {@link HttpVersion HTTP protocol version} to be used by the * {@link org.apache.commons.httpclient.HttpMethod HTTP methods} that * this collection of parameters applies to. * * @return {@link HttpVersion HTTP protocol version} */ public HttpVersion getVersion() { Object param = getParameter(PROTOCOL_VERSION); if (param == null) { return HttpVersion.HTTP_1_1; } return (HttpVersion)param; }
public boolean process(final SimpleRequest request, final SimpleResponse response) throws IOException { HttpVersion ver = request.getRequestLine().getHttpVersion(); response.setStatusLine(ver, HttpStatus.SC_OK); response.addHeader(new Header("Connection", "close")); response.addHeader(new Header("Set-Cookie", "custno = 12345; comment=test; version=1," + " name=John; version=1; max-age=600; secure; domain=.apache.org")); return true; }
public boolean process(final SimpleRequest request, final SimpleResponse response) throws IOException { HttpVersion httpversion = request.getRequestLine().getHttpVersion(); response.setStatusLine(httpversion, HttpStatus.SC_OK); response.addHeader(new Header("Set-Cookie", "name1=value1; path=/test")); response.setBodyString("whatever"); return true; }
public boolean process(final SimpleRequest request, final SimpleResponse response) throws IOException { HttpVersion httpversion = request.getRequestLine().getHttpVersion(); response.setStatusLine(httpversion, HttpStatus.SC_OK); response.addHeader(new Header("Set-Cookie", "name1=value1; Path=\"/test\"; Version=\"1\"")); response.addHeader(new Header("Set-Cookie2", "name2=value2; Path=\"/test\"; Version=\"1\"")); response.setBodyString("whatever"); return true; }
public boolean process(final SimpleRequest request, final SimpleResponse response) throws IOException { HttpVersion httpversion = request.getRequestLine().getHttpVersion(); response.setStatusLine(httpversion, HttpStatus.SC_OK); response.addHeader(new Header("Set-Cookie2", "name2=value2; Path=\"/test\"; Version=\"2\"")); response.setBodyString("whatever"); return true; }
public boolean process(final SimpleRequest request, final SimpleResponse response) throws IOException { HttpVersion httpversion = request.getRequestLine().getHttpVersion(); response.setStatusLine(httpversion, HttpStatus.SC_OK); response.addHeader(new Header("Set-Cookie", "name=wrong; Path=/test")); response.addHeader(new Header("Set-Cookie2", "name=right; Path=\"/test\"; Version=\"1\"")); response.setBodyString("whatever"); return true; }
public boolean process(final SimpleRequest request, final SimpleResponse response) throws IOException { RequestLine requestLine = request.getRequestLine(); HttpVersion ver = requestLine.getHttpVersion(); Header auth = request.getFirstHeader("Authorization"); if (auth == null) { response.setStatusLine(ver, HttpStatus.SC_UNAUTHORIZED); response.addHeader(new Header("WWW-Authenticate", "Digest realm=\"realm1\", nonce=\"ABC123\"")); response.setBodyString("Authorization required"); return true; } else { Map table = AuthChallengeParser.extractParams(auth.getValue()); String nonce = (String)table.get("nonce"); if (nonce.equals("ABC123")) { response.setStatusLine(ver, HttpStatus.SC_UNAUTHORIZED); response.addHeader(new Header("WWW-Authenticate", "Digest realm=\"realm1\", nonce=\"321CBA\", stale=\"true\"")); response.setBodyString("Authorization required"); return true; } else { response.setStatusLine(ver, HttpStatus.SC_OK); response.setBodyString("Authorization successful"); return true; } } }
public boolean process(final SimpleRequest request, final SimpleResponse response) throws IOException { RequestLine requestLine = request.getRequestLine(); HttpVersion ver = requestLine.getHttpVersion(); Header auth = request.getFirstHeader("Authorization"); if (auth == null) { response.setStatusLine(ver, HttpStatus.SC_UNAUTHORIZED); response.addHeader(new Header("WWW-Authenticate", "NTLM")); response.setBodyString("Authorization required"); return true; } else { String authstr = auth.getValue(); if (authstr.equals("NTLM TlRMTVNTUAABAAAABlIAAAYABgAkAAAABAAEACAAAABIT1NURE9NQUlO")) { response.setStatusLine(ver, HttpStatus.SC_UNAUTHORIZED); response.addHeader(new Header("WWW-Authenticate", "NTLM TlRMTVNTUAACAAAAAAAAACgAAAABggAAU3J2Tm9uY2UAAAAAAAAAAA==")); response.setBodyString("Authorization required"); return true; } if (authstr.equals("NTLM TlRMTVNTUAADAAAAGAAYAFIAAAAAAAAAagAAAAYABgBAAAAACAAIAEYAAAAEAAQATgAAAAAAAABqAAAABlIAAERPTUFJTlVTRVJOQU1FSE9TVJxndWIt46bHm11TPrt5Z6wrz7ziq04yRA==")) { response.setStatusLine(ver, HttpStatus.SC_OK); response.setBodyString("Authorization successful"); return true; } else { response.setStatusLine(ver, HttpStatus.SC_UNAUTHORIZED); response.addHeader(new Header("WWW-Authenticate", "NTLM")); response.setBodyString("Authorization required"); return true; } } }
public boolean process(final SimpleRequest request, final SimpleResponse response) throws IOException { RequestLine requestLine = request.getRequestLine(); HttpVersion ver = requestLine.getHttpVersion(); Header auth = request.getFirstHeader("Authorization"); if (auth == null) { response.setStatusLine(ver, HttpStatus.SC_BAD_REQUEST); response.setBodyString("Authorization header missing"); return true; } else { String authstr = auth.getValue(); if (authstr.indexOf("NTLM") != -1) { response.setStatusLine(ver, HttpStatus.SC_OK); return true; } else if (authstr.indexOf("Basic") != -1) { response.setStatusLine(ver, HttpStatus.SC_UNAUTHORIZED); response.addHeader(new Header("WWW-Authenticate", "Negotiate")); response.addHeader(new Header("WWW-Authenticate", "NTLM")); response.setBodyString("Authorization required"); return true; } else { response.setStatusLine(ver, HttpStatus.SC_BAD_REQUEST); response.setBodyString("Unknown auth type: " + authstr); return true; } } }
public void setStatusLine(final HttpVersion ver, int statuscode, final String phrase) { if (ver == null) { throw new IllegalArgumentException("HTTP version may not be null"); } if (statuscode <= 0) { throw new IllegalArgumentException("Status code may not be negative or zero"); } this.ver = ver; this.statuscode = statuscode; if (phrase != null) { this.phrase = phrase; } else { this.phrase = HttpStatus.getStatusText(statuscode); } }
public RequestLine(final String method, final String uri, final HttpVersion httpversion) { super(); if (method == null) { throw new IllegalArgumentException("Method may not be null"); } if (uri == null) { throw new IllegalArgumentException("URI may not be null"); } if (httpversion == null) { throw new IllegalArgumentException("HTTP version may not be null"); } this.method = method; this.uri = uri; this.httpversion = httpversion; }
private static HttpClient createRequestExecutor() { HttpClient httpclient = new HttpClient(); httpclient.getParams().setVersion(HttpVersion.HTTP_1_1); httpclient.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false); httpclient.getHttpConnectionManager().getParams().setStaleCheckingEnabled(false); return httpclient; }
private void initialize(Cluster cluster, boolean sslEnabled) { this.cluster = cluster; this.sslEnabled = sslEnabled; MultiThreadedHttpConnectionManager manager = new MultiThreadedHttpConnectionManager(); HttpConnectionManagerParams managerParams = manager.getParams(); managerParams.setConnectionTimeout(2000); // 2 s managerParams.setDefaultMaxConnectionsPerHost(10); managerParams.setMaxTotalConnections(100); extraHeaders = new ConcurrentHashMap<String, String>(); this.httpClient = new HttpClient(manager); HttpClientParams clientParams = httpClient.getParams(); clientParams.setVersion(HttpVersion.HTTP_1_1); }
/** * Constructor * @param cluster the cluster definition */ public Client(Cluster cluster) { this.cluster = cluster; MultiThreadedHttpConnectionManager manager = new MultiThreadedHttpConnectionManager(); HttpConnectionManagerParams managerParams = manager.getParams(); managerParams.setConnectionTimeout(2000); // 2 s managerParams.setDefaultMaxConnectionsPerHost(10); managerParams.setMaxTotalConnections(100); extraHeaders = new ConcurrentHashMap<String, String>(); this.httpClient = new HttpClient(manager); HttpClientParams clientParams = httpClient.getParams(); clientParams.setVersion(HttpVersion.HTTP_1_1); }
/** * Constructor */ public OwnCloudClient(Uri baseUri, HttpConnectionManager connectionMgr) { super(connectionMgr); if (baseUri == null) { throw new IllegalArgumentException("Parameter 'baseUri' cannot be NULL"); } mBaseUri = baseUri; mInstanceNumber = sIntanceCounter++; Log_OC.d(TAG + " #" + mInstanceNumber, "Creating OwnCloudClient"); String userAgent = OwnCloudClientManagerFactory.getUserAgent(); getParams().setParameter(HttpMethodParams.USER_AGENT, userAgent); getParams().setParameter( CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); getParams().setCookiePolicy( CookiePolicy.IGNORE_COOKIES); getParams().setParameter( PARAM_SINGLE_COOKIE_HEADER, // to avoid problems with some web servers PARAM_SINGLE_COOKIE_HEADER_VALUE); applyProxySettings(); clearCredentials(); }
public void setVersion(String version) { try { setVersion(HttpVersion.parse(version)); } catch (ProtocolException e) { throw new BuildException(e); } }
public static int sendFile(final String host, final String port, final String path, final String fileName, final InputStream inputStream, final long lengthInBytes) { HttpClient client = new HttpClient(); try { client.getParams().setParameter("http.protocol.version", HttpVersion.HTTP_1_1); client.getParams().setSoTimeout(3600 * 1000); // One hour PostMethod post = new PostMethod("http://" + host + ":" + port + "/" + path); Part[] parts = { new FilePart(fileName, new PartSource() { @Override public long getLength() { return lengthInBytes; } @Override public String getFileName() { return "fileName"; } @Override public InputStream createInputStream() throws IOException { return new BufferedInputStream(inputStream); } }) }; post.setRequestEntity(new MultipartRequestEntity(parts, new HttpMethodParams())); client.executeMethod(post); if (post.getStatusCode() >= 400) { String errorString = "POST Status Code: " + post.getStatusCode() + "\n"; if (post.getResponseHeader("Error") != null) { errorString += "ServletException: " + post.getResponseHeader("Error").getValue(); } throw new HttpException(errorString); } return post.getStatusCode(); } catch (Exception e) { LOGGER.error("Caught exception while sending file", e); Utils.rethrowException(e); throw new AssertionError("Should not reach this"); } }
/** * Constructor * @param cluster the cluster definition */ public Client(Cluster cluster) { this.cluster = cluster; MultiThreadedHttpConnectionManager manager = new MultiThreadedHttpConnectionManager(); HttpConnectionManagerParams managerParams = manager.getParams(); managerParams.setConnectionTimeout(2000); // 2 s managerParams.setDefaultMaxConnectionsPerHost(10); managerParams.setMaxTotalConnections(100); this.httpClient = new HttpClient(manager); HttpClientParams clientParams = httpClient.getParams(); clientParams.setVersion(HttpVersion.HTTP_1_1); }
/** * Test that the deferredTask handler is installed. */ public void testDeferredTask() throws Exception { // Replace the API proxy delegate so we can fake API responses. FakeableVmApiProxyDelegate fakeApiProxy = new FakeableVmApiProxyDelegate(); ApiProxy.setDelegate(fakeApiProxy); // Add a api response so the task queue api is happy. TaskQueueBulkAddResponse taskAddResponse = new TaskQueueBulkAddResponse(); TaskResult taskResult = taskAddResponse.addTaskResult(); taskResult.setResult(ErrorCode.OK.getValue()); taskResult.setChosenTaskName("abc"); fakeApiProxy.addApiResponse(taskAddResponse); // Issue a deferredTaskRequest with payload. String testData = "0987654321acbdefghijklmn"; String[] lines = fetchUrl(createUrl("/testTaskQueue?deferredTask=1&deferredData=" + testData)); TaskQueueBulkAddRequest request = new TaskQueueBulkAddRequest(); request.parseFrom(fakeApiProxy.getLastRequest().requestData); assertEquals(1, request.addRequestSize()); TaskQueueAddRequest addRequest = request.getAddRequest(0); assertEquals(TaskQueueAddRequest.RequestMethod.POST.getValue(), addRequest.getMethod()); // Pull out the request and fire it at the app. HttpClient httpClient = new HttpClient(); httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(30000); PostMethod post = new PostMethod(createUrl(addRequest.getUrl()).toString()); post.getParams().setVersion(HttpVersion.HTTP_1_0); // Add the required Task queue header, plus any headers from the request. post.addRequestHeader("X-AppEngine-QueueName", "1"); for (TaskQueueAddRequest.Header header : addRequest.headers()) { post.addRequestHeader(header.getKey(), header.getValue()); } post.setRequestEntity(new ByteArrayRequestEntity(addRequest.getBodyAsBytes())); int httpCode = httpClient.executeMethod(post); assertEquals(HttpURLConnection.HTTP_OK, httpCode); // Verify that the task was handled and that the payload is correct. lines = fetchUrl(createUrl("/testTaskQueue?getLastPost=1")); assertEquals("deferredData:" + testData, lines[lines.length - 1]); }