List of usage examples for org.apache.http.protocol HTTP CONN_DIRECTIVE
String CONN_DIRECTIVE
To view the source code for org.apache.http.protocol HTTP CONN_DIRECTIVE.
Click Source Link
From source file:groovesquid.GetAdsThread.java
public static String getFile(String url) { String responseContent = null; HttpEntity httpEntity = null;//w w w .j a v a2 s . co m try { HttpGet httpGet = new HttpGet(url); httpGet.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE); httpGet.setHeader(HTTP.USER_AGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31"); HttpClient httpClient = HttpClientBuilder.create().build(); HttpResponse httpResponse = httpClient.execute(httpGet); ByteArrayOutputStream baos = new ByteArrayOutputStream(); httpEntity = httpResponse.getEntity(); StatusLine statusLine = httpResponse.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode == HttpStatus.SC_OK) { httpEntity.writeTo(baos); } else { throw new RuntimeException(url); } responseContent = baos.toString("UTF-8"); } catch (Exception ex) { log.log(Level.SEVERE, null, ex); } finally { try { EntityUtils.consume(httpEntity); } catch (IOException ex) { log.log(Level.SEVERE, null, ex); } } return responseContent; }
From source file:groovesquid.Grooveshark.java
public static String sendRequest(String method, HashMap<String, Object> parameters) { if (tokenExpires <= new Date().getTime() && tokenExpires != 0 && !"initiateSession".equals(method) && !"getCommunicationToken".equals(method) && !"getCountry".equals(method)) { try {//from ww w .j a va 2 s .c o m InitThread initThread = new InitThread(); initThread.start(); initThread.getLatch().await(); } catch (InterruptedException ex) { log.log(Level.SEVERE, null, ex); } } String responseContent = null; HttpEntity httpEntity = null; try { Client client = clients.getHtmlshark(); String protocol = "http://"; if (method.equals("getCommunicationToken")) { protocol = "https://"; } String url = protocol + "grooveshark.com/more.php?" + method; for (String jsqueueMethod : jsqueueMethods) { if (jsqueueMethod.equals(method)) { client = clients.getJsqueue(); break; } } header.put("client", client.getName()); header.put("clientRevision", client.getRevision()); header.put("privacy", "0"); header.put("uuid", uuid); header.put("country", country); if (!method.equals("initiateSession")) { header.put("session", session); header.put("token", generateToken(method, client.getSecret())); } Gson gson = new Gson(); String jsonString = gson.toJson(new JsonRequest(header, parameters, method)); log.info(">>> " + jsonString); HttpPost httpPost = new HttpPost(url); httpPost.setHeader(HTTP.CONTENT_TYPE, "application/json"); httpPost.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE); httpPost.setHeader(HTTP.USER_AGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31"); httpPost.setHeader("Referer", "http://grooveshark.com/JSQueue.swf?" + client.getRevision()); httpPost.setHeader("Content-Language", "en-US"); httpPost.setHeader("Cache-Control", "max-age=0"); httpPost.setHeader("Accept", "*/*"); httpPost.setHeader("Accept-Charset", "utf-8,ISO-8859-1;q=0.7,*;q=0.3"); httpPost.setHeader("Accept-Language", "de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4"); httpPost.setHeader("Accept-Encoding", "gzip,deflate,sdch"); httpPost.setHeader("Origin", "http://grooveshark.com"); if (!method.equals("initiateSession")) { httpPost.setHeader("Cookie", "PHPSESSID=" + session); } httpPost.setEntity(new StringEntity(jsonString, "UTF-8")); HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); if (Main.getConfig().getProxyHost() != null && Main.getConfig().getProxyPort() != null) { httpClientBuilder .setProxy(new HttpHost(Main.getConfig().getProxyHost(), Main.getConfig().getProxyPort())); } HttpClient httpClient = httpClientBuilder.build(); HttpResponse httpResponse = httpClient.execute(httpPost); ByteArrayOutputStream baos = new ByteArrayOutputStream(); httpEntity = httpResponse.getEntity(); StatusLine statusLine = httpResponse.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode == HttpStatus.SC_OK) { httpEntity.writeTo(baos); } else { throw new RuntimeException("method " + method + ": " + statusLine); } responseContent = baos.toString("UTF-8"); } catch (Exception ex) { Logger.getLogger(Grooveshark.class.getName()).log(Level.SEVERE, null, ex); } finally { try { EntityUtils.consume(httpEntity); } catch (IOException ex) { Logger.getLogger(Grooveshark.class.getName()).log(Level.SEVERE, null, ex); } } log.info("<<< " + responseContent); return responseContent; }
From source file:net.oneandone.sushi.fs.webdav.WebdavRoot.java
private static boolean wantsClose(HttpResponse response) { if (response == null) { // no response yet return true; }/*ww w .jav a 2 s .c o m*/ for (Header header : response.getHeaders(HTTP.CONN_DIRECTIVE)) { if ("close".equalsIgnoreCase(header.getValue())) { return true; } } return false; }
From source file:org.jsnap.http.base.HttpServlet.java
protected void doService(org.apache.http.HttpRequest request, org.apache.http.HttpResponse response) throws HttpException, IOException { // Client might keep the executing thread blocked for very long unless this header is added. response.addHeader(new Header(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE)); // Create a wrapped request object. String uri, data;/*from w w w.ja v a 2 s . c om*/ String method = request.getRequestLine().getMethod(); if (method.equals(HttpGet.METHOD_NAME)) { BasicHttpRequest get = (BasicHttpRequest) request; data = get.getRequestLine().getUri(); int ix = data.indexOf('?'); uri = (ix < 0 ? data : data.substring(0, ix)); data = (ix < 0 ? "" : data.substring(ix + 1)); } else if (method.equals(HttpPost.METHOD_NAME)) { BasicHttpEntityEnclosingRequest post = (BasicHttpEntityEnclosingRequest) request; HttpEntity postedEntity = post.getEntity(); uri = post.getRequestLine().getUri(); data = EntityUtils.toString(postedEntity); } else { response.setStatusCode(HttpStatus.SC_NOT_IMPLEMENTED); response.setHeader(new Header(HTTP.CONTENT_LEN, "0")); return; } String cookieLine = ""; if (request.containsHeader(COOKIE)) { Header[] cookies = request.getHeaders(COOKIE); for (Header cookie : cookies) { if (cookieLine.length() > 0) cookieLine += "; "; cookieLine += cookie.getValue(); } } HttpRequest req = new HttpRequest(uri, underlying, data, cookieLine); // Create a wrapped response object. ByteArrayOutputStream out = new ByteArrayOutputStream(BUFFER_SIZE); HttpResponse resp = new HttpResponse(out); // Do implementation specific processing. doServiceImpl(req, resp); out.flush(); // It's good practice to do this. // Do the actual writing to the actual response object. if (resp.redirectTo != null) { // Redirection is requested. resp.statusCode = HttpStatus.SC_MOVED_TEMPORARILY; response.setStatusCode(resp.statusCode); Header redirection = new Header(LOCATION, resp.redirectTo); response.setHeader(redirection); Logger.getLogger(HttpServlet.class).log(Level.DEBUG, "Status Code: " + Integer.toString(resp.statusCode)); Logger.getLogger(HttpServlet.class).log(Level.DEBUG, redirection.toString()); } else { // There will be a response entity. response.setStatusCode(resp.statusCode); HttpEntity entity; Header contentTypeHeader; boolean text = resp.contentType.startsWith(Formatter.TEXT); if (text) { // text/* ... entity = new StringEntity(out.toString(resp.characterSet), resp.characterSet); contentTypeHeader = new Header(HTTP.CONTENT_TYPE, resp.contentType + HTTP.CHARSET_PARAM + resp.characterSet); } else { // application/octet-stream, image/* ... entity = new ByteArrayEntity(out.toByteArray()); contentTypeHeader = new Header(HTTP.CONTENT_TYPE, resp.contentType); } boolean acceptsGzip = clientAcceptsGzip(request); long contentLength = entity.getContentLength(); // If client accepts gzipped content, the implementing object requested that response // gets gzipped and size of the response exceeds implementing object's size threshold // response entity will be gzipped. boolean gzipped = false; if (acceptsGzip && resp.zipSize > 0 && contentLength >= resp.zipSize) { ByteArrayOutputStream zipped = new ByteArrayOutputStream(BUFFER_SIZE); GZIPOutputStream gzos = new GZIPOutputStream(zipped); entity.writeTo(gzos); gzos.close(); entity = new ByteArrayEntity(zipped.toByteArray()); contentLength = zipped.size(); gzipped = true; } // This is where true writes are made. Header contentLengthHeader = new Header(HTTP.CONTENT_LEN, Long.toString(contentLength)); Header contentEncodingHeader = null; response.setHeader(contentTypeHeader); response.setHeader(contentLengthHeader); if (gzipped) { contentEncodingHeader = new Header(CONTENT_ENCODING, Formatter.GZIP); response.setHeader(contentEncodingHeader); } response.setEntity(entity); // Log critical headers. Logger.getLogger(HttpServlet.class).log(Level.DEBUG, "Status Code: " + Integer.toString(resp.statusCode)); Logger.getLogger(HttpServlet.class).log(Level.DEBUG, contentTypeHeader.toString()); if (gzipped) Logger.getLogger(HttpServlet.class).log(Level.DEBUG, contentEncodingHeader.toString()); Logger.getLogger(HttpServlet.class).log(Level.DEBUG, contentLengthHeader.toString()); } // Log cookies. for (Cookie cookie : resp.cookies) { if (cookie.valid()) { Header h = new Header(SET_COOKIE, cookie.toString()); response.addHeader(h); Logger.getLogger(HttpServlet.class).log(Level.DEBUG, h.toString()); } } }
From source file:net.kungfoo.grizzly.proxy.impl.ConnectingHandler.java
private static void requestReadyCleanUpHeaders(final HttpRequest request) { request.removeHeaders(HTTP.CONTENT_LEN); request.removeHeaders(HTTP.TRANSFER_ENCODING); request.removeHeaders(HTTP.CONN_DIRECTIVE); request.removeHeaders("Keep-Alive"); request.removeHeaders("Proxy-Authenticate"); request.removeHeaders("Proxy-Authorization"); request.removeHeaders("TE"); request.removeHeaders("Trailers"); request.removeHeaders("Upgrade"); // Remove host header request.removeHeaders(HTTP.TARGET_HOST); }
From source file:org.apache.synapse.transport.nhttp.Axis2HttpRequest.java
/** * Create and return a new HttpPost request to the destination EPR * * @return the HttpRequest to be sent out * @throws IOException in error retrieving the <code>HttpRequest</code> *///ww w . j a v a 2 s. com public HttpRequest getRequest() throws IOException, HttpException { String httpMethod = (String) msgContext.getProperty(Constants.Configuration.HTTP_METHOD); if (httpMethod == null) { httpMethod = "POST"; } endpointURLPrefix = (String) msgContext.getProperty(NhttpConstants.ENDPOINT_PREFIX); boolean forceHTTP10 = msgContext.isPropertyTrue(NhttpConstants.FORCE_HTTP_1_0); HttpVersion httpver = forceHTTP10 ? HttpVersion.HTTP_1_0 : HttpVersion.HTTP_1_1; HttpRequest httpRequest; try { if ("POST".equals(httpMethod) || "PUT".equals(httpMethod) || "PATCH".equals(httpMethod)) { URI uri = rewriteRequestURI(new URI(epr.getAddress())); BasicHttpEntityEnclosingRequest requestWithEntity = new BasicHttpEntityEnclosingRequest(httpMethod, uri.toASCIIString(), httpver); BasicHttpEntity entity = new BasicHttpEntity(); if (forceHTTP10) { setStreamAsTempData(entity); } else { entity.setChunked(chunked); if (!chunked) { setStreamAsTempData(entity); } } requestWithEntity.setEntity(entity); requestWithEntity.setHeader(HTTP.CONTENT_TYPE, messageFormatter.getContentType(msgContext, format, msgContext.getSoapAction())); httpRequest = requestWithEntity; } else if ("GET".equals(httpMethod) || "DELETE".equals(httpMethod)) { URL url = messageFormatter.getTargetAddress(msgContext, format, new URL(epr.getAddress())); URI uri = rewriteRequestURI(url.toURI()); httpRequest = new BasicHttpRequest(httpMethod, uri.toASCIIString(), httpver); /*GETs and DELETEs do not need Content-Type headers because they do not have payloads*/ //httpRequest.setHeader(HTTP.CONTENT_TYPE, messageFormatter.getContentType( // msgContext, format, msgContext.getSoapAction())); } else { URI uri = rewriteRequestURI(new URI(epr.getAddress())); httpRequest = new BasicHttpRequest(httpMethod, uri.toASCIIString(), httpver); } } catch (URISyntaxException ex) { throw new HttpException(ex.getMessage(), ex); } // set any transport headers Object o = msgContext.getProperty(MessageContext.TRANSPORT_HEADERS); if (o != null && o instanceof Map) { Map headers = (Map) o; for (Object header : headers.keySet()) { Object value = headers.get(header); if (header instanceof String && value != null && value instanceof String) { if (!HTTPConstants.HEADER_HOST.equalsIgnoreCase((String) header)) { httpRequest.setHeader((String) header, (String) value); String excessProp = NhttpConstants.EXCESS_TRANSPORT_HEADERS; Map map = (Map) msgContext.getProperty(excessProp); if (map != null && map.get(header) != null) { log.debug("Number of excess values for " + header + " header is : " + ((Collection) (map.get(header))).size()); for (Iterator iterator = map.keySet().iterator(); iterator.hasNext();) { String key = (String) iterator.next(); for (String excessVal : (Collection<String>) map.get(key)) { httpRequest.addHeader((String) header, (String) excessVal); } } } } else { if (msgContext.getProperty(NhttpConstants.REQUEST_HOST_HEADER) != null) { httpRequest.setHeader((String) header, (String) msgContext.getProperty(NhttpConstants.REQUEST_HOST_HEADER)); } } } } } // if the message is SOAP 11 (for which a SOAPAction is *required*), and // the msg context has a SOAPAction or a WSA-Action (give pref to SOAPAction) // use that over any transport header that may be available String soapAction = msgContext.getSoapAction(); if (soapAction == null) { soapAction = msgContext.getWSAAction(); } if (soapAction == null) { msgContext.getAxisOperation().getInputAction(); } if (msgContext.isSOAP11() && soapAction != null && soapAction.length() >= 0) { Header existingHeader = httpRequest.getFirstHeader(HTTPConstants.HEADER_SOAP_ACTION); if (existingHeader != null) { httpRequest.removeHeader(existingHeader); } httpRequest.setHeader(HTTPConstants.HEADER_SOAP_ACTION, messageFormatter.formatSOAPAction(msgContext, null, soapAction)); } if (NHttpConfiguration.getInstance().isKeepAliveDisabled() || msgContext.isPropertyTrue(NhttpConstants.NO_KEEPALIVE)) { httpRequest.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE); } return httpRequest; }