java.net.httpurlconnection Java Examples

The following examples show how to use java.net.httpurlconnection. 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 check out the related API usage on the sidebar.
Example #1
Source File: ArqITSessionInUrlServlet3.java    From HttpSessionReplacer with MIT License 7 votes vote down vote up
@RunAsClient
@Test
public void testSessionSwitched(@ArquillianResource URL baseURL) throws IOException {
  URL urlTest = url(baseURL, "TestServlet", "testSessionSwitched");
  String originalSession = callWebapp(urlTest);
  HttpURLConnection connection = (HttpURLConnection) url(baseURL, "TestServlet" + originalSession,
                                                         "testSessionSwitched").openConnection();
  assertThat(connection, matchLines("Previous value of attribute: B", "New value of attribute: B", "Encoded url: /" + originalSession));

  URL urlOther = url(baseURL, "SwitchServlet" + originalSession, "testSessionSwitched");
  String switchedSession = callWebapp(urlOther);

  assertThat(switchedSession, not(equalTo(originalSession)));
  HttpURLConnection connectionOther = (HttpURLConnection) url(baseURL, "TestServlet" + switchedSession,
                                                              "testSessionSwitched").openConnection();
  assertThat(connectionOther, matchLines("Previous value of attribute: S", "New value of attribute: B"));
}
 
Example #2
Source File: ListedLicenses.java    From tools with Apache License 2.0 6 votes vote down vote up
public static String getNestedURL(String stringUrl) throws MalformedURLException {
	URL url = new URL(stringUrl);
	try {
		HttpURLConnection con = (HttpURLConnection) url.openConnection();
		con.setInstanceFollowRedirects(false);
		con.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36");
		con.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
		con.addRequestProperty("Referer", "https://www.google.com/");
		con.connect();
		int resultCode = con.getResponseCode();
		if (resultCode == HttpURLConnection.HTTP_SEE_OTHER
				|| resultCode == HttpURLConnection.HTTP_MOVED_PERM
				|| resultCode == HttpURLConnection.HTTP_MOVED_TEMP) {
			String Location = con.getHeaderField("Location");
			if (Location.startsWith("/")) {
				Location = url.getProtocol() + "://" + url.getHost() + Location;
			}
			return getNestedURL(Location);
		}
	} catch (Exception e) {
		System.out.println(e.getMessage());
	}
	return url.toString();
}
 
Example #3
Source File: NetworkUtils.java    From android-dev-challenge with Apache License 2.0 6 votes vote down vote up
/**
 * This method returns the entire result from the HTTP response.
 *
 * @param url The URL to fetch the HTTP response from.
 * @return The contents of the HTTP response.
 * @throws IOException Related to network and stream reading
 */
public static String getResponseFromHttpUrl(URL url) throws IOException {
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    try {
        InputStream in = urlConnection.getInputStream();

        Scanner scanner = new Scanner(in);
        scanner.useDelimiter("\\A");

        boolean hasInput = scanner.hasNext();
        if (hasInput) {
            return scanner.next();
        } else {
            return null;
        }
    } finally {
        urlConnection.disconnect();
    }
}
 
Example #4
Source File: HurlStack.java    From FeedListViewDemo with MIT License 6 votes vote down vote up
/**
 * Opens an {@link HttpURLConnection} with parameters.
 * @param url
 * @return an open connection
 * @throws IOException
 */
private HttpURLConnection openConnection(URL url, Request<?> request) throws IOException {
    HttpURLConnection connection = createConnection(url);

    int timeoutMs = request.getTimeoutMs();
    connection.setConnectTimeout(timeoutMs);
    connection.setReadTimeout(timeoutMs);
    connection.setUseCaches(false);
    connection.setDoInput(true);

    // use caller-provided custom SslSocketFactory, if any, for HTTPS
    if ("https".equals(url.getProtocol()) && mSslSocketFactory != null) {
        ((HttpsURLConnection)connection).setSSLSocketFactory(mSslSocketFactory);
    }

    return connection;
}
 
