本文整理了Java中java.net.HttpURLConnection.connect()
方法的一些代码示例,展示了HttpURLConnection.connect()
的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。HttpURLConnection.connect()
方法的具体详情如下:
包路径:java.net.HttpURLConnection
类名称:HttpURLConnection
方法名:connect
暂无
代码示例来源:origin: google/data-transfer-project
/**
* Gets an input stream to an image, given its URL.
*/
public InputStream get(String urlStr) throws IOException {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.connect();
return conn.getInputStream();
}
}
代码示例来源:origin: aws/aws-sdk-java
public HttpURLConnection connectToEndpoint(URI endpoint, Map<String, String> headers) throws IOException {
HttpURLConnection connection = (HttpURLConnection) endpoint.toURL().openConnection(Proxy.NO_PROXY);
connection.setConnectTimeout(1000 * 2);
connection.setReadTimeout(1000 * 5);
connection.setRequestMethod("GET");
connection.setDoOutput(true);
for (Map.Entry<String, String> header : headers.entrySet()) {
connection.addRequestProperty(header.getKey(), header.getValue());
}
// TODO should we autoredirect 3xx
// connection.setInstanceFollowRedirects(false);
connection.connect();
return connection;
}
代码示例来源:origin: spring-projects/spring-framework
@Override
protected ClientHttpResponse executeInternal(HttpHeaders headers) throws IOException {
try {
if (this.body != null) {
this.body.close();
}
else {
SimpleBufferingClientHttpRequest.addHeaders(this.connection, headers);
this.connection.connect();
// Immediately trigger the request in a no-output scenario as well
this.connection.getResponseCode();
}
}
catch (IOException ex) {
// ignore
}
return new SimpleClientHttpResponse(this.connection);
}
代码示例来源:origin: eclipse-vertx/vert.x
public static JsonObject getContent() throws IOException {
URL url = new URL("http://localhost:8080");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.connect();
InputStreamReader in = new InputStreamReader((InputStream) conn.getContent());
BufferedReader buff = new BufferedReader(in);
String line;
StringBuilder builder = new StringBuilder();
do {
line = buff.readLine();
builder.append(line).append("\n");
} while (line != null);
buff.close();
return new JsonObject(builder.toString());
}
代码示例来源:origin: graphhopper/graphhopper
/**
* This method initiates a connect call of the provided connection and returns the response
* stream. It only returns the error stream if it is available and readErrorStreamNoException is
* true otherwise it throws an IOException if an error happens. Furthermore it wraps the stream
* to decompress it if the connection content encoding is specified.
*/
public InputStream fetch(HttpURLConnection connection, boolean readErrorStreamNoException) throws IOException {
// create connection but before reading get the correct inputstream based on the compression and if error
connection.connect();
InputStream is;
if (readErrorStreamNoException && connection.getResponseCode() >= 400 && connection.getErrorStream() != null)
is = connection.getErrorStream();
else
is = connection.getInputStream();
if (is == null)
throw new IOException("Stream is null. Message:" + connection.getResponseMessage());
// wrap
try {
String encoding = connection.getContentEncoding();
if (encoding != null && encoding.equalsIgnoreCase("gzip"))
is = new GZIPInputStream(is);
else if (encoding != null && encoding.equalsIgnoreCase("deflate"))
is = new InflaterInputStream(is, new Inflater(true));
} catch (IOException ex) {
}
return is;
}
代码示例来源:origin: ACRA/acra
@SuppressWarnings("WeakerAccess")
protected void writeContent(@NonNull HttpURLConnection connection, @NonNull Method method, @NonNull T content) throws IOException {
// write output - see http://developer.android.com/reference/java/net/HttpURLConnection.html
connection.setRequestMethod(method.name());
connection.setDoOutput(true);
// Disable ConnectionPooling because otherwise OkHttp ConnectionPool will try to start a Thread on #connect
System.setProperty("http.keepAlive", "false");
connection.connect();
final OutputStream outputStream = senderConfiguration.compress() ? new GZIPOutputStream(connection.getOutputStream(), ACRAConstants.DEFAULT_BUFFER_SIZE_IN_BYTES)
: new BufferedOutputStream(connection.getOutputStream());
try {
write(outputStream, content);
outputStream.flush();
} finally {
IOUtils.safeClose(outputStream);
}
}
代码示例来源:origin: google/data-transfer-project
private InputStream getImageAsStream(String urlStr) throws IOException {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.connect();
return conn.getInputStream();
}
}
代码示例来源:origin: aws/aws-sdk-java
/**
* Connects to the metadata service to read the specified resource and
* returns the text contents.
*
* @param resourcePath
* The resource
*
* @return The text payload returned from the Amazon EC2 Instance Metadata
* service for the specified resource path.
*
* @throws IOException
* If any problems were encountered while connecting to metadata
* service for the requested resource path.
* @throws SdkClientException
* If the requested metadata service is not found.
*/
public String readResource(String resourcePath) throws IOException, SdkClientException {
URL url = getEc2MetadataServiceUrlForResource(resourcePath);
log.debug("Connecting to EC2 instance metadata service at URL: " + url.toString());
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setConnectTimeout(1000 * 2);
connection.setReadTimeout(1000 * 5);
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.addRequestProperty("User-Agent", USER_AGENT);
connection.connect();
return readResponse(connection);
}
代码示例来源:origin: spring-projects/spring-framework
@Override
public ClientHttpResponse call() throws Exception {
try {
if (body != null) {
body.close();
}
else {
SimpleBufferingClientHttpRequest.addHeaders(connection, headers);
connection.connect();
// Immediately trigger the request in a no-output scenario as well
connection.getResponseCode();
}
}
catch (IOException ex) {
// ignore
}
return new SimpleClientHttpResponse(connection);
}
});
代码示例来源:origin: google/data-transfer-project
/**
* Gets an input stream to an image, given its URL. Used by {@link FlickrPhotosImporter} to
* upload the image.
*/
public BufferedInputStream get(String urlStr) throws IOException {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.connect();
return new BufferedInputStream(conn.getInputStream());
}
}
代码示例来源:origin: org.springframework/spring-web
@Override
protected ClientHttpResponse executeInternal(HttpHeaders headers) throws IOException {
try {
if (this.body != null) {
this.body.close();
}
else {
SimpleBufferingClientHttpRequest.addHeaders(this.connection, headers);
this.connection.connect();
// Immediately trigger the request in a no-output scenario as well
this.connection.getResponseCode();
}
}
catch (IOException ex) {
// ignore
}
return new SimpleClientHttpResponse(this.connection);
}
代码示例来源:origin: stanfordnlp/CoreNLP
public boolean checkStatus(URL serverURL) {
try {
// 1. Set up the connection
HttpURLConnection connection = (HttpURLConnection) serverURL.openConnection();
// 1.1 Set authentication
if (apiKey != null && apiSecret != null) {
String userpass = apiKey + ':' + apiSecret;
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userpass.getBytes()));
connection.setRequestProperty("Authorization", basicAuth);
}
connection.setRequestMethod("GET");
connection.connect();
return connection.getResponseCode() >= 200 && connection.getResponseCode() <= 400;
} catch (Throwable t) {
throw new RuntimeException(t);
}
}
代码示例来源:origin: org.springframework/spring-web
@Override
public ClientHttpResponse call() throws Exception {
try {
if (body != null) {
body.close();
}
else {
SimpleBufferingClientHttpRequest.addHeaders(connection, headers);
connection.connect();
// Immediately trigger the request in a no-output scenario as well
connection.getResponseCode();
}
}
catch (IOException ex) {
// ignore
}
return new SimpleClientHttpResponse(connection);
}
});
代码示例来源:origin: libgdx/libgdx
/** Downloads the content of the specified url to the array. The array has to be big enough. */
private int download (byte[] out, String url) {
InputStream in = null;
try {
HttpURLConnection conn = null;
conn = (HttpURLConnection)new URL(url).openConnection();
conn.setDoInput(true);
conn.setDoOutput(false);
conn.setUseCaches(true);
conn.connect();
in = conn.getInputStream();
int readBytes = 0;
while (true) {
int length = in.read(out, readBytes, out.length - readBytes);
if (length == -1) break;
readBytes += length;
}
return readBytes;
} catch (Exception ex) {
return 0;
} finally {
StreamUtils.closeQuietly(in);
}
}
代码示例来源:origin: spring-projects/spring-framework
@Override
protected ClientHttpResponse executeInternal(HttpHeaders headers, byte[] bufferedOutput) throws IOException {
addHeaders(this.connection, headers);
// JDK <1.8 doesn't support getOutputStream with HTTP DELETE
if (getMethod() == HttpMethod.DELETE && bufferedOutput.length == 0) {
this.connection.setDoOutput(false);
}
if (this.connection.getDoOutput() && this.outputStreaming) {
this.connection.setFixedLengthStreamingMode(bufferedOutput.length);
}
this.connection.connect();
if (this.connection.getDoOutput()) {
FileCopyUtils.copy(bufferedOutput, this.connection.getOutputStream());
}
else {
// Immediately trigger the request in a no-output scenario as well
this.connection.getResponseCode();
}
return new SimpleClientHttpResponse(this.connection);
}
代码示例来源:origin: jenkinsci/jenkins
/**
* If the first URL we try to access with a HTTP proxy is HTTPS then the authentication cache will not have been
* pre-populated, so we try to access at least one HTTP URL before the very first HTTPS url.
* @param proxy
* @param url the actual URL being opened.
*/
private void jenkins48775workaround(Proxy proxy, URL url) {
if ("https".equals(url.getProtocol()) && !authCacheSeeded && proxy != Proxy.NO_PROXY) {
HttpURLConnection preAuth = null;
try {
// We do not care if there is anything at this URL, all we care is that it is using the proxy
preAuth = (HttpURLConnection) new URL("http", url.getHost(), -1, "/").openConnection(proxy);
preAuth.setRequestMethod("HEAD");
preAuth.connect();
} catch (IOException e) {
// ignore, this is just a probe we don't care at all
} finally {
if (preAuth != null) {
preAuth.disconnect();
}
}
authCacheSeeded = true;
} else if ("https".equals(url.getProtocol())){
// if we access any http url using a proxy then the auth cache will have been seeded
authCacheSeeded = authCacheSeeded || proxy != Proxy.NO_PROXY;
}
}
代码示例来源:origin: spring-projects/spring-framework
@Override
public ClientHttpResponse call() throws Exception {
SimpleBufferingClientHttpRequest.addHeaders(connection, headers);
// JDK <1.8 doesn't support getOutputStream with HTTP DELETE
if (getMethod() == HttpMethod.DELETE && bufferedOutput.length == 0) {
connection.setDoOutput(false);
}
if (connection.getDoOutput() && outputStreaming) {
connection.setFixedLengthStreamingMode(bufferedOutput.length);
}
connection.connect();
if (connection.getDoOutput()) {
FileCopyUtils.copy(bufferedOutput, connection.getOutputStream());
}
else {
// Immediately trigger the request in a no-output scenario as well
connection.getResponseCode();
}
return new SimpleClientHttpResponse(connection);
}
});
代码示例来源:origin: cymcsg/UltimateAndroid
public static Drawable drawableFromUrl(Context context, String url) throws IOException {
Bitmap x;
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.connect();
InputStream input = connection.getInputStream();
x = BitmapFactory.decodeStream(input);
return new BitmapDrawable(context.getResources(), x);
}
代码示例来源:origin: TeamNewPipe/NewPipe
/**
* @param threadId id of the calling thread
* @param conn Opens and establish the communication
* @throws IOException if an error occurred connecting to the server.
* @throws HttpError if the HTTP Status-Code is not satisfiable
*/
void establishConnection(int threadId, HttpURLConnection conn) throws IOException, HttpError {
conn.connect();
int statusCode = conn.getResponseCode();
if (DEBUG) {
Log.d(TAG, threadId + ":Content-Length=" + conn.getContentLength() + " Code:" + statusCode);
}
switch (statusCode) {
case 204:
case 205:
case 207:
throw new HttpError(conn.getResponseCode());
case 416:
return;// let the download thread handle this error
default:
if (statusCode < 200 || statusCode > 299) {
throw new HttpError(statusCode);
}
}
}
代码示例来源:origin: apache/flink
public static String getFromHTTP(String url, Time timeout) throws Exception {
final URL u = new URL(url);
LOG.info("Accessing URL " + url + " as URL: " + u);
final long deadline = timeout.toMilliseconds() + System.currentTimeMillis();
while (System.currentTimeMillis() <= deadline) {
HttpURLConnection connection = (HttpURLConnection) u.openConnection();
connection.setConnectTimeout(100000);
connection.connect();
if (Objects.equals(HttpResponseStatus.SERVICE_UNAVAILABLE, HttpResponseStatus.valueOf(connection.getResponseCode()))) {
// service not available --> Sleep and retry
LOG.debug("Web service currently not available. Retrying the request in a bit.");
Thread.sleep(100L);
} else {
InputStream is;
if (connection.getResponseCode() >= 400) {
// error!
LOG.warn("HTTP Response code when connecting to {} was {}", url, connection.getResponseCode());
is = connection.getErrorStream();
} else {
is = connection.getInputStream();
}
return IOUtils.toString(is, ConfigConstants.DEFAULT_CHARSET);
}
}
throw new TimeoutException("Could not get HTTP response in time since the service is still unavailable.");
}
内容来源于网络,如有侵权,请联系作者删除!