Java Code Examples for java.net.URLConnection#getContent()

The following examples show how to use java.net.URLConnection#getContent() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CsrfPreventionIT.java    From camunda-bpm-spring-boot-starter with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldRejectModifyingRequest() {
  // given

  // when
  URLConnection urlConnection = headerRule.performPostRequest("http://localhost:" + port + "/api/admin/auth/user/default/login/welcome",
    "Content-Type", "application/x-www-form-urlencoded");

  /*
    This "then" block smells bad. However, due to
    https://app.camunda.com/jira/browse/CAM-10911
    it is not possible to check the error properly.
   */
  try {
    urlConnection.getContent();
    fail("Exception expected!");
  } catch (IOException e) {
    // then
    assertThat(e).hasMessageContaining("Server returned HTTP response code: 500 for URL: ");
  }

}
 
Example 2
Source File: CsrfPreventionIT.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
@Test(timeout=10000)
public void shouldRejectModifyingRequest() {
  // given
  String baseUrl = testProperties.getApplicationPath("/" + getWebappCtxPath());
  String modifyingRequestPath = "api/admin/auth/user/default/login/welcome";

  // when
  URLConnection urlConnection = performRequest(baseUrl + modifyingRequestPath,
                                               "POST",
                                               "Content-Type",
                                               "application/x-www-form-urlencoded");

  try {
    urlConnection.getContent();
    fail("Exception expected!");
  } catch (IOException e) {
    // then
    assertTrue(getXsrfTokenHeader().equals("Required"));
    assertTrue(e.getMessage().contains("Server returned HTTP response code: 403 for URL"));
  }

}
 
Example 3
Source File: CsrfPreventionIT.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldRejectModifyingRequest() {
  // given

  // when
  URLConnection urlConnection = headerRule.performPostRequest("http://localhost:" + port +
          "/camunda/api/admin/auth/user/default/login/welcome", "Content-Type",
      "application/x-www-form-urlencoded");

  try {
    urlConnection.getContent();
    fail("Exception expected!");
  } catch (IOException e) {
    // then
    assertThat(e).hasMessageContaining("Server returned HTTP response code: 403 for URL");
    assertThat(headerRule.getHeaderXsrfToken()).isEqualTo("Required");
    assertThat(headerRule.getErrorResponseContent()).contains("CSRFPreventionFilter: Token provided via HTTP Header is absent/empty.");
  }

}
 
Example 4
Source File: ImageService.java    From mobile-sdk-android with Apache License 2.0 6 votes vote down vote up
@Override
protected Bitmap doInBackground(Void... params) {
    if (isCancelled() || StringUtil.isEmpty(url)) {
        return null;
    }
    try {
        URLConnection connection = new URL(url).openConnection();
        connection.setReadTimeout(TIMEOUT);
        InputStream is = (InputStream) connection.getContent();
        Bitmap bitmap = BitmapFactory.decodeStream(is);
        is.close();
        return bitmap;

    } catch (Exception ignore) {
    }
    return null;
}
 
Example 5
Source File: TrackerLoadTester.java    From TorrentEngine with GNU General Public License v3.0 6 votes vote down vote up
private void announce(String trackerURL,byte[] hash,byte[] peerId,int port) {
  try {
    String strUrl = trackerURL 
    	+ "?info_hash=" + URLEncoder.encode(new String(hash, Constants.BYTE_ENCODING), Constants.BYTE_ENCODING).replaceAll("\\+", "%20")
    	+ "&peer_id="   + URLEncoder.encode(new String(peerId, Constants.BYTE_ENCODING), Constants.BYTE_ENCODING).replaceAll("\\+", "%20")
    	+ "&port=" + port
    	+ "&uploaded=0&downloaded=0&left=0&numwant=50&no_peer_id=1&compact=1";
    //System.out.println(strUrl);
    URL url = new URL(strUrl);
    URLConnection con = url.openConnection();
    con.connect();
    con.getContent();
  } catch(Exception e) {
    e.printStackTrace();
  }    
}
 
