当前位置: 首页>>代码示例>>Java>>正文


Java HttpURLConnection.setFixedLengthStreamingMode方法代码示例

本文整理汇总了Java中java.net.HttpURLConnection.setFixedLengthStreamingMode方法的典型用法代码示例。如果您正苦于以下问题:Java HttpURLConnection.setFixedLengthStreamingMode方法的具体用法?Java HttpURLConnection.setFixedLengthStreamingMode怎么用?Java HttpURLConnection.setFixedLengthStreamingMode使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在java.net.HttpURLConnection的用法示例。


在下文中一共展示了HttpURLConnection.setFixedLengthStreamingMode方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: testRewind

import java.net.HttpURLConnection; //导入方法依赖的package包/类
@SmallTest
@Feature({"Cronet"})
@CompareDefaultWithCronet
public void testRewind() throws Exception {
    // Post preserving redirect should fail.
    URL url = new URL(NativeTestServer.getRedirectToEchoBody());
    HttpURLConnection connection =
            (HttpURLConnection) url.openConnection();
    connection.setDoOutput(true);
    connection.setRequestMethod("POST");
    connection.setFixedLengthStreamingMode(TestUtil.UPLOAD_DATA.length);
    try {
        OutputStream out = connection.getOutputStream();
        out.write(TestUtil.UPLOAD_DATA);
    } catch (HttpRetryException e) {
        assertEquals("Cannot retry streamed Http body", e.getMessage());
    }
    connection.disconnect();
}
 
开发者ID:lizhangqu,项目名称:chromium-net-for-android,代码行数:20,代码来源:CronetFixedModeOutputStreamTest.java

示例2: writeRequestData

import java.net.HttpURLConnection; //导入方法依赖的package包/类
private static void writeRequestData(HttpURLConnection connection, byte[] postData)
    throws IOException {
  // According to the documentation at
  // http://developer.android.com/reference/java/net/HttpURLConnection.html
  // HttpURLConnection uses the GET method by default. It will use POST if setDoOutput(true) has
  // been called.
  connection.setDoOutput(true); // This makes it something other than a HTTP GET.
  // Write the data.
  connection.setFixedLengthStreamingMode(postData.length);
  BufferedOutputStream out = new BufferedOutputStream(connection.getOutputStream());
  try {
    out.write(postData, 0, postData.length);
    out.flush();
  } finally {
    out.close();
  }
}
 
开发者ID:mit-cml,项目名称:appinventor-extensions,代码行数:18,代码来源:Web.java

示例3: testOneMassiveWrite

import java.net.HttpURLConnection; //导入方法依赖的package包/类
@SmallTest
@Feature({"Cronet"})
@OnlyRunNativeCronet
// Regression testing for crbug.com/618872.
public void testOneMassiveWrite() throws Exception {
    String path = "/simple.txt";
    URL url = new URL(QuicTestServer.getServerURL() + path);
    HttpURLConnection connection =
            (HttpURLConnection) mTestFramework.mCronetEngine.openConnection(url);
    connection.setDoOutput(true);
    connection.setRequestMethod("POST");
    // Size is chosen so the last time mBuffer will be written 14831 bytes,
    // which is larger than the internal QUIC read buffer size of 14520.
    byte[] largeData = new byte[195055];
    Arrays.fill(largeData, "a".getBytes("UTF-8")[0]);
    connection.setFixedLengthStreamingMode(largeData.length);
    OutputStream out = connection.getOutputStream();
    // Write everything at one go, so the data is larger than the buffer
    // used in CronetFixedModeOutputStream.
    out.write(largeData);
    assertEquals(200, connection.getResponseCode());
    connection.disconnect();
}
 
开发者ID:lizhangqu,项目名称:chromium-net-for-android,代码行数:24,代码来源:QuicUploadTest.java

示例4: httpPost