Example #5
Source File: MultiputResponseHandler.java    From box-android-sdk with Apache License 2.0 6 votes vote down vote up
@Override
public <T extends BoxObject> T onResponse(Class<T> clazz, BoxHttpResponse response) throws IllegalAccessException, InstantiationException, BoxException {
        if (response.getResponseCode() == HttpURLConnection.HTTP_ACCEPTED) {
            try {
                // First attempt to use Retry-After header, all failures will eventually fall back to exponential backoff
                if (mNumAcceptedRetries < DEFAULT_NUM_RETRIES) {
                    mNumAcceptedRetries++;
                    mRetryAfterMillis = getRetryAfterFromResponse(response, 1);
                } else if (mRetryAfterMillis < DEFAULT_MAX_WAIT_MILLIS) {
                    // Exponential back off with some randomness to avoid traffic spikes to server
                    mRetryAfterMillis *= (1.5 + Math.random());
                } else {
                    // Give up after the maximum retry time is exceeded.
                    throw new BoxException.MaxAttemptsExceeded("Max wait time exceeded.", mNumAcceptedRetries);
                }
                Thread.sleep(mRetryAfterMillis);
                return (T) mRequest.send();
            } catch (InterruptedException e) {
                throw new BoxException(e.getMessage(), response);
            }
        } else {
            BoxIterator list = super.onResponse(BoxIteratorBoxEntity.class, response);
            return (T)list.get(0);
        }
    }
 
Example #6
Source File: Networker.java    From stetho with MIT License 6 votes vote down vote up
private HttpResponse doFetch() throws IOException {
  HttpURLConnection conn = configureAndConnectRequest();
  try {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    InputStream rawStream = conn.getInputStream();
    try {
      // Let Stetho see the raw, possibly compressed stream.
      rawStream = stethoManager.interpretResponseStream(rawStream);
      InputStream decompressedStream = applyDecompressionIfApplicable(conn, rawStream);
      if (decompressedStream != null) {
        copy(decompressedStream, out, new byte[1024]);
      }
    } finally {
      if (rawStream != null) {
        rawStream.close();
      }
    }
    return new HttpResponse(conn.getResponseCode(), out.toByteArray());
  } finally {
    conn.disconnect();
  }
}
 
Example #7
Source File: OFAgentWebResourceTest.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Tests updating an OFAgent with PUT.
 */
@Test
public void testOFAgentUpdate() {
    expect(mockOFAgentService.agent(eq(NETWORK))).andReturn(OF_AGENT).anyTimes();
    replay(mockOFAgentService);

    mockOFAgentAdminService.updateAgent(anyObject());
    expectLastCall().anyTimes();
    replay(mockOFAgentAdminService);

    InputStream jsonStream = OFAgentWebResourceTest.class
            .getResourceAsStream("put-ofagent-update.json");
    assertNotNull("put-ofagent-update.json is null", jsonStream);
    WebTarget wt = target();
    Response response = wt.path("service/ofagent-update")
            .request(MediaType.APPLICATION_JSON_TYPE)
            .put(Entity.json(jsonStream));
    assertThat(response.getStatus(), is(HttpURLConnection.HTTP_OK));
    assertThat(response.readEntity(String.class), containsString("OFAgent updated"));

    verify(mockOFAgentService);
    verify(mockOFAgentAdminService);

}
 
Example #8
Source File: DockerAction.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public List<DockerContainer> getContainers() {
    try {
        JSONArray value = (JSONArray) doGetRequest("/containers/json?all=1",
                Collections.singleton(HttpURLConnection.HTTP_OK));
        List<DockerContainer> ret = new ArrayList<>(value.size());
        for (Object o : value) {
            JSONObject json = (JSONObject) o;
            String id = (String) json.get("Id");
            String image = (String) json.get("Image");
            String name = null;
            JSONArray names = (JSONArray) json.get("Names");
            if (names != null && !names.isEmpty()) {
                name = (String) names.get(0);
            }
            DockerContainer.Status status = DockerUtils.getContainerStatus((String) json.get("Status"));
            ret.add(new DockerContainer(instance, id, image, name, status));
        }
        return ret;
    } catch (DockerException ex) {
        LOGGER.log(Level.INFO, null, ex);
    }
    return Collections.emptyList();
}
 