Example 6
Source File: TrackerLoadTester.java    From BiglyBT with GNU General Public License v2.0 6 votes vote down vote up
private void announce(String trackerURL,byte[] hash,byte[] peerId,int port) {
  try {
    String strUrl = trackerURL
      + "?info_hash=" + URLEncoder.encode(new String(hash, Constants.BYTE_ENCODING_CHARSET), Constants.BYTE_ENCODING_CHARSET.name()).replaceAll("\\+", "%20")
      + "&peer_id="   + URLEncoder.encode(new String(peerId, Constants.BYTE_ENCODING_CHARSET), Constants.BYTE_ENCODING_CHARSET.name()).replaceAll("\\+", "%20")
    	+ "&port=" + port
    	+ "&uploaded=0&downloaded=0&left=0&numwant=50&no_peer_id=1&compact=1";
    //System.out.println(strUrl);
    URL url = new URL(strUrl);
    URLConnection con = url.openConnection();
    con.connect();
    con.getContent();
  } catch(Exception e) {
    e.printStackTrace();
  }
}
 
Example 7
Source File: PerformanceTester.java    From ns4_frame with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
	//访问特定的dispatcher地址
	long startTime = System.currentTimeMillis();
	try {
		URL url = new URL(targetUrl);
		URLConnection httpURLConnection = url.openConnection();
		httpURLConnection.setUseCaches(false);
		httpURLConnection.connect();
		Object o = httpURLConnection.getContent();
		long cost = (System.currentTimeMillis()-startTime);
		if (cost > 100) 
		{
			logger.debug(o + " cost:"+cost+"ms");
		}
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} 
}
 
Example 8
Source File: TestNameNodeHttpServer.java    From big-c with Apache License 2.0 5 votes vote down vote up
private static boolean canAccess(String scheme, InetSocketAddress addr) {
  if (addr == null)
    return false;
  try {
    URL url = new URL(scheme + "://" + NetUtils.getHostPortString(addr));
    URLConnection conn = connectionFactory.openConnection(url);
    conn.connect();
    conn.getContent();
  } catch (Exception e) {
    return false;
  }
  return true;
}
 
Example 9
Source File: GravatarAsyncFetchTask.java    From zulip-android with Apache License 2.0 5 votes vote down vote up
public static Bitmap fetch(URL url) throws IOException {
    Log.i("GAFT.fetch", "Getting gravatar from url: " + url);
    URLConnection connection = url.openConnection();
    connection.setUseCaches(true);
    Object response = connection.getContent();
    if (response instanceof InputStream) {
        return BitmapFactory.decodeStream((InputStream) response);
    }
    return null;
}
 
Example 10
Source File: TestStorageContainerManagerHttpServer.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
private static boolean canAccess(String scheme, InetSocketAddress addr) {
  if (addr == null) {
    return false;
  }
  try {
    URL url =
        new URL(scheme + "://" + NetUtils.getHostPortString(addr) + "/jmx");
    URLConnection conn = connectionFactory.openConnection(url);
    conn.connect();
    conn.getContent();
  } catch (IOException e) {
    return false;
  }
  return true;
}
 
