java.net.URLConnection#getContent ( )源码实例Demo

下面列出了java.net.URLConnection#getContent ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: ns4_frame   文件: PerformanceTester.java
@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();
	} 
}
 
源代码2 项目: BiglyBT   文件: TrackerLoadTester.java
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();
  }
}
 
源代码3 项目: TorrentEngine   文件: TrackerLoadTester.java
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();
  }    
}
 
@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: ");
  }

}
 
源代码5 项目: mobile-sdk-android   文件: ImageService.java
@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;
}
 
源代码6 项目: camunda-bpm-platform   文件: CsrfPreventionIT.java
@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.");
  }

}
 
源代码7 项目: camunda-bpm-platform   文件: CsrfPreventionIT.java
@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"));
  }

}
 
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;
}
 
源代码9 项目: hadoop-ozone   文件: TestOzoneManagerHttpServer.java
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;
}
 
源代码10 项目: hadoop   文件: TestNameNodeHttpServer.java
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;
}
 
源代码11 项目: big-c   文件: TestNameNodeHttpServer.java
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;
}
 
源代码12 项目: zulip-android   文件: GravatarAsyncFetchTask.java
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;
}
 
源代码13 项目: json-schema   文件: DefaultSchemaClient.java
@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);
    }
}
 
源代码14 项目: olingo-odata2   文件: ODataApplicationTest.java
@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);

}
 
源代码15 项目: TestRailSDK   文件: HTTPUtils.java
/**
 * 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);
}
 
源代码16 项目: j2objc   文件: OldCookieHandlerTest.java
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);
    }
}
 
源代码17 项目: chipster   文件: UrlTransferUtil.java
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);
	}
}