Example #9
Source File: ConsentInformation.java    From googleads-consent-sdk-android with Apache License 2.0 6 votes vote down vote up
private ConsentInfoUpdateResponse makeConsentLookupRequest(String urlString) {
    try {
        URL url = new URL(urlString);

        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            String responseString = readStream(urlConnection.getInputStream());
            urlConnection.disconnect();
            consentInformation.updateConsentData(responseString, publisherIds);
            return new ConsentInfoUpdateResponse(true, UPDATE_SUCCESS);
        } else {
            return new ConsentInfoUpdateResponse(
                false, urlConnection.getResponseMessage());
        }
    } catch (Exception e) {
        return new ConsentInfoUpdateResponse(false, e.getLocalizedMessage());
    }
}
 
Example #10
Source File: CredentialsManagementServiceImpl.java    From enmasse with Apache License 2.0 6 votes vote down vote up
@Override
protected Future<OperationResult<List<CommonCredential>>> processReadCredentials(final DeviceKey key, final Span span) {

    return this.store.getCredentials(key, span.context())
            .<OperationResult<List<CommonCredential>>>map(r -> {

                if (r.isPresent()) {
                    var result = r.get();
                    return OperationResult.ok(
                            HTTP_OK,
                            result.getCredentials(),
                            this.ttl,
                            result.getResourceVersion());
                } else {
                    return empty(HTTP_NOT_FOUND);
                }

            })

            .otherwise(err -> empty(HttpURLConnection.HTTP_INTERNAL_ERROR));

}
 
Example #11
Source File: CloudBlobContainer.java    From azure-storage-android with Apache License 2.0 6 votes vote down vote up
/**
 * Deletes the container if it exists using the specified request options and operation context.
 * 
 * @param accessCondition
 *            An {@link AccessCondition} object that represents the access conditions for the container.
 * @param options
 *            A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying
 *            <code>null</code> will use the default request options from the associated service client (
 *            {@link CloudBlobClient}).
 * @param opContext
 *            An {@link OperationContext} object that represents the context for the current operation. This object
 *            is used to track requests to the storage service, and to provide additional runtime information about
 *            the operation.
 * 
 * @return <code>true</code> if the container existed and was deleted; otherwise, <code>false</code>.
 * 
 * @throws StorageException
 *             If a storage service error occurred.
 */
@DoesServiceRequest
public boolean deleteIfExists(AccessCondition accessCondition, BlobRequestOptions options,
        OperationContext opContext) throws StorageException {
    options = BlobRequestOptions.populateAndApplyDefaults(options, BlobType.UNSPECIFIED, this.blobServiceClient);

    boolean exists = this.exists(true /* primaryOnly */, accessCondition, options, opContext);
    if (exists) {
        try {
            this.delete(accessCondition, options, opContext);
            return true;
        }
        catch (StorageException e) {
            if (e.getHttpStatusCode() == HttpURLConnection.HTTP_NOT_FOUND
                    && StorageErrorCodeStrings.CONTAINER_NOT_FOUND.equals(e.getErrorCode())) {
                return false;
            }
            else {
                throw e;
            }
        }
    }
    else {
        return false;
    }
}
 
Example #12
Source File: EventBusAuthenticationServiceTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that an authentication request is sent via the vert.x event bus and the failure reply,
 * containing an invalid error code, is passed on to the handler of the <code>authenticate</code> method
 * as an internal error.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testAuthenticateFailureInvalidStatusCode(final VertxTestContext ctx) {

    final String failureMessage = "failureMessage";

    authRequestConsumer = vertx.eventBus().consumer(AuthenticationConstants.EVENT_BUS_ADDRESS_AUTHENTICATION_IN, message -> {
        message.fail(200, failureMessage);
    });

    final EventBusAuthenticationService eventBusAuthService = new EventBusAuthenticationService(vertx, authTokenHelperForValidating);
    eventBusAuthService.authenticate(new JsonObject(), ctx.failing(t -> {
        ctx.verify(() -> {
            assertThat(t).isInstanceOf(ServerErrorException.class);
            assertThat(((ServiceInvocationException) t).getErrorCode()).isEqualTo(HttpURLConnection.HTTP_INTERNAL_ERROR);
            assertThat(t.getMessage()).isEqualTo(failureMessage);
        });
        ctx.completeNow();
    }));
}
 
