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

The following examples show how to use java.net.URLConnection#getContent() . These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: ns4_frame   File: PerformanceTester.java    License: 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 2
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 3
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 4
@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 5
Source Project: mobile-sdk-android   File: ImageService.java    License: 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 6
@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 7
@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 8
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 9
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;
}
 
Example 10
Source Project: hadoop   File: TestNameNodeHttpServer.java    License: 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 11
Source Project: big-c   File: TestNameNodeHttpServer.java    License: 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 12
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 13
Source Project: json-schema   File: DefaultSchemaClient.java    License: 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 14
@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 15
Source Project: TestRailSDK   File: HTTPUtils.java    License: 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 16
Source Project: j2objc   File: OldCookieHandlerTest.java    License: 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 17
Source Project: chipster   File: UrlTransferUtil.java    License: 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);
	}
}