import java.net.HttpURLConnection; //导入方法依赖的package包/类
public T httpPost(String jsonBody, Class<T> clazz) {
try {
    URL url = new URL(HTTP_PROTOCOL, LOCAL_HOST, HTTP_PORT,
	    USERS_SERVICE_ENDPOINT);
    httpConnection = (HttpURLConnection) url.openConnection();
    httpConnection.setRequestMethod(HttpRequestMethod.POST.toString());
    setConnectionParameters(httpConnection, HttpRequestMethod.POST);
    httpConnection
	    .setFixedLengthStreamingMode(jsonBody.getBytes().length);
    try (OutputStreamWriter out = new OutputStreamWriter(
	    httpConnection.getOutputStream())) {
	out.write(jsonBody);
    }
    StringBuilder sb = new StringBuilder();
    try (BufferedReader in = new BufferedReader(new InputStreamReader(
	    httpConnection.getInputStream()))) {
	String inputLine;
	while ((inputLine = in.readLine()) != null) {
	    sb.append(inputLine);
	}
    }
    return new Gson().fromJson(sb.toString(), clazz);
} catch (IOException e) {
    log.error(e);
}
return null;
   }
 
开发者ID:ahmed-ebaid,项目名称:invest-stash-rest,代码行数:28,代码来源:HttpRequests.java

示例5: interruptWritingRequestBody

import java.net.HttpURLConnection; //导入方法依赖的package包/类
@Test public void interruptWritingRequestBody() throws Exception {
  int requestBodySize = 2 * 1024 * 1024; // 2 MiB

  server.enqueue(new MockResponse()
      .throttleBody(64 * 1024, 125, TimeUnit.MILLISECONDS)); // 500 Kbps
  server.start();

  HttpURLConnection connection = new OkUrlFactory(client).open(server.url("/").url());
  disconnectLater(connection, 500);

  connection.setDoOutput(true);
  connection.setFixedLengthStreamingMode(requestBodySize);
  OutputStream requestBody = connection.getOutputStream();
  byte[] buffer = new byte[1024];
  try {
    for (int i = 0; i < requestBodySize; i += buffer.length) {
      requestBody.write(buffer);
      requestBody.flush();
    }
    fail("Expected connection to be closed");
  } catch (IOException expected) {
  }

  connection.disconnect();
}
 
开发者ID:weiwenqiang,项目名称:GitHub,代码行数:26,代码来源:DisconnectTest.java

示例6: testFixedLengthStreamingModeLargeDataWriteOneByte

import java.net.HttpURLConnection; //导入方法依赖的package包/类
@SmallTest
@Feature({"Cronet"})
@CompareDefaultWithCronet
public void testFixedLengthStreamingModeLargeDataWriteOneByte()
        throws Exception {
    URL url = new URL(NativeTestServer.getEchoBodyURL());
    HttpURLConnection connection =
            (HttpURLConnection) url.openConnection();
    connection.setDoOutput(true);
    connection.setRequestMethod("POST");
    byte[] largeData = TestUtil.getLargeData();
    connection.setFixedLengthStreamingMode(largeData.length);
    OutputStream out = connection.getOutputStream();
    for (int i = 0; i < largeData.length; i++) {
        // Write one byte at a time.
        out.write(largeData[i]);
    }
    assertEquals(200, connection.getResponseCode());
    assertEquals("OK", connection.getResponseMessage());
    TestUtil.checkLargeData(TestUtil.getResponseAsString(connection));
    connection.disconnect();
}
 
开发者ID:lizhangqu,项目名称:chromium-net-for-android,代码行数:23,代码来源:CronetFixedModeOutputStreamTest.java

示例7: doUpload

