List of usage examples for java.net HttpURLConnection getHeaderField
public String getHeaderField(int n)
From source file:org.wso2.msf4j.HttpServerTest.java
@Test public void testDownloadTxtFile() throws Exception { HttpURLConnection urlConn = request("/test/v1/fileserver/txt", HttpMethod.GET); assertEquals(Response.Status.OK.getStatusCode(), urlConn.getResponseCode()); String contentType = urlConn.getHeaderField(HttpHeaders.CONTENT_TYPE); assertTrue("text/plain".equalsIgnoreCase(contentType)); InputStream downStream = urlConn.getInputStream(); File file = new File(Thread.currentThread().getContextClassLoader().getResource("testTxtFile.txt").toURI()); assertTrue(isStreamEqual(downStream, new FileInputStream(file))); }
From source file:org.wso2.msf4j.HttpServerTest.java
@Test public void testDownloadJpgFile() throws Exception { HttpURLConnection urlConn = request("/test/v1/fileserver/jpg", HttpMethod.GET); assertEquals(Response.Status.OK.getStatusCode(), urlConn.getResponseCode()); assertEquals("wso2", urlConn.getHeaderField("X-Custom-Header")); String contentType = urlConn.getHeaderField(HttpHeaders.CONTENT_TYPE); assertTrue("image/jpeg".equalsIgnoreCase(contentType)); InputStream downStream = urlConn.getInputStream(); File file = new File(Thread.currentThread().getContextClassLoader().getResource("testJpgFile.jpg").toURI()); assertTrue(isStreamEqual(downStream, new FileInputStream(file))); }
From source file:org.wso2.msf4j.HttpServerTest.java
@Test public void testContentTypeSetting0() throws Exception { HttpURLConnection urlConn = request("/test/v1/response/typehtml", HttpMethod.GET); assertEquals(Response.Status.OK.getStatusCode(), urlConn.getResponseCode()); String contentType = urlConn.getHeaderField(HttpHeaders.CONTENT_TYPE); assertTrue(contentType.equalsIgnoreCase(MediaType.TEXT_HTML)); String content = getContent(urlConn); assertEquals("Hello", content); urlConn.disconnect();// w w w . j av a2 s . c o m }
From source file:org.wso2.msf4j.HttpServerTest.java
@Test public void testDownloadPngFileFromInputStream() throws Exception { HttpURLConnection urlConn = request("/test/v1/fileserver/ip/png", HttpMethod.GET); assertEquals(Response.Status.OK.getStatusCode(), urlConn.getResponseCode()); String contentType = urlConn.getHeaderField(HttpHeaders.CONTENT_TYPE); assertTrue("image/png".equalsIgnoreCase(contentType)); InputStream downStream = urlConn.getInputStream(); File file = new File(Thread.currentThread().getContextClassLoader().getResource("testPngFile.png").toURI()); assertTrue(isStreamEqual(downStream, new FileInputStream(file))); }
From source file:org.wso2.msf4j.HttpServerTest.java
@Test public void testDownloadTxtFileFromInputStream() throws Exception { HttpURLConnection urlConn = request("/test/v1/fileserver/ip/txt", HttpMethod.GET); assertEquals(Response.Status.OK.getStatusCode(), urlConn.getResponseCode()); String contentType = urlConn.getHeaderField(HttpHeaders.CONTENT_TYPE); assertTrue("text/plain".equalsIgnoreCase(contentType)); InputStream downStream = urlConn.getInputStream(); File file = new File(Thread.currentThread().getContextClassLoader().getResource("testTxtFile.txt").toURI()); assertTrue(isStreamEqual(downStream, new FileInputStream(file))); }
From source file:org.wso2.msf4j.HttpServerTest.java
@Test public void testDownloadJpgFileFromInputStream() throws Exception { HttpURLConnection urlConn = request("/test/v1/fileserver/ip/jpg", HttpMethod.GET); assertEquals(Response.Status.OK.getStatusCode(), urlConn.getResponseCode()); assertEquals("wso2", urlConn.getHeaderField("X-Custom-Header")); String contentType = urlConn.getHeaderField(HttpHeaders.CONTENT_TYPE); assertTrue("image/jpeg".equalsIgnoreCase(contentType)); InputStream downStream = urlConn.getInputStream(); File file = new File(Thread.currentThread().getContextClassLoader().getResource("testJpgFile.jpg").toURI()); assertTrue(isStreamEqual(downStream, new FileInputStream(file))); }
From source file:com.gelakinetic.mtgfam.FamiliarActivity.java
/** * Open an inputStream to the HTML content at the given URL, making recursive calls for * redirection (HTTP 301, 302).//from ww w .j a v a 2s . c om * * @param url The URL to open a stream to * @param logWriter A PrintWriter to log debug info to. Can be null * @param recursionLevel The redirect recursion level. Starts at 0, doesn't go past 10 * @return An InputStream to the content at the URL, or null * @throws IOException Thrown if something goes terribly wrong */ private static @Nullable InputStream getHttpInputStream(URL url, @Nullable PrintWriter logWriter, int recursionLevel) throws IOException { /* Don't allow infinite recursion */ if (recursionLevel > 10) { return null; } /* Make the URL & connection objects, follow redirects, timeout after 5s */ HttpURLConnection.setFollowRedirects(true); HttpURLConnection connection = (HttpURLConnection) (url).openConnection(); connection.setConnectTimeout(5000); connection.setInstanceFollowRedirects(true); /* If the connection is not OK, debug print the response */ if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { /* Log the URL and response code */ if (logWriter != null) { logWriter.write("URL : " + url.toString() + '\n'); logWriter.write("RESP: " + connection.getResponseCode() + '\n'); } /* Comb through header fields for a redirect location */ URL nextUrl = null; for (String key : connection.getHeaderFields().keySet()) { /* Log the header */ if (logWriter != null) { logWriter.write("HDR : [" + key + "] " + connection.getHeaderField(key) + '\n'); } /* Found the URL to try next */ if (key != null && key.equalsIgnoreCase("location")) { nextUrl = new URL(connection.getHeaderField(key)); } } /* If the next location is still null, comb through the HTML * This is kind of a hack for when sites.google.com is serving up malformed 302 * redirects and all the header fields end up being in this input stream */ if (nextUrl == null) { /* Open the stream */ BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; int linesRead = 0; /* Read one line at a time */ while ((line = br.readLine()) != null) { /* Log the line */ if (logWriter != null) { logWriter.write("HTML:" + line + '\n'); } /* Check for a location */ if (line.toLowerCase().contains("location")) { nextUrl = new URL(line.split("\\s+")[1]); break; } /* Count the line, make sure to quit after 1000 */ linesRead++; if (linesRead > 1000) { break; } } } if (nextUrl != null) { /* If there is a URL to follow, follow it */ return getHttpInputStream(nextUrl, logWriter, recursionLevel + 1); } else { /* Otherwise return null */ return null; } } else { /* HTTP response is A-OK. Return the inputStream */ return connection.getInputStream(); } }
From source file:org.wso2.msf4j.HttpServerTest.java
@Test public void testContentTypeSetting1() throws Exception { HttpURLConnection urlConn = request("/test/v1/response/typehtml/str", HttpMethod.GET); assertEquals(Response.Status.OK.getStatusCode(), urlConn.getResponseCode()); String contentType = urlConn.getHeaderField(HttpHeaders.CONTENT_TYPE); assertTrue(contentType.equalsIgnoreCase(MediaType.TEXT_HTML)); String content = getContent(urlConn); assertEquals("Hello", content); urlConn.disconnect();//from w w w . j a va 2s . co m }
From source file:org.apache.hadoop.mapred.TestShuffleHandler.java
@Test(timeout = 10000) public void testKeepAlive() throws Exception { final ArrayList<Throwable> failures = new ArrayList<Throwable>(1); Configuration conf = new Configuration(); conf.setInt(ShuffleHandler.SHUFFLE_PORT_CONFIG_KEY, 0); conf.setBoolean(ShuffleHandler.SHUFFLE_CONNECTION_KEEP_ALIVE_ENABLED, true); // try setting to -ve keep alive timeout. conf.setInt(ShuffleHandler.SHUFFLE_CONNECTION_KEEP_ALIVE_TIME_OUT, -100); final LastSocketAddress lastSocketAddress = new LastSocketAddress(); ShuffleHandler shuffleHandler = new ShuffleHandler() { @Override//from ww w. j a va 2s . c o m protected Shuffle getShuffle(final Configuration conf) { // replace the shuffle handler with one stubbed for testing return new Shuffle(conf) { @Override protected MapOutputInfo getMapOutputInfo(String base, String mapId, int reduce, String user) throws IOException { return null; } @Override protected void verifyRequest(String appid, ChannelHandlerContext ctx, HttpRequest request, HttpResponse response, URL requestUri) throws IOException { } @Override protected void populateHeaders(List<String> mapIds, String jobId, String user, int reduce, HttpRequest request, HttpResponse response, boolean keepAliveParam, Map<String, MapOutputInfo> infoMap) throws IOException { // Send some dummy data (populate content length details) ShuffleHeader header = new ShuffleHeader("attempt_12345_1_m_1_0", 5678, 5678, 1); DataOutputBuffer dob = new DataOutputBuffer(); header.write(dob); dob = new DataOutputBuffer(); for (int i = 0; i < 100000; ++i) { header.write(dob); } long contentLength = dob.getLength(); // for testing purpose; // disable connectinKeepAliveEnabled if keepAliveParam is available if (keepAliveParam) { connectionKeepAliveEnabled = false; } super.setResponseHeaders(response, keepAliveParam, contentLength); } @Override protected ChannelFuture sendMapOutput(ChannelHandlerContext ctx, Channel ch, String user, String mapId, int reduce, MapOutputInfo info) throws IOException { lastSocketAddress.setAddress(ch.getRemoteAddress()); HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK); // send a shuffle header and a lot of data down the channel // to trigger a broken pipe ShuffleHeader header = new ShuffleHeader("attempt_12345_1_m_1_0", 5678, 5678, 1); DataOutputBuffer dob = new DataOutputBuffer(); header.write(dob); ch.write(wrappedBuffer(dob.getData(), 0, dob.getLength())); dob = new DataOutputBuffer(); for (int i = 0; i < 100000; ++i) { header.write(dob); } return ch.write(wrappedBuffer(dob.getData(), 0, dob.getLength())); } @Override protected void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) { if (failures.size() == 0) { failures.add(new Error()); ctx.getChannel().close(); } } @Override protected void sendError(ChannelHandlerContext ctx, String message, HttpResponseStatus status) { if (failures.size() == 0) { failures.add(new Error()); ctx.getChannel().close(); } } }; } }; shuffleHandler.init(conf); shuffleHandler.start(); String shuffleBaseURL = "http://127.0.0.1:" + shuffleHandler.getConfig().get(ShuffleHandler.SHUFFLE_PORT_CONFIG_KEY); URL url = new URL(shuffleBaseURL + "/mapOutput?job=job_12345_1&reduce=1&" + "map=attempt_12345_1_m_1_0"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty(ShuffleHeader.HTTP_HEADER_NAME, ShuffleHeader.DEFAULT_HTTP_HEADER_NAME); conn.setRequestProperty(ShuffleHeader.HTTP_HEADER_VERSION, ShuffleHeader.DEFAULT_HTTP_HEADER_VERSION); conn.connect(); DataInputStream input = new DataInputStream(conn.getInputStream()); Assert.assertEquals(HttpHeaders.KEEP_ALIVE, conn.getHeaderField(HttpHeaders.CONNECTION)); Assert.assertEquals("timeout=1", conn.getHeaderField(HttpHeaders.KEEP_ALIVE)); Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode()); ShuffleHeader header = new ShuffleHeader(); header.readFields(input); byte[] buffer = new byte[1024]; while (input.read(buffer) != -1) { } SocketAddress firstAddress = lastSocketAddress.getSocketAddres(); input.close(); // For keepAlive via URL url = new URL(shuffleBaseURL + "/mapOutput?job=job_12345_1&reduce=1&" + "map=attempt_12345_1_m_1_0&keepAlive=true"); conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty(ShuffleHeader.HTTP_HEADER_NAME, ShuffleHeader.DEFAULT_HTTP_HEADER_NAME); conn.setRequestProperty(ShuffleHeader.HTTP_HEADER_VERSION, ShuffleHeader.DEFAULT_HTTP_HEADER_VERSION); conn.connect(); input = new DataInputStream(conn.getInputStream()); Assert.assertEquals(HttpHeaders.KEEP_ALIVE, conn.getHeaderField(HttpHeaders.CONNECTION)); Assert.assertEquals("timeout=1", conn.getHeaderField(HttpHeaders.KEEP_ALIVE)); Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode()); header = new ShuffleHeader(); header.readFields(input); input.close(); SocketAddress secondAddress = lastSocketAddress.getSocketAddres(); Assert.assertNotNull("Initial shuffle address should not be null", firstAddress); Assert.assertNotNull("Keep-Alive shuffle address should not be null", secondAddress); Assert.assertEquals("Initial shuffle address and keep-alive shuffle " + "address should be the same", firstAddress, secondAddress); }
From source file:org.wso2.msf4j.HttpServerTest.java
@Test public void testSessionExpiry() throws Exception { long value = System.currentTimeMillis(); // Request to first operation HttpURLConnection urlConn = request("/test/v1/set-session2/" + value, HttpMethod.GET); assertEquals(200, urlConn.getResponseCode()); String setCookieHeader = urlConn.getHeaderField("Set-Cookie"); assertNotNull(setCookieHeader);//from w ww . j a v a 2s .c o m String content = getContent(urlConn); assertEquals(String.valueOf(value), content); urlConn.disconnect(); // Request to 2nd operation urlConn = request("/test/v1/get-session/", HttpMethod.GET); urlConn.setRequestProperty("Cookie", setCookieHeader); assertEquals(200, urlConn.getResponseCode()); setCookieHeader = urlConn.getHeaderField("Set-Cookie"); assertNull(setCookieHeader); content = getContent(urlConn); // content retrieved & returned from session assertEquals(String.valueOf(value), content); urlConn.disconnect(); // Expire the session urlConn = request("/test/v1/expire-session/", HttpMethod.GET); urlConn.setRequestProperty("Cookie", setCookieHeader); assertEquals(204, urlConn.getResponseCode()); setCookieHeader = urlConn.getHeaderField("Set-Cookie"); assertNull(setCookieHeader); urlConn.disconnect(); // Try to retrieve the object stored in the expired session urlConn = request("/test/v1/get-session/", HttpMethod.GET); urlConn.setRequestProperty("Cookie", setCookieHeader); assertEquals(204, urlConn.getResponseCode()); setCookieHeader = urlConn.getHeaderField("Set-Cookie"); assertNotNull(setCookieHeader); content = getContent(urlConn); // content retrieved & returned from session assertEquals("", content); urlConn.disconnect(); }