List of usage examples for org.apache.http.message BasicHttpRequest BasicHttpRequest
public BasicHttpRequest(String str, String str2)
From source file:com.nominanuda.web.http.ServletHelper.java
public HttpRequest copyRequest(HttpServletRequest servletRequest, boolean stripContextPath) throws IOException { final InputStream is = getServletRequestBody(servletRequest); String method = servletRequest.getMethod(); String uri = getRequestLineURI(servletRequest, stripContextPath); String ct = servletRequest.getContentType(); @SuppressWarnings("unused") String charenc = getCharacterEncoding(servletRequest); String cenc = getContentEncoding(servletRequest); long contentLength = servletRequest.getContentLength(); HttpRequest req;//from w w w . j a v a2 s . c o m if (is == null) { req = new BasicHttpRequest(method, uri); } else { req = new BasicHttpEntityEnclosingRequest(method, uri); HttpEntity entity = buildEntity(servletRequest, is, contentLength, ct, cenc); if (entity != null) { ((BasicHttpEntityEnclosingRequest) req).setEntity(entity); } } Enumeration<?> names = servletRequest.getHeaderNames(); while (names.hasMoreElements()) { String name = (String) names.nextElement(); Enumeration<?> vals = servletRequest.getHeaders(name); while (vals.hasMoreElements()) { String value = (String) vals.nextElement(); req.addHeader(name, value); } } return req; }
From source file:snoopware.api.ProxyServlet.java
@Override protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws ServletException, IOException { // Make the Request //note: we won't transfer the protocol version because I'm not sure it would truly be compatible String method = servletRequest.getMethod(); String proxyRequestUri = rewriteUrlFromRequest(servletRequest); HttpRequest proxyRequest;/*from w w w. ja va 2s .c om*/ //spec: RFC 2616, sec 4.3: either of these two headers signal that there is a message body. if (servletRequest.getHeader(HttpHeaders.CONTENT_LENGTH) != null || servletRequest.getHeader(HttpHeaders.TRANSFER_ENCODING) != null) { HttpEntityEnclosingRequest eProxyRequest = new BasicHttpEntityEnclosingRequest(method, proxyRequestUri); // Add the input entity (streamed) // note: we don't bother ensuring we close the servletInputStream since the container handles it eProxyRequest.setEntity( new InputStreamEntity(servletRequest.getInputStream(), servletRequest.getContentLength())); proxyRequest = eProxyRequest; } else { proxyRequest = new BasicHttpRequest(method, proxyRequestUri); } copyRequestHeaders(servletRequest, proxyRequest); try { // Execute the request if (doLog) { log("proxy " + method + " uri: " + servletRequest.getRequestURL().toString() + " -- " + proxyRequest.getRequestLine().getUri()); } HttpResponse proxyResponse = proxyClient.execute(URIUtils.extractHost(targetUri), proxyRequest); // Process the response int statusCode = proxyResponse.getStatusLine().getStatusCode(); if (doResponseRedirectOrNotModifiedLogic(servletRequest, servletResponse, proxyResponse, statusCode)) { //just to be sure, but is probably a no-op EntityUtils.consume(proxyResponse.getEntity()); return; } // Pass the response code. This method with the "reason phrase" is deprecated but // it's the only way to pass the // reason along too. //noinspection deprecation servletResponse.setStatus(statusCode, proxyResponse.getStatusLine().getReasonPhrase()); copyResponseHeaders(proxyResponse, servletResponse); // Send the content to the client copyResponseEntity(proxyResponse, servletResponse); } catch (Exception e) { //abort request, according to best practice with HttpClient if (proxyRequest instanceof AbortableHttpRequest) { AbortableHttpRequest abortableHttpRequest = (AbortableHttpRequest) proxyRequest; abortableHttpRequest.abort(); } if (e instanceof RuntimeException) { throw (RuntimeException) e; } if (e instanceof ServletException) { throw (ServletException) e; } //noinspection ConstantConditions if (e instanceof IOException) { throw (IOException) e; } throw new RuntimeException(e); } }
From source file:io.uploader.drive.drive.largefile.DriveResumableUpload.java
public boolean checkMD5(String md5) throws IOException { logger.info("Querying metadata of completed upload..."); Preconditions.checkState(org.apache.commons.lang3.StringUtils.isNotEmpty(md5)); CloseableHttpClient httpclient = null; CloseableHttpResponse response = null; try {//from w w w . j a v a2 s .co m httpclient = getHttpClient(); BasicHttpRequest httpreq = new BasicHttpRequest("PUT", location); httpreq.addHeader("Authorization", auth.getAuthHeader()); httpreq.addHeader("Content-Length", "0"); httpreq.addHeader("Content-Range", "bytes */" + getFileSizeString()); response = httpclient.execute(URIUtils.extractHost(uri), httpreq); BufferedHttpEntity entity = new BufferedHttpEntity(response.getEntity()); EntityUtils.consume(response.getEntity()); String retSrc = EntityUtils.toString(entity); String driveMd5 = null; if (useOldApi) { // Old API will return XML! JSONObject result = XML.toJSONObject(retSrc); logger.info("id : " + result.getJSONObject("entry").getString("gd:resourceId").replace("file:", "")); logger.info("title : " + result.getJSONObject("entry").getString("title")); logger.info("link : " + result.getJSONObject("entry").getJSONArray("link").getJSONObject(0).getString("href")); logger.info("md5Checksum : " + result.getJSONObject("entry").getString("docs:md5Checksum")); driveMd5 = result.getJSONObject("entry").getString("docs:md5Checksum"); } else { JSONObject result = new JSONObject(retSrc); logger.info("id : " + result.getString("id")); logger.info("title : " + result.getString("title")); logger.info("link : " + result.getString("webContentLink")); logger.info("md5Checksum : " + result.getString("md5Checksum")); driveMd5 = result.getString("md5Checksum"); } // verify the consistency of the md5 values return md5.equals(driveMd5); } finally { if (response != null) { response.close(); } if (httpclient != null) { httpclient.close(); } } }
From source file:be.milieuinfo.core.proxy.controller.ProxyServlet.java
@SuppressWarnings("deprecation") @Override//from w w w. j av a2 s . c o m protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws ServletException, IOException { // Make the Request //note: we won't transfer the protocol version because I'm not sure it would truly be compatible String method = servletRequest.getMethod(); String proxyRequestUri = rewriteUrlFromRequest(servletRequest); HttpRequest proxyRequest; //spec: RFC 2616, sec 4.3: either these two headers signal that there is a message body. if (servletRequest.getHeader(HttpHeaders.CONTENT_LENGTH) != null || servletRequest.getHeader(HttpHeaders.TRANSFER_ENCODING) != null) { HttpEntityEnclosingRequest eProxyRequest = new BasicHttpEntityEnclosingRequest(method, proxyRequestUri); // Add the input entity (streamed) // note: we don't bother ensuring we close the servletInputStream since the container handles it eProxyRequest.setEntity( new InputStreamEntity(servletRequest.getInputStream(), servletRequest.getContentLength())); proxyRequest = eProxyRequest; } else proxyRequest = new BasicHttpRequest(method, proxyRequestUri); copyRequestHeaders(servletRequest, proxyRequest); try { // Execute the request if (doLog) { log("proxy " + method + " uri: " + servletRequest.getRequestURI() + " -- " + proxyRequest.getRequestLine().getUri()); } HttpResponse proxyResponse = proxyClient.execute(URIUtils.extractHost(targetUri), proxyRequest); // Process the response int statusCode = proxyResponse.getStatusLine().getStatusCode(); if (doResponseRedirectOrNotModifiedLogic(servletRequest, servletResponse, proxyResponse, statusCode)) { //just to be sure, but is probably a no-op EntityUtils.consume(proxyResponse.getEntity()); return; } // Pass the response code. This method with the "reason phrase" is deprecated but it's the only way to pass the // reason along too. //noinspection deprecation servletResponse.setStatus(statusCode, proxyResponse.getStatusLine().getReasonPhrase()); copyResponseHeaders(proxyResponse, servletResponse); // Send the content to the client copyResponseEntity(proxyResponse, servletResponse); } catch (Exception e) { //abort request, according to best practice with HttpClient if (proxyRequest instanceof AbortableHttpRequest) { AbortableHttpRequest abortableHttpRequest = (AbortableHttpRequest) proxyRequest; abortableHttpRequest.abort(); } if (e instanceof RuntimeException) throw (RuntimeException) e; if (e instanceof ServletException) throw (ServletException) e; if (e instanceof IOException) throw (IOException) e; throw new RuntimeException(e); } }
From source file:uk.co.bubobubo.web.HttpClientProxy.java
@Override protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws ServletException, IOException { // Make the Request //note: we won't transfer the protocol version because I'm not sure it would truly be compatible String method = servletRequest.getMethod(); String proxyRequestUri = rewriteUrlFromRequest(servletRequest); HttpRequest proxyRequest;/*from w w w .j a va 2s .c om*/ //spec: RFC 2616, sec 4.3: either these two headers signal that there is a message body. if (servletRequest.getHeader(HttpHeaders.CONTENT_LENGTH) != null || servletRequest.getHeader(HttpHeaders.TRANSFER_ENCODING) != null) { HttpEntityEnclosingRequest eProxyRequest = new BasicHttpEntityEnclosingRequest(method, proxyRequestUri); // Add the input entity (streamed) // note: we don't bother ensuring we close the servletInputStream since the container handles it eProxyRequest.setEntity( new InputStreamEntity(servletRequest.getInputStream(), servletRequest.getContentLength())); proxyRequest = eProxyRequest; } else proxyRequest = new BasicHttpRequest(method, proxyRequestUri); copyRequestHeaders(servletRequest, proxyRequest); try { // Execute the request if (doLog) { log("proxy " + method + " uri: " + servletRequest.getRequestURI() + " -- " + proxyRequest.getRequestLine().getUri()); } proxyRequest.removeHeaders("authorization"); if (targetUri.getUserInfo() != null && !targetUri.getUserInfo().equalsIgnoreCase("") && !targetUri.getUserInfo().equalsIgnoreCase(":")) { Credentials credentials = new UsernamePasswordCredentials(targetUri.getUserInfo().split(":")[0], targetUri.getUserInfo().split(":")[1]); proxyClient.getCredentialsProvider().setCredentials(AuthScope.ANY, credentials); } HttpResponse proxyResponse = proxyClient.execute(URIUtils.extractHost(targetUri), proxyRequest); // Process the response int statusCode = proxyResponse.getStatusLine().getStatusCode(); if (doResponseRedirectOrNotModifiedLogic(servletRequest, servletResponse, proxyResponse, statusCode)) { //just to be sure, but is probably a no-op EntityUtils.consume(proxyResponse.getEntity()); return; } // Pass the response code. This method with the "reason phrase" is deprecated but it's the only way to pass the // reason along too. //noinspection deprecation servletResponse.setStatus(statusCode, proxyResponse.getStatusLine().getReasonPhrase()); copyResponseHeaders(proxyResponse, servletResponse); // Send the content to the client copyResponseEntity(proxyResponse, servletResponse); } catch (Exception e) { //abort request, according to best practice with HttpClient if (proxyRequest instanceof AbortableHttpRequest) { AbortableHttpRequest abortableHttpRequest = (AbortableHttpRequest) proxyRequest; abortableHttpRequest.abort(); } if (e instanceof RuntimeException) throw (RuntimeException) e; if (e instanceof ServletException) throw (ServletException) e; if (e instanceof IOException) throw (IOException) e; throw new RuntimeException(e); } }
From source file:org.redhat.jboss.httppacemaker.ProxyServlet.java
@Override protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws ServletException, IOException { // Make the Request //note: we won't transfer the protocol version because I'm not sure it would truly be compatible String method = servletRequest.getMethod(); // FIXME: the rewriteUrlFromRequest() method adds an extra trailing "slash", remove by the replace String proxyRequestUri = rewriteUrlFromRequest(servletRequest).replaceAll("/$", ""); HttpRequest proxyRequest;/*from ww w. java2 s. com*/ //spec: RFC 2616, sec 4.3: either of these two headers signal that there is a message body. if (servletRequest.getHeader(HttpHeaders.CONTENT_LENGTH) != null || servletRequest.getHeader(HttpHeaders.TRANSFER_ENCODING) != null) { HttpEntityEnclosingRequest eProxyRequest = new BasicHttpEntityEnclosingRequest(method, proxyRequestUri); // Add the input entity (streamed) // note: we don't bother ensuring we close the servletInputStream since the container handles it eProxyRequest.setEntity( new InputStreamEntity(servletRequest.getInputStream(), servletRequest.getContentLength())); proxyRequest = eProxyRequest; } else proxyRequest = new BasicHttpRequest(method, proxyRequestUri); copyRequestHeaders(servletRequest, proxyRequest); if (doLog) { log("proxy " + method + " uri: " + servletRequest.getRequestURI() + " -- " + proxyRequest.getRequestLine().getUri()); } sendProxyRequestToBackend(proxyRequest, servletRequest, servletResponse); }
From source file:securitydigest.TestDigestScheme.java
public void testDigestAuthenticationWithQueryStringInDigestURI() throws Exception { String challenge = "Digest realm=\"realm1\", nonce=\"f2a3f18799759d4f1a1c068b92b573cb\""; Header authChallenge = new BasicHeader(AUTH.WWW_AUTH, challenge); HttpRequest request = new BasicHttpRequest("Simple", "/?param=value"); Credentials cred = new UsernamePasswordCredentials("username", "password"); AuthScheme authscheme = new DigestScheme(); authscheme.processChallenge(authChallenge); Header authResponse = authscheme.authenticate(cred, request); Map<String, String> table = parseAuthResponse(authResponse); assertEquals("username", table.get("username")); assertEquals("realm1", table.get("realm")); assertEquals("/?param=value", table.get("uri")); assertEquals("f2a3f18799759d4f1a1c068b92b573cb", table.get("nonce")); assertEquals("a847f58f5fef0bc087bcb9c3eb30e042", table.get("response")); }
From source file:org.uiautomation.ios.grid.IOSCapabilitiesMonitor.java
private JSONObject getNodeStatusJson() throws IOException, JSONException { HttpClient client = new DefaultHttpClient(); String url = "http://" + node.getHost() + ":" + node.getPort() + "/wd/hub/status"; BasicHttpRequest r = new BasicHttpRequest("GET", url); HttpResponse response = client.execute(new HttpHost(node.getHost(), node.getPort()), r); return extractObject(response); }
From source file:org.ocpsoft.rewrite.servlet.config.proxy.ProxyServlet.java
protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws ServletException, IOException { /*/* w ww. jav a 2 s . com*/ * Note: we won't transfer the protocol version because I'm not sure it would truly be compatible */ String method = servletRequest.getMethod(); HttpRequest proxyRequest; /* * Spec: RFC 2616, sec 4.3: either of these two headers signal that there is a message body. */ if (servletRequest.getHeader(HttpHeaders.CONTENT_LENGTH) != null || servletRequest.getHeader(HttpHeaders.TRANSFER_ENCODING) != null) { HttpEntityEnclosingRequest eProxyRequest = new BasicHttpEntityEnclosingRequest(method, targetUri); /* * Add the input entity (streamed) note: we don't bother ensuring we close the servletInputStream since the * container handles it */ eProxyRequest.setEntity( new InputStreamEntity(servletRequest.getInputStream(), servletRequest.getContentLength())); proxyRequest = eProxyRequest; } else proxyRequest = new BasicHttpRequest(method, targetUri); copyRequestHeaders(servletRequest, proxyRequest); try { /* * Execute the request */ if (doLog) { logger.debug("proxy " + method + " uri: " + servletRequest.getRequestURI() + " -- " + proxyRequest.getRequestLine().getUri()); } HttpResponse proxyResponse = proxyClient.execute(URIUtils.extractHost(targetUriObj), proxyRequest); /* * Process the response */ int statusCode = proxyResponse.getStatusLine().getStatusCode(); if (doResponseRedirectOrNotModifiedLogic(servletRequest, servletResponse, proxyResponse, statusCode)) { /* * just to be sure, but is probably a no-op */ EntityUtils.consume(proxyResponse.getEntity()); return; } /* * Pass the response code. This method with the "reason phrase" is deprecated but it's the only way to pass the * reason along too. noinspection deprecation */ servletResponse.setStatus(statusCode, proxyResponse.getStatusLine().getReasonPhrase()); copyResponseHeaders(proxyResponse, servletResponse); /* * Send the content to the client */ copyResponseEntity(proxyResponse, servletResponse); } catch (Exception e) { /* * abort request, according to best practice with HttpClient */ if (proxyRequest instanceof AbortableHttpRequest) { AbortableHttpRequest abortableHttpRequest = (AbortableHttpRequest) proxyRequest; abortableHttpRequest.abort(); } if (e instanceof RuntimeException) throw (RuntimeException) e; if (e instanceof ServletException) throw (ServletException) e; // noinspection ConstantConditions if (e instanceof IOException) throw (IOException) e; throw new RuntimeException(e); } }
From source file:android.net.http.HttpsConnection.java
/** * Opens the connection to a http server or proxy. * * @return the opened low level connection * @throws IOException if the connection fails for any reason. *//*from w w w . jav a2s. c o m*/ @Override AndroidHttpClientConnection openConnection(Request req) throws IOException { SSLSocket sslSock = null; if (mProxyHost != null) { // If we have a proxy set, we first send a CONNECT request // to the proxy; if the proxy returns 200 OK, we negotiate // a secure connection to the target server via the proxy. // If the request fails, we drop it, but provide the event // handler with the response status and headers. The event // handler is then responsible for cancelling the load or // issueing a new request. AndroidHttpClientConnection proxyConnection = null; Socket proxySock = null; try { proxySock = new Socket(mProxyHost.getHostName(), mProxyHost.getPort()); proxySock.setSoTimeout(60 * 1000); proxyConnection = new AndroidHttpClientConnection(); HttpParams params = new BasicHttpParams(); HttpConnectionParams.setSocketBufferSize(params, 8192); proxyConnection.bind(proxySock, params); } catch (IOException e) { if (proxyConnection != null) { proxyConnection.close(); } String errorMessage = e.getMessage(); if (errorMessage == null) { errorMessage = "failed to establish a connection to the proxy"; } throw new IOException(errorMessage); } StatusLine statusLine = null; int statusCode = 0; Headers headers = new Headers(); try { BasicHttpRequest proxyReq = new BasicHttpRequest("CONNECT", mHost.toHostString()); // add all 'proxy' headers from the original request for (Header h : req.mHttpRequest.getAllHeaders()) { String headerName = h.getName().toLowerCase(); if (headerName.startsWith("proxy") || headerName.equals("keep-alive")) { proxyReq.addHeader(h); } } proxyConnection.sendRequestHeader(proxyReq); proxyConnection.flush(); // it is possible to receive informational status // codes prior to receiving actual headers; // all those status codes are smaller than OK 200 // a loop is a standard way of dealing with them do { statusLine = proxyConnection.parseResponseHeader(headers); statusCode = statusLine.getStatusCode(); } while (statusCode < HttpStatus.SC_OK); } catch (ParseException e) { String errorMessage = e.getMessage(); if (errorMessage == null) { errorMessage = "failed to send a CONNECT request"; } throw new IOException(errorMessage); } catch (HttpException e) { String errorMessage = e.getMessage(); if (errorMessage == null) { errorMessage = "failed to send a CONNECT request"; } throw new IOException(errorMessage); } catch (IOException e) { String errorMessage = e.getMessage(); if (errorMessage == null) { errorMessage = "failed to send a CONNECT request"; } throw new IOException(errorMessage); } if (statusCode == HttpStatus.SC_OK) { try { sslSock = (SSLSocket) getSocketFactory().createSocket(proxySock, mHost.getHostName(), mHost.getPort(), true); } catch (IOException e) { if (sslSock != null) { sslSock.close(); } String errorMessage = e.getMessage(); if (errorMessage == null) { errorMessage = "failed to create an SSL socket"; } throw new IOException(errorMessage); } } else { // if the code is not OK, inform the event handler ProtocolVersion version = statusLine.getProtocolVersion(); req.mEventHandler.status(version.getMajor(), version.getMinor(), statusCode, statusLine.getReasonPhrase()); req.mEventHandler.headers(headers); req.mEventHandler.endData(); proxyConnection.close(); // here, we return null to indicate that the original // request needs to be dropped return null; } } else { // if we do not have a proxy, we simply connect to the host try { sslSock = (SSLSocket) getSocketFactory().createSocket(); sslSock.setSoTimeout(SOCKET_TIMEOUT); sslSock.connect(new InetSocketAddress(mHost.getHostName(), mHost.getPort())); } catch (IOException e) { if (sslSock != null) { sslSock.close(); } String errorMessage = e.getMessage(); if (errorMessage == null) { errorMessage = "failed to create an SSL socket"; } throw new IOException(errorMessage); } } // do handshake and validate server certificates SslError error = CertificateChainValidator.getInstance().doHandshakeAndValidateServerCertificates(this, sslSock, mHost.getHostName()); // Inform the user if there is a problem if (error != null) { // handleSslErrorRequest may immediately unsuspend if it wants to // allow the certificate anyway. // So we mark the connection as suspended, call handleSslErrorRequest // then check if we're still suspended and only wait if we actually // need to. synchronized (mSuspendLock) { mSuspended = true; } // don't hold the lock while calling out to the event handler boolean canHandle = req.getEventHandler().handleSslErrorRequest(error); if (!canHandle) { throw new IOException("failed to handle " + error); } synchronized (mSuspendLock) { if (mSuspended) { try { // Put a limit on how long we are waiting; if the timeout // expires (which should never happen unless you choose // to ignore the SSL error dialog for a very long time), // we wake up the thread and abort the request. This is // to prevent us from stalling the network if things go // very bad. mSuspendLock.wait(10 * 60 * 1000); if (mSuspended) { // mSuspended is true if we have not had a chance to // restart the connection yet (ie, the wait timeout // has expired) mSuspended = false; mAborted = true; if (HttpLog.LOGV) { HttpLog.v("HttpsConnection.openConnection():" + " SSL timeout expired and request was cancelled!!!"); } } } catch (InterruptedException e) { // ignore } } if (mAborted) { // The user decided not to use this unverified connection // so close it immediately. sslSock.close(); throw new SSLConnectionClosedByUserException("connection closed by the user"); } } } // All went well, we have an open, verified connection. AndroidHttpClientConnection conn = new AndroidHttpClientConnection(); BasicHttpParams params = new BasicHttpParams(); params.setIntParameter(HttpConnectionParams.SOCKET_BUFFER_SIZE, 8192); conn.bind(sslSock, params); return conn; }