Example #13
Source File: BaseImageDownloader.java    From mobile-manager-tool with MIT License 6 votes vote down vote up
/**
 * Retrieves {@link java.io.InputStream} of image by URI (image is located in the network).
 *
 * @param imageUri Image URI
 * @param extra    Auxiliary object which was passed to {@link com.nostra13.universalimageloader.core.DisplayImageOptions.Builder#extraForDownloader(Object)
 *                 DisplayImageOptions.extraForDownloader(Object)}; can be null
 * @return {@link java.io.InputStream} of image
 * @throws java.io.IOException if some I/O error occurs during network request or if no InputStream could be created for
 *                     URL.
 */
protected InputStream getStreamFromNetwork(String imageUri, Object extra) throws IOException {
	HttpURLConnection conn = createConnection(imageUri, extra);

	int redirectCount = 0;
	while (conn.getResponseCode() / 100 == 3 && redirectCount < MAX_REDIRECT_COUNT) {
		conn = createConnection(conn.getHeaderField("Location"), extra);
		redirectCount++;
	}

	InputStream imageStream;
	try {
		imageStream = conn.getInputStream();
	} catch (IOException e) {
		// Read all data to allow reuse connection (http://bit.ly/1ad35PY)
		IoUtils.readAndCloseStream(conn.getErrorStream());
		throw e;
	}
	return new ContentLengthInputStream(new BufferedInputStream(imageStream, BUFFER_SIZE), conn.getContentLength());
}
 
Example #14
Source File: ImagesService.java    From FlyCms with MIT License 6 votes vote down vote up
/**
 * @param fileUrl
 *            文件来源地址
 * @param savePath
 *            文件保存地址
 * @return
 */
public static boolean saveUrlAs(String fileUrl, String savePath) {
	try {
		URL url = new URL(fileUrl);
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		DataInputStream in = new DataInputStream(connection.getInputStream());
		DataOutputStream out = new DataOutputStream(new FileOutputStream(savePath));
		byte[] buffer = new byte[4096];
		int count = 0;
		while ((count = in.read(buffer)) > 0) {
			out.write(buffer, 0, count);
		}
		out.close();
		in.close();
		connection.disconnect();
		return true;

	} catch (Exception e) {
		return false;
	}
}
 
Example #15
Source File: BaseImageDownloader.java    From MiBandDecompiled with Apache License 2.0 6 votes vote down vote up
protected InputStream getStreamFromNetwork(String s, Object obj)
{
    HttpURLConnection httpurlconnection = createConnection(s, obj);
    for (int i = 0; httpurlconnection.getResponseCode() / 100 == 3 && i < 5; i++)
    {
        httpurlconnection = createConnection(httpurlconnection.getHeaderField("Location"), obj);
    }

    InputStream inputstream;
    try
    {
        inputstream = httpurlconnection.getInputStream();
    }
    catch (IOException ioexception)
    {
        IoUtils.readAndCloseStream(httpurlconnection.getErrorStream());
        throw ioexception;
    }
    return new ContentLengthInputStream(new BufferedInputStream(inputstream, 32768), httpurlconnection.getContentLength());
}
 
Example #16
Source File: ScepClient.java    From xipki with Apache License 2.0 6 votes vote down vote up
@Override
protected ScepHttpResponse httpGet(String url) throws ScepClientException {
  Args.notNull(url, "url");
  try {
    HttpURLConnection httpConn = openHttpConn(new URL(url));
    if (httpConn instanceof HttpsURLConnection) {
      if (sslSocketFactory != null) {
        ((HttpsURLConnection) httpConn).setSSLSocketFactory(sslSocketFactory);
      }
      if (hostnameVerifier != null) {
        ((HttpsURLConnection) httpConn).setHostnameVerifier(hostnameVerifier);
      }
    }

    httpConn.setRequestMethod("GET");
    return parseResponse(httpConn);
  } catch (IOException ex) {
    throw new ScepClientException(ex);
  }
}
 
