本文整理汇总了Java中java.net.HttpURLConnection.getURL方法的典型用法代码示例。如果您正苦于以下问题:Java HttpURLConnection.getURL方法的具体用法?Java HttpURLConnection.getURL怎么用?Java HttpURLConnection.getURL使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类java.net.HttpURLConnection
的用法示例。
在下文中一共展示了HttpURLConnection.getURL方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: readResponse
import java.net.HttpURLConnection; //导入方法依赖的package包/类
/**
* Reads a response from the Amazon EC2 Instance Metadata Service and
* returns the content as a string.
*
* @param connection
* The connection to the Amazon EC2 Instance Metadata Service.
*
* @return The content contained in the response from the Amazon EC2
* Instance Metadata Service.
*
* @throws IOException
* If any problems ocurred while reading the response.
*/
private String readResponse(HttpURLConnection connection) throws IOException {
if (connection.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND)
throw new SdkClientException("The requested metadata is not found at " + connection.getURL());
InputStream inputStream = connection.getInputStream();
try {
StringBuilder buffer = new StringBuilder();
while (true) {
int c = inputStream.read();
if (c == -1) break;
buffer.append((char)c);
}
return buffer.toString();
} finally {
inputStream.close();
}
}
示例2: DelegatingHttpsURLConnection
import java.net.HttpURLConnection; //导入方法依赖的package包/类
public DelegatingHttpsURLConnection(HttpURLConnection delegate) {
super(delegate.getURL());
this.delegate = delegate;
}
示例3: readResource
import java.net.HttpURLConnection; //导入方法依赖的package包/类
/**
* Connects to the given endpoint to read the resource
* and returns the text contents.
*
* @param endpoint The service endpoint to connect to.
* @param retryPolicy The custom retry policy that determines whether a
* failed request should be retried or not.
* @return The text payload returned from the container metadata endpoint
* service for the specified resource path.
* @throws IOException If any problems were encountered while connecting to the
* service for the requested resource path.
* @throws SdkClientException If the requested service is not found.
*/
public String readResource(CredentialsEndpointProvider endpointProvider) throws IOException {
int retriesAttempted = 0;
InputStream inputStream = null;
while (true) {
try {
HttpURLConnection connection = connectionUtils.connectToEndpoint(endpointProvider.endpoint(),
endpointProvider.headers());
int statusCode = connection.getResponseCode();
if (statusCode == HttpURLConnection.HTTP_OK) {
inputStream = connection.getInputStream();
return IoUtils.toString(inputStream);
} else if (statusCode == HttpURLConnection.HTTP_NOT_FOUND) {
// This is to preserve existing behavior of EC2 Instance metadata service.
throw new SdkClientException("The requested metadata is not found at " + connection.getURL());
} else {
if (!endpointProvider.retryPolicy().shouldRetry(retriesAttempted++,
CredentialsEndpointRetryParameters.builder()
.withStatusCode(statusCode)
.build())) {
inputStream = connection.getErrorStream();
handleErrorResponse(inputStream, statusCode, connection.getResponseMessage());
}
}
} catch (IOException ioException) {
if (!endpointProvider.retryPolicy().shouldRetry(retriesAttempted++,
CredentialsEndpointRetryParameters.builder()
.withException(ioException)
.build())) {
throw ioException;
}
log.debug("An IOException occurred when connecting to endpoint: {} \n Retrying to connect again",
endpointProvider.endpoint());
} finally {
IoUtils.closeQuietly(inputStream, log);
}
}
}
示例4: readResource
import java.net.HttpURLConnection; //导入方法依赖的package包/类
/**
* Connects to the given endpoint to read the resource
* and returns the text contents.
*
* @param endpoint
* The service endpoint to connect to.
*
* @param retryPolicy
* The custom retry policy that determines whether a
* failed request should be retried or not.
*
* @return The text payload returned from the Amazon EC2 endpoint
* service for the specified resource path.
*
* @throws IOException
* If any problems were encountered while connecting to the
* service for the requested resource path.
* @throws SdkClientException
* If the requested service is not found.
*/
public String readResource(URI endpoint, CredentialsEndpointRetryPolicy retryPolicy) throws IOException {
int retriesAttempted = 0;
InputStream inputStream = null;
while (true) {
try {
HttpURLConnection connection = connectionUtils.connectToEndpoint(endpoint);
int statusCode = connection.getResponseCode();
if (statusCode == HttpURLConnection.HTTP_OK) {
inputStream = connection.getInputStream();
return IOUtils.toString(inputStream);
} else if (statusCode == HttpURLConnection.HTTP_NOT_FOUND) {
// This is to preserve existing behavior of EC2 Instance metadata service.
throw new SdkClientException("The requested metadata is not found at " + connection.getURL());
} else {
if (!retryPolicy.shouldRetry(retriesAttempted++, CredentialsEndpointRetryParameters.builder().withStatusCode(statusCode).build())) {
inputStream = connection.getErrorStream();
handleErrorResponse(inputStream, statusCode, connection.getResponseMessage());
}
}
} catch (IOException ioException) {
if (!retryPolicy.shouldRetry(retriesAttempted++, CredentialsEndpointRetryParameters.builder().withException(ioException).build())) {
throw ioException;
}
LOG.debug("An IOException occured when connecting to service endpoint: " + endpoint + "\n Retrying to connect again.");
} finally {
IOUtils.closeQuietly(inputStream, LOG);
}
}
}
示例5: write
import java.net.HttpURLConnection; //导入方法依赖的package包/类
/**
* Writes bytes to the output stream for the connection provided
* @param bytes the bytes to write
* @param conn the connection to write bytes to
*/
private void write(byte[] bytes, HttpURLConnection conn) {
try (OutputStream os = new BufferedOutputStream(conn.getOutputStream())) {
os.write(bytes);
os.flush();
} catch (IOException ex) {
throw new RuntimeException("Failed to write byes to URL: " + conn.getURL(), ex);
}
}
示例6: tjekOmdirigering
import java.net.HttpURLConnection; //导入方法依赖的package包/类
/**
* Tjek for om vi er på et netværk der kræver login eller lignende.
* Se 'Handling Network Sign-On' i http://developer.android.com/reference/java/net/HttpHttpURLConnection.html
*/
private static void tjekOmdirigering(URL u, HttpURLConnection urlConnection) throws IOException {
URL u2 = urlConnection.getURL();
if (!u.getHost().equals(u2.getHost())) {
// Vi blev omdirigeret
Log.d("tjekOmdirigering " + u);
Log.d("tjekOmdirigering " + u2);
//Log.rapporterFejl(omdirigeringsfejl);
throw new UnknownHostException("Der blev omdirigeret fra " + u.getHost() + " til " + u2.getHost());
}
}
示例7: DelegatingHttpsURLConnection
import java.net.HttpURLConnection; //导入方法依赖的package包/类
DelegatingHttpsURLConnection(HttpURLConnection delegate) {
super(delegate.getURL());
this.delegate = delegate;
}
示例8: call
import java.net.HttpURLConnection; //导入方法依赖的package包/类
private <T> T call(HttpURLConnection conn, Map jsonOutput,
int expectedResponse, Class<T> klass, int authRetryCount)
throws IOException {
T ret = null;
try {
if (jsonOutput != null) {
writeJson(jsonOutput, conn.getOutputStream());
}
} catch (IOException ex) {
IOUtils.closeStream(conn.getInputStream());
throw ex;
}
if ((conn.getResponseCode() == HttpURLConnection.HTTP_FORBIDDEN
&& (conn.getResponseMessage().equals(ANONYMOUS_REQUESTS_DISALLOWED) ||
conn.getResponseMessage().contains(INVALID_SIGNATURE)))
|| conn.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
// Ideally, this should happen only when there is an Authentication
// failure. Unfortunately, the AuthenticationFilter returns 403 when it
// cannot authenticate (Since a 401 requires Server to send
// WWW-Authenticate header as well)..
KMSClientProvider.this.authToken =
new DelegationTokenAuthenticatedURL.Token();
if (authRetryCount > 0) {
String contentType = conn.getRequestProperty(CONTENT_TYPE);
String requestMethod = conn.getRequestMethod();
URL url = conn.getURL();
conn = createConnection(url, requestMethod);
conn.setRequestProperty(CONTENT_TYPE, contentType);
return call(conn, jsonOutput, expectedResponse, klass,
authRetryCount - 1);
}
}
try {
AuthenticatedURL.extractToken(conn, authToken);
} catch (AuthenticationException e) {
// Ignore the AuthExceptions.. since we are just using the method to
// extract and set the authToken.. (Workaround till we actually fix
// AuthenticatedURL properly to set authToken post initialization)
}
HttpExceptionUtils.validateResponse(conn, expectedResponse);
if (conn.getContentType() != null
&& conn.getContentType().trim().toLowerCase()
.startsWith(APPLICATION_JSON_MIME)
&& klass != null) {
ObjectMapper mapper = new ObjectMapper();
InputStream is = null;
try {
is = conn.getInputStream();
ret = mapper.readValue(is, klass);
} finally {
IOUtils.closeStream(is);
}
}
return ret;
}
示例9: serializeToUrlConnection
import java.net.HttpURLConnection; //导入方法依赖的package包/类
final static void serializeToUrlConnection(RequestBatch requests, HttpURLConnection connection)
throws IOException, JSONException {
Logger logger = new Logger(LoggingBehavior.REQUESTS, "Request");
int numRequests = requests.size();
HttpMethod connectionHttpMethod = (numRequests == 1) ? requests.get(0).httpMethod : HttpMethod.POST;
connection.setRequestMethod(connectionHttpMethod.name());
URL url = connection.getURL();
logger.append("Request:\n");
logger.appendKeyValue("Id", requests.getId());
logger.appendKeyValue("URL", url);
logger.appendKeyValue("Method", connection.getRequestMethod());
logger.appendKeyValue("User-Agent", connection.getRequestProperty("User-Agent"));
logger.appendKeyValue("Content-Type", connection.getRequestProperty("Content-Type"));
connection.setConnectTimeout(requests.getTimeout());
connection.setReadTimeout(requests.getTimeout());
// If we have a single non-POST request, don't try to serialize anything or HttpURLConnection will
// turn it into a POST.
boolean isPost = (connectionHttpMethod == HttpMethod.POST);
if (!isPost) {
logger.log();
return;
}
connection.setDoOutput(true);
OutputStream outputStream = null;
try {
if (hasOnProgressCallbacks(requests)) {
ProgressNoopOutputStream countingStream = null;
countingStream = new ProgressNoopOutputStream(requests.getCallbackHandler());
processRequest(requests, null, numRequests, url, countingStream);
int max = countingStream.getMaxProgress();
Map<Request, RequestProgress> progressMap = countingStream.getProgressMap();
BufferedOutputStream buffered = new BufferedOutputStream(connection.getOutputStream());
outputStream = new ProgressOutputStream(buffered, requests, progressMap, max);
}
else {
outputStream = new BufferedOutputStream(connection.getOutputStream());
}
processRequest(requests, logger, numRequests, url, outputStream);
}
finally {
outputStream.close();
}
logger.log();
}
示例10: HttpURLConnectionWrapper
import java.net.HttpURLConnection; //导入方法依赖的package包/类
public HttpURLConnectionWrapper(HttpURLConnection conn) {
super(conn.getURL());
_conn = conn;
}
示例11: downloadHelper
import java.net.HttpURLConnection; //导入方法依赖的package包/类
private void downloadHelper(String hostName, String servlet, final String path, final String url,
final Map<String, Object> dict) {
HttpURLConnection op = null;
URL originalURL = null;
try {
if (url == null) {
op = Util.operation(
hostName,
servlet,
dict,
httpMethod,
Constants.API_SSL,
Constants.NETWORK_TIMEOUT_SECONDS_FOR_DOWNLOADS);
} else {
op = Util.createHttpUrlConnection(url, httpMethod, url.startsWith("https://"),
Constants.NETWORK_TIMEOUT_SECONDS_FOR_DOWNLOADS);
}
originalURL = op.getURL();
op.connect();
int statusCode = op.getResponseCode();
if (statusCode != 200) {
throw new Exception("Leanplum: Error sending request to: " + hostName +
", HTTP status code: " + statusCode);
}
Stack<String> dirs = new Stack<>();
String currentDir = path;
while ((currentDir = new File(currentDir).getParent()) != null) {
dirs.push(currentDir);
}
while (!dirs.isEmpty()) {
String directory = FileManager.fileRelativeToDocuments(dirs.pop());
boolean isCreated = new File(directory).mkdir();
if (!isCreated) {
Log.w("Failed to create directory: ", directory);
}
}
FileOutputStream out = new FileOutputStream(
new File(FileManager.fileRelativeToDocuments(path)));
Util.saveResponse(op, out);
pendingDownloads--;
if (Request.this.response != null) {
Request.this.response.response(null);
}
if (pendingDownloads == 0 && noPendingDownloadsBlock != null) {
noPendingDownloadsBlock.noPendingDownloads();
}
} catch (Exception e) {
if (e instanceof EOFException) {
if (op != null && !op.getURL().equals(originalURL)) {
downloadHelper(null, op.getURL().toString(), path, url, new HashMap<String, Object>());
return;
}
}
Log.e("Error downloading resource:" + path, e);
pendingDownloads--;
if (error != null) {
error.error(e);
}
if (pendingDownloads == 0 && noPendingDownloadsBlock != null) {
noPendingDownloadsBlock.noPendingDownloads();
}
} finally {
if (op != null) {
op.disconnect();
}
}
}
示例12: DelegatingHttpsURLConnection
import java.net.HttpURLConnection; //导入方法依赖的package包/类
public DelegatingHttpsURLConnection(HttpURLConnection delegate) {
super(delegate.getURL());
this.delegate = delegate;
}
示例13: getResolvedUrl
import java.net.HttpURLConnection; //导入方法依赖的package包/类
@Override
protected URL getResolvedUrl(final HttpURLConnection connection) {
return connection.getURL();
}