Example 11
Source File: DefaultSchemaClient.java    From json-schema with Apache License 2.0 5 votes vote down vote up
@Override
public InputStream get(final String url) {
    try {
        URL u = new URL(url);
        URLConnection conn = u.openConnection();
        String location = conn.getHeaderField("Location");
        if (location != null) {
            return get(location);
        }
        return (InputStream) conn.getContent();
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example 12
Source File: ODataApplicationTest.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
@Test
public void run() throws Exception {
  URL url = new URL(endpoint + "/$metadata");
  URLConnection con = url.openConnection();
  con.addRequestProperty("accept", "*/*");
  Object content = con.getContent();
  assertNotNull(content);

}
 
Example 13
Source File: HTTPUtils.java    From TestRailSDK with MIT License 5 votes vote down vote up
/**
 * Gathers the contents of a URL Connection and concatenates everything into a String
 * @param connection A URLConnection object that presumably has a getContent() that will have some content to get
 * @return A Concatenated String of the Content contained in the URLConnection
 */
public String getContentsFromConnection(URLConnection connection) {
    //Get the content from the connection. Since the content could be in many forms, this Java library requires us to marshall it into an InputStream, from which we get a...
    InputStreamReader in;
    try {
        in = new InputStreamReader((InputStream) connection.getContent());
    } catch ( IOException e ) {
        throw new RuntimeException("Could not read contents from connection: " + e.getMessage());
    }
    return getContentsFromInputStream(in);
}
 
Example 14
Source File: OldCookieHandlerTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void test_get_put() throws Exception {
    MockCookieHandler mch = new MockCookieHandler();
    CookieHandler defaultHandler = CookieHandler.getDefault();
    try {
        CookieHandler.setDefault(mch);

        server.play();
        server.enqueue(new MockResponse().addHeader("Set-Cookie2: a=\"android\"; "
                + "Comment=\"this cookie is delicious\"; "
                + "CommentURL=\"http://google.com/\"; "
                + "Discard; "
                + "Domain=\"" + server.getCookieDomain() + "\"; "
                + "Max-Age=\"60\"; "
                + "Path=\"/path\"; "
                + "Port=\"80,443," + server.getPort() + "\"; "
                + "Secure; "
                + "Version=\"1\""));

        URLConnection connection = server.getUrl("/path/foo").openConnection();
        connection.getContent();

        assertTrue(mch.wasGetCalled());
        assertTrue(mch.wasPutCalled());
    } finally {
        CookieHandler.setDefault(defaultHandler);
    }
}
 
Example 15
Source File: UrlTransferUtil.java    From chipster with MIT License 5 votes vote down vote up
public static Long getContentLength(URL url, boolean isChipsterServer) throws IOException {
	URLConnection connection = null;
	try {
		connection = url.openConnection();
		if (isChipsterServer) {				
			KeyAndTrustManager.configureForChipsterCertificate(connection);
		} else {
			KeyAndTrustManager.configureForCACertificates(connection);
		}
		
		if (connection instanceof HttpURLConnection) {
			HttpURLConnection httpConnection = (HttpURLConnection) connection;
			// check the response code first because the content length may be the length of the error message
			if (httpConnection.getResponseCode() >= 200 && httpConnection.getResponseCode() < 300) {
				long contentLength = connection.getContentLengthLong();

				if (contentLength >= 0) {
					return contentLength;
				} else {
					throw new IOException("content length not available: " + connection.getContent());
				}					
			} else {
				throw new IOException("content length not available: " + httpConnection.getResponseCode() + " " + httpConnection.getResponseMessage());
			}
		} else {
			throw new IOException("the remote content location isn't using http or https protocol: " + url);
		}
	} finally {
		IOUtils.disconnectIfPossible(connection);
	}
}
 
Example 16
Source File: TestNameNodeHttpServer.java    From hadoop with Apache License 2.0 5 votes vote down vote up
private static boolean canAccess(String scheme, InetSocketAddress addr) {
  if (addr == null)
    return false;
  try {
    URL url = new URL(scheme + "://" + NetUtils.getHostPortString(addr));
    URLConnection conn = connectionFactory.openConnection(url);
    conn.connect();
    conn.getContent();
  } catch (Exception e) {
    return false;
  }
  return true;
}
 
Example 17
Source File: TestOzoneManagerHttpServer.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
private static boolean canAccess(String scheme, InetSocketAddress addr) {
  if (addr == null) {
    return false;
  }
  try {
    URL url =
        new URL(scheme + "://" + NetUtils.getHostPortString(addr) + "/jmx");
    URLConnection conn = connectionFactory.openConnection(url);
    conn.connect();
    conn.getContent();
  } catch (Exception e) {
    return false;
  }
  return true;
}