Example #17
Source File: TableBatchOperationTests.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
@Test
public void testBatchSizeOver4mb() {
    TableRequestOptions options = new TableRequestOptions();
    options.setTablePayloadFormat(TablePayloadFormat.Json);

    TableBatchOperation batch = new TableBatchOperation();
    byte[] datArr = new byte[1024 * 128];
    Random rand = new Random();
    rand.nextBytes(datArr);

    // Each entity is approx 128kb, meaning ~32 entities will result in a request over 4mb.
    try {
        for (int m = 0; m < 32; m++) {
            Class1 ref = new Class1();

            ref.setA("foo_A");
            ref.setB("foo_B");
            ref.setC("foo_C");
            ref.setD(datArr);
            ref.setPartitionKey("jxscl_odata");
            ref.setRowKey(UUID.randomUUID().toString());
            batch.insert(ref);
        }

        this.table.execute(batch, options, null);
        fail();
    }
    catch (StorageException ex) {
        assertEquals(ex.getHttpStatusCode(), HttpURLConnection.HTTP_ENTITY_TOO_LARGE);
        assertEquals(ex.getErrorCode(), StorageErrorCodeStrings.REQUEST_BODY_TOO_LARGE);
        assertTrue(ex.getMessage().startsWith(
                "The request body is too large and exceeds the maximum permissible limit."));
    }
}
 
Example #18
Source File: Processor.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
private HttpURLConnection openConnection ( final URL url ) throws IOException
{
    final String host = this.properties.getProperty ( "local.proxy.host" );
    final String port = this.properties.getProperty ( "local.proxy.port" );

    if ( host != null && port != null && !host.isEmpty () && !port.isEmpty () )
    {
        final Proxy proxy = new Proxy ( Type.HTTP, new InetSocketAddress ( host, Integer.parseInt ( port ) ) );
        return (HttpURLConnection)url.openConnection ( proxy );
    }
    else
    {
        return (HttpURLConnection)url.openConnection ();
    }
}
 
Example #19
Source File: AbstractVertxBasedMqttProtocolAdapter.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Forwards a message to the AMQP Messaging Network.
 *
 * @param ctx The context in which the MQTT message has been published.
 * @param resource The resource that the message should be forwarded to.
 * @param message The message to send.
 * @return A future indicating the outcome of the operation.
 *         <p>
 *         The future will succeed if the message has been forwarded successfully.
 *         Otherwise the future will fail with a {@link ServiceInvocationException}.
 * @throws NullPointerException if any of context, resource or payload is {@code null}.
 * @throws IllegalArgumentException if the payload is empty.
 */
public final Future<Void> uploadMessage(
        final MqttContext ctx,
        final ResourceIdentifier resource,
        final MqttPublishMessage message) {

    Objects.requireNonNull(ctx);
    Objects.requireNonNull(resource);
    Objects.requireNonNull(message);

    switch (MetricsTags.EndpointType.fromString(resource.getEndpoint())) {
    case TELEMETRY:
        return uploadTelemetryMessage(
                ctx,
                resource.getTenantId(),
                resource.getResourceId(),
                message.payload());
    case EVENT:
        return uploadEventMessage(
                ctx,
                resource.getTenantId(),
                resource.getResourceId(),
                message.payload());
    case COMMAND:
        return uploadCommandResponseMessage(ctx, resource);
    default:
        return Future
                .failedFuture(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST, "unsupported endpoint"));
    }

}
 
Example #20
Source File: HttpHelper.java    From Study_Android_Demo with Apache License 2.0 5 votes vote down vote up
public static URI unredirect(URI uri) throws IOException {
  if (!REDIRECTOR_DOMAINS.contains(uri.getHost())) {
    return uri;
  }
  URL url = uri.toURL();
  HttpURLConnection connection = safelyOpenConnection(url);
  connection.setInstanceFollowRedirects(false);
  connection.setDoInput(false);
  connection.setRequestMethod("HEAD");
  connection.setRequestProperty("User-Agent", "ZXing (Android)");
  try {
    int responseCode = safelyConnect(connection);
    switch (responseCode) {
      case HttpURLConnection.HTTP_MULT_CHOICE:
      case HttpURLConnection.HTTP_MOVED_PERM:
      case HttpURLConnection.HTTP_MOVED_TEMP:
      case HttpURLConnection.HTTP_SEE_OTHER:
      case 307: // No constant for 307 Temporary Redirect ?
        String location = connection.getHeaderField("Location");
        if (location != null) {
          try {
            return new URI(location);
          } catch (URISyntaxException e) {
            // nevermind
          }
        }
    }
    return uri;
  } finally {
    connection.disconnect();
  }
}
 
Example #21
Source File: NetworkUtils.java    From OpenMapKitAndroid with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static HttpURLConnection getHttpURLConnection(final URL url, final Cache cache, final SSLSocketFactory sslSocketFactory) {
    OkHttpClient client = new OkHttpClient();
    if (cache != null) {
        client.setCache(cache);
    }
    if (sslSocketFactory != null) {
        client.setSslSocketFactory(sslSocketFactory);
    }
    HttpURLConnection connection = new OkUrlFactory(client).open(url);
    connection.setRequestProperty("User-Agent", MapboxUtils.getUserAgent());
    return connection;
}
 
Example #22
Source File: PsLinkedin.java    From takes with MIT License 5 votes vote down vote up
@Override
public Opt<Identity> enter(final Request request)
    throws IOException {
    final Href href = new RqHref.Base(request).href();
    final Iterator<String> code = href.param(PsLinkedin.CODE).iterator();
    if (!code.hasNext()) {
        throw new HttpException(
            HttpURLConnection.HTTP_BAD_REQUEST,
            "code is not provided by LinkedIn"
        );
    }
    return new Opt.Single<>(
        this.fetch(this.token(href.toString(), code.next()))
    );
}
 
Example #23
Source File: UrlResource.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Override
public InputStream getInputStream() throws IOException {
    URLConnection con = this.url.openConnection();
    useCachesIfNecessary(con);
    try {
        return con.getInputStream();
    } catch (IOException ex) {
        // Close the HTTP connection (if applicable).
        if (con instanceof HttpURLConnection) {
            ((HttpURLConnection) con).disconnect();
        }
        throw ex;
    }
}
 
Example #24
Source File: RestaurantAppDockerIT.java    From Mastering-Microservices-with-Java with MIT License 5 votes vote down vote up
/**
 *
 * @throws IOException
 */
@Test
public void testConnection() throws IOException {
    String baseUrl = System.getProperty("service.url");
    URL serviceUrl = new URL(baseUrl + "v1/restaurants/1");
    HttpURLConnection connection = (HttpURLConnection) serviceUrl.openConnection();
    int responseCode = connection.getResponseCode();
    assertEquals(200, responseCode);
}
 
Example #25
Source File: HttpRequestUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void shouldReturnStatusOKWhenSendGetRequestTimeoutSet() throws IOException, InterruptedException, URISyntaxException {
    HttpRequest request = HttpRequest.newBuilder()
        .uri(new URI("https://postman-echo.com/get"))
        .timeout(Duration.of(10, SECONDS))
        .GET()
        .build();

    HttpResponse<String> response = HttpClient.newHttpClient()
        .send(request, HttpResponse.BodyHandlers.ofString());

    assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
}
 
Example #26
Source File: WelcomeActivity.java    From iMoney with Apache License 2.0 5 votes vote down vote up
/**
 * 下载对应url下的apk文件
 */
private void downloadAPK() throws Exception {
    FileOutputStream fos = new FileOutputStream(apkFile);
    String path = updateInfo.apkUrl;
    URL url = new URL(path);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setConnectTimeout(5000);
    conn.setReadTimeout(5000);
    conn.setRequestMethod("GET");
    conn.connect();

    if (conn.getResponseCode() == 200) {
        InputStream is = conn.getInputStream();
        dialog.setMax(conn.getContentLength());
        byte[] buffer = new byte[1024];
        int len;
        while ((len = is.read(buffer)) != -1) {
            fos.write(buffer, 0, len);
            dialog.incrementProgressBy(len);
            Thread.sleep(2);
        }
        // 暂且使用throws的方式处理异常了
        is.close();
        fos.close();
    } else {
        handler.sendEmptyMessage(WHAT_DOWNLOAD_FAIL);
    }
    // 关闭连接
    conn.disconnect();
}
 
Example #27
Source File: SentinelUtils.java    From Natty with GNU General Public License v3.0 5 votes vote down vote up
private static HttpURLConnection getConnection(String url) throws IOException {
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setConnectTimeout(10 * 1000);
    conn.setReadTimeout(10 * 1000);
    conn.setDoOutput(true);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/json");
    return conn;
}
 
Example #28
Source File: MuchThreadDown.java    From cs-summary-reflection with Apache License 2.0 5 votes vote down vote up
/** 下载文件 */
public void download() throws Exception {
    // 连接资源
    URL url = new URL(path);

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("GET");
    connection.setConnectTimeout(10000);

    int code = connection.getResponseCode();
    if (code == 200) {
        // 获取资源大小
        int connectionLength = connection.getContentLength();
        System.out.println(connectionLength);
        // 在本地创建一个与资源同样大小的文件来占位
        RandomAccessFile randomAccessFile =
                new RandomAccessFile(new File(targetFilePath, getFileName(url)), "rw");
        randomAccessFile.setLength(connectionLength);
        /*
         * 将下载任务分配给每个线程
         */
        int blockSize = connectionLength / threadCount; // 计算每个线程理论上下载的数量.
        for (int threadId = 0; threadId < threadCount; threadId++) { // 为每个线程分配任务
            int startIndex = threadId * blockSize; // 线程开始下载的位置
            int endIndex = (threadId + 1) * blockSize - 1; // 线程结束下载的位置
            if (threadId == (threadCount - 1)) { // 如果是最后一个线程,将剩下的文件全部交给这个线程完成
                endIndex = connectionLength - 1;
            }

            new DownloadThread(threadId, startIndex, endIndex).start(); // 开启线程下载
        }
        randomAccessFile.close();
    }
}
 
Example #29
Source File: RestServerEndpointITCase.java    From flink with Apache License 2.0 5 votes vote down vote up
/**
 * Tests that files can be served with the {@link StaticFileServerHandler}.
 */
@Test
public void testStaticFileServerHandler() throws Exception {
	final File file = temporaryFolder.newFile();
	Files.write(file.toPath(), Collections.singletonList("foobar"));

	final URL url = new URL(serverEndpoint.getRestBaseUrl() + "/" + file.getName());
	final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
	connection.setRequestMethod("GET");
	final String fileContents = IOUtils.toString(connection.getInputStream());

	assertEquals("foobar", fileContents.trim());
}
 
Example #30
Source File: CloudBlobContainerTests.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
@Test
@Category({ DevFabricTests.class, DevStoreTests.class })
public void testCloudBlobContainerInvalidMetadata() throws StorageException{
    // test client-side fails correctly
    testMetadataFailures(this.container, null, "value1", true);
    testMetadataFailures(this.container, "", "value1", true);
    testMetadataFailures(this.container, " ", "value1", true);
    testMetadataFailures(this.container, "\n \t", "value1", true);

    testMetadataFailures(this.container, "key1", null, false);
    testMetadataFailures(this.container, "key1", "", false);
    testMetadataFailures(this.container, "key1", " ", false);
    testMetadataFailures(this.container, "key1", "\n \t", false);

    // test client can get empty metadata
    this.container.create();

    OperationContext opContext = new OperationContext();
    opContext.getSendingRequestEventHandler().addListener(new StorageEvent<SendingRequestEvent>() {
        // insert a metadata element with an empty value
        @Override
        public void eventOccurred(SendingRequestEvent eventArg) {
            HttpURLConnection request = (HttpURLConnection) eventArg.getConnectionObject();
            request.setRequestProperty(Constants.HeaderConstants.PREFIX_FOR_STORAGE_METADATA + "key1", "");
        }
    });
    this.container.uploadMetadata(null, null, opContext);

    this.container.downloadAttributes();
    assertEquals(1, this.container.getMetadata().size());
    assertEquals("", this.container.getMetadata().get("key1"));
}