import java.net.HttpURLConnection; //导入方法依赖的package包/类
private void doUpload(TransferKind uploadKind, WriteKind writeKind) throws Exception {
  int n = 512 * 1024;
  server.setBodyLimit(0);
  server.enqueue(new MockResponse());

  HttpURLConnection conn = urlFactory.open(server.url("/").url());
  conn.setDoOutput(true);
  conn.setRequestMethod("POST");
  if (uploadKind == TransferKind.CHUNKED) {
    conn.setChunkedStreamingMode(-1);
  } else {
    conn.setFixedLengthStreamingMode(n);
  }
  OutputStream out = conn.getOutputStream();
  if (writeKind == WriteKind.BYTE_BY_BYTE) {
    for (int i = 0; i < n; ++i) {
      out.write('x');
    }
  } else {
    byte[] buf = new byte[writeKind == WriteKind.SMALL_BUFFERS ? 256 : 64 * 1024];
    Arrays.fill(buf, (byte) 'x');
    for (int i = 0; i < n; i += buf.length) {
      out.write(buf, 0, Math.min(buf.length, n - i));
    }
  }
  out.close();
  assertEquals(200, conn.getResponseCode());
  RecordedRequest request = server.takeRequest();
  assertEquals(n, request.getBodySize());
  if (uploadKind == TransferKind.CHUNKED) {
    assertTrue(request.getChunkSizes().size() > 0);
  } else {
    assertTrue(request.getChunkSizes().isEmpty());
  }
}
 
开发者ID:weiwenqiang,项目名称:GitHub,代码行数:36,代码来源:URLConnectionTest.java

示例8: disconnectRequestHalfway

import java.net.HttpURLConnection; //导入方法依赖的package包/类
@Test public void disconnectRequestHalfway() throws IOException {
  server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_DURING_REQUEST_BODY));
  // Limit the size of the request body that the server holds in memory to an arbitrary
  // 3.5 MBytes so this test can pass on devices with little memory.
  server.setBodyLimit(7 * 512 * 1024);

  HttpURLConnection connection = (HttpURLConnection) server.url("/").url().openConnection();
  connection.setRequestMethod("POST");
  connection.setDoOutput(true);
  connection.setFixedLengthStreamingMode(1024 * 1024 * 1024); // 1 GB
  connection.connect();
  OutputStream out = connection.getOutputStream();

  byte[] data = new byte[1024 * 1024];
  int i;
  for (i = 0; i < 1024; i++) {
    try {
      out.write(data);
      out.flush();
    } catch (IOException e) {
      break;
    }
  }
  assertEquals(512f, i, 10f); // Halfway +/- 1%
}
 
开发者ID:weiwenqiang,项目名称:GitHub,代码行数:26,代码来源:MockWebServerTest.java

示例9: makeConnection

import java.net.HttpURLConnection; //导入方法依赖的package包/类
/**
 * Configures a connection and opens it.
 *
 * @param url The url to connect to.
 * @param postBody The body data for a POST request.
 * @param position The byte offset of the requested data.
 * @param length The length of the requested data, or {@link C#LENGTH_UNBOUNDED}.
 * @param allowGzip Whether to allow the use of gzip.
 * @param followRedirects Whether to follow redirects.
 */
private HttpURLConnection makeConnection(URL url, byte[] postBody, long position,
    long length, boolean allowGzip, boolean followRedirects) throws IOException {
  HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  connection.setConnectTimeout(connectTimeoutMillis);
  connection.setReadTimeout(readTimeoutMillis);
  synchronized (requestProperties) {
    for (Map.Entry<String, String> property : requestProperties.entrySet()) {
      connection.setRequestProperty(property.getKey(), property.getValue());
    }
  }
  if (!(position == 0 && length == C.LENGTH_UNBOUNDED)) {
    String rangeRequest = "bytes=" + position + "-";
    if (length != C.LENGTH_UNBOUNDED) {
      rangeRequest += (position + length - 1);
    }
    connection.setRequestProperty("Range", rangeRequest);
  }
  connection.setRequestProperty("User-Agent", userAgent);
  if (!allowGzip) {
    connection.setRequestProperty("Accept-Encoding", "identity");
  }
  connection.setInstanceFollowRedirects(followRedirects);
  connection.setDoOutput(postBody != null);
  if (postBody != null) {
    connection.setFixedLengthStreamingMode(postBody.length);
    connection.connect();
    OutputStream os = connection.getOutputStream();
    os.write(postBody);
    os.close();
  } else {
    connection.connect();
  }
  return connection;
}
 
开发者ID:MLNO,项目名称:airgram,代码行数:45,代码来源:DefaultHttpDataSource.java

示例10: testConnectBeforeWrite

import java.net.HttpURLConnection; //导入方法依赖的package包/类
@SmallTest
@Feature({"Cronet"})
@CompareDefaultWithCronet
public void testConnectBeforeWrite() throws Exception {
    URL url = new URL(NativeTestServer.getEchoBodyURL());
    HttpURLConnection connection =
            (HttpURLConnection) url.openConnection();
    connection.setDoOutput(true);
    connection.setRequestMethod("POST");
    connection.setFixedLengthStreamingMode(TestUtil.UPLOAD_DATA.length);
    OutputStream out = connection.getOutputStream();
    connection.connect();
    out.write(TestUtil.UPLOAD_DATA);
    assertEquals(200, connection.getResponseCode());
    assertEquals("OK", connection.getResponseMessage());
    assertEquals(TestUtil.UPLOAD_DATA_STRING, TestUtil.getResponseAsString(connection));
    connection.disconnect();
}
 
开发者ID:lizhangqu,项目名称:chromium-net-for-android,代码行数:19,代码来源:CronetFixedModeOutputStreamTest.java

示例11: generateConnection

import java.net.HttpURLConnection; //导入方法依赖的package包/类
public HttpURLConnection generateConnection() throws IOException {
	URL obj = new URL(getUrl());
	HttpURLConnection con = (HttpURLConnection) obj.openConnection();
	con.setInstanceFollowRedirects(followRedirects);
	con.setRequestMethod(method);
	if (timeout != null) {
		con.setConnectTimeout(timeout);
	}
	if (fixedSize) {
		con.setFixedLengthStreamingMode(body.toString().length());
	}
	if (disableSecurity && con instanceof HttpsURLConnection) {
		applyDisableSecurity((HttpsURLConnection) con);
	}
	setHeaders(con);
	setBody(con);
	return con;
}
 
开发者ID:luanpotter,项目名称:http-facade,代码行数:19,代码来源:HttpFacade.java

示例12: testInputStreamReadOneByte

import java.net.HttpURLConnection; //导入方法依赖的package包/类
@SmallTest
@Feature({"Cronet"})
@CompareDefaultWithCronet
public void testInputStreamReadOneByte() throws Exception {
    URL url = new URL(NativeTestServer.getEchoBodyURL());
    final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    // Make the server echo a large request body, so it exceeds the internal
    // read buffer.
    connection.setDoOutput(true);
    connection.setRequestMethod("POST");
    byte[] largeData = TestUtil.getLargeData();
    connection.setFixedLengthStreamingMode(largeData.length);
    connection.getOutputStream().write(largeData);
    InputStream in = connection.getInputStream();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    int b;
    while ((b = in.read()) != -1) {
        out.write(b);
    }

    // All data has been read. Try reading beyond what is available should give -1.
    assertEquals(-1, in.read());
    assertEquals(200, connection.getResponseCode());
    assertEquals("OK", connection.getResponseMessage());
    String responseData = new String(out.toByteArray());
    TestUtil.checkLargeData(responseData);
}
 
开发者ID:lizhangqu,项目名称:chromium-net-for-android,代码行数:28,代码来源:CronetHttpURLConnectionTest.java

示例13: testFixedLengthStreamingModeZeroContentLength

import java.net.HttpURLConnection; //导入方法依赖的package包/类
@SmallTest
@Feature({"Cronet"})
@CompareDefaultWithCronet
public void testFixedLengthStreamingModeZeroContentLength() throws Exception {
    // Check content length is set.
    URL echoLength = new URL(NativeTestServer.getEchoHeaderURL("Content-Length"));
    HttpURLConnection connection1 =
            (HttpURLConnection) echoLength.openConnection();
    connection1.setDoOutput(true);
    connection1.setRequestMethod("POST");
    connection1.setFixedLengthStreamingMode(0);
    assertEquals(200, connection1.getResponseCode());
    assertEquals("OK", connection1.getResponseMessage());
    assertEquals("0", TestUtil.getResponseAsString(connection1));
    connection1.disconnect();

    // Check body is empty.
    URL echoBody = new URL(NativeTestServer.getEchoBodyURL());
    HttpURLConnection connection2 =
            (HttpURLConnection) echoBody.openConnection();
    connection2.setDoOutput(true);
    connection2.setRequestMethod("POST");
    connection2.setFixedLengthStreamingMode(0);
    assertEquals(200, connection2.getResponseCode());
    assertEquals("OK", connection2.getResponseMessage());
    assertEquals("", TestUtil.getResponseAsString(connection2));
    connection2.disconnect();
}
 
开发者ID:lizhangqu,项目名称:chromium-net-for-android,代码行数:29,代码来源:CronetFixedModeOutputStreamTest.java

示例14: append

import java.net.HttpURLConnection; //导入方法依赖的package包/类
/**
 * curl -i -X POST
 * "http://<HOST>:<PORT>/webhdfs/v1/<PATH>?op=APPEND[&buffersize=<INT>]"
 *
 * @param path
 * @param is
 * @return
 * @throws MalformedURLException
 * @throws IOException
 * @throws AuthenticationException
 */
public String append(String path, InputStream is)
        throws MalformedURLException, IOException, AuthenticationException {
    String resp = null;
    ensureValidToken();

    String redirectUrl = null;
    HttpURLConnection conn = authenticatedURL.openConnection(
            new URL(new URL(httpfsUrl), MessageFormat.format(
                    "/webhdfs/v1/{0}?op=APPEND", path)), token);
    conn.setRequestMethod("POST");
    conn.setInstanceFollowRedirects(false);
    conn.connect();
    logger.info("Location:" + conn.getHeaderField("Location"));
    resp = result(conn, true);
    if (conn.getResponseCode() == 307)
        redirectUrl = conn.getHeaderField("Location");
    conn.disconnect();

    if (redirectUrl != null) {
        conn = authenticatedURL.openConnection(new URL(redirectUrl), token);
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setRequestProperty("Content-Type", "application/octet-stream");
        // conn.setRequestProperty("Transfer-Encoding", "chunked");
        final int _SIZE = is.available();
        conn.setRequestProperty("Content-Length", "" + _SIZE);
        conn.setFixedLengthStreamingMode(_SIZE);
        conn.connect();
        OutputStream os = conn.getOutputStream();
        copy(is, os);
        // Util.copyStream(is, os);
        is.close();
        os.close();
        resp = result(conn, true);
        conn.disconnect();
    }

    return resp;
}
 
开发者ID:Transwarp-DE,项目名称:Transwarp-Sample-Code,代码行数:53,代码来源:KerberosWebHDFSConnection2.java

示例15: test

import java.net.HttpURLConnection; //导入方法依赖的package包/类
void test(String[] args) throws IOException {
    HttpServer httpServer = startHttpServer();
    int port = httpServer.getAddress().getPort();
    try {
        URL url = new URL("http://localhost:" + port + "/flis/");
        HttpURLConnection uc = (HttpURLConnection)url.openConnection();
        uc.setDoOutput(true);
        uc.setRequestMethod("POST");
        uc.setFixedLengthStreamingMode(POST_SIZE);
        OutputStream os = uc.getOutputStream();

        /* create a 32K byte array with data to POST */
        int thirtyTwoK = 32 * 1024;
        byte[] ba = new byte[thirtyTwoK];
        for (int i =0; i<thirtyTwoK; i++)
            ba[i] = (byte)i;

        long times = POST_SIZE / thirtyTwoK;
        for (int i=0; i<times; i++) {
            os.write(ba);
        }

        os.close();
        InputStream is = uc.getInputStream();
        while(is.read(ba) != -1);
        is.close();

        pass();
    } finally {
        httpServer.stop(0);
    }
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:33,代码来源:FixedLengthInputStream.java


注:本文中的java.net.HttpURLConnection.setFixedLengthStreamingMode方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。