下面列出了java.net.URLConnection#getContent ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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();
}
}
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();
}
}
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: ");
}
}
@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;
}
@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.");
}
}
@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;
}
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;
}
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;
}
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;
}
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;
}
@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);
}
}
@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);
}
/**
* 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);
}
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);
}
}
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);
}
}