@Override
 public OutputStream get() {
   String expanded = repositoryURL.toString() + "/repo/sendobject";
   try {
     HttpURLConnection connection = (HttpURLConnection) new URL(expanded).openConnection();
     connection.setDoOutput(true);
     connection.setDoInput(true);
     connection.setUseCaches(false);
     connection.setRequestMethod("POST");
     connection.setChunkedStreamingMode(4096);
     connection.setRequestProperty("content-length", "-1");
     connection.setRequestProperty("content-encoding", "gzip");
     OutputStream out = connection.getOutputStream();
     final ReportingOutputStream rout =
         HttpUtils.newReportingOutputStream(connection, out, true);
     return new FilterOutputStream(rout) {
       @Override
       public void close() throws IOException {
         super.close();
         compressedSize += ((ReportingOutputStream) super.out).compressedSize();
         uncompressedSize += ((ReportingOutputStream) super.out).unCompressedSize();
       }
     };
   } catch (Exception e) {
     throw Throwables.propagate(e);
   }
 }
Example #2
0
  static void setContentTypeAndLengthForStreaming(
      HttpURLConnection connection, Request request, boolean compress) {

    long length;

    if (request.payload instanceof File) {
      length = compress ? -1L : ((File) request.payload).length();
    } else if (request.payload instanceof InputStream) {
      length = -1L;
    } else {
      throw new IllegalStateException();
    }

    if (length > Integer.MAX_VALUE) {
      length = -1L; // use chunked streaming mode
    }

    WebbUtils.ensureRequestProperty(connection, Const.HDR_CONTENT_TYPE, Const.APP_BINARY);
    if (length < 0) {
      connection.setChunkedStreamingMode(-1); // use default chunk size
      if (compress) {
        connection.setRequestProperty(Const.HDR_CONTENT_ENCODING, "gzip");
      }
    } else {
      connection.setFixedLengthStreamingMode((int) length);
    }
  }
  void prepareRequest(HttpURLConnection connection, Request request) throws IOException {
    // HttpURLConnection artificially restricts request method
    try {
      connection.setRequestMethod(request.getMethod());
    } catch (ProtocolException e) {
      try {
        methodField.set(connection, request.getMethod());
      } catch (IllegalAccessException e1) {
        throw RetrofitError.unexpectedError(request.getUrl(), e1);
      }
    }

    connection.setDoInput(true);

    for (Header header : request.getHeaders()) {
      connection.addRequestProperty(header.getName(), header.getValue());
    }

    TypedOutput body = request.getBody();
    if (body != null) {
      connection.setDoOutput(true);
      connection.addRequestProperty("Content-Type", body.mimeType());
      long length = body.length();
      if (length != -1) {
        connection.setFixedLengthStreamingMode((int) length);
        connection.addRequestProperty("Content-Length", String.valueOf(length));
      } else {
        connection.setChunkedStreamingMode(CHUNK_SIZE);
      }
      body.writeTo(connection.getOutputStream());
    }
  }
  @Override
  public void setHeaders(
      List<NameValue> requestHeaders, boolean isFixedLengthStreamingMode, long totalBodyBytes)
      throws IOException {

    if (isFixedLengthStreamingMode) {
      if (android.os.Build.VERSION.SDK_INT >= 19) {
        mConnection.setFixedLengthStreamingMode(totalBodyBytes);

      } else {
        if (totalBodyBytes > Integer.MAX_VALUE)
          throw new RuntimeException(
              "You need Android API version 19 or newer to "
                  + "upload more than 2GB in a single request using "
                  + "fixed size content length. Try switching to "
                  + "chunked mode instead, but make sure your server side supports it!");

        mConnection.setFixedLengthStreamingMode((int) totalBodyBytes);
      }
    } else {
      mConnection.setChunkedStreamingMode(0);
    }

    for (final NameValue param : requestHeaders) {
      mConnection.setRequestProperty(param.getName(), param.getValue());
    }
  }
  public static final HTTPStream createHTTPStream(
      String address,
      boolean isPost,
      byte[] postData,
      String headers,
      int timeOutMs,
      java.lang.StringBuffer responseHeaders) {
    try {
      HttpURLConnection connection = (HttpURLConnection) (new URL(address).openConnection());

      if (connection != null) {
        try {
          if (isPost) {
            connection.setConnectTimeout(timeOutMs);
            connection.setDoOutput(true);
            connection.setChunkedStreamingMode(0);

            OutputStream out = connection.getOutputStream();
            out.write(postData);
            out.flush();
          }

          return new HTTPStream(connection);
        } catch (Throwable e) {
          connection.disconnect();
        }
      }
    } catch (Throwable e) {
    }

    return null;
  }
 /**
  * 根据 url获取HttpURLConnection 对象
  *
  * @param SERVER_URL API的地址
  * @return
  */
 private HttpURLConnection getConnection(String SERVER_URL) {
   HttpURLConnection connection = null;
   // 初始化connection
   try {
     // 根据地址创建URL对象
     URL url = new URL(SERVER_URL);
     // 根据URL对象打开链接
     connection = (HttpURLConnection) url.openConnection();
     // 设置请求的方式
     connection.setRequestMethod(REQUEST_MOTHOD);
     // 发送POST请求必须设置允许输入,默认为true
     connection.setDoInput(true);
     // 发送POST请求必须设置允许输出
     connection.setDoOutput(true);
     // 设置不使用缓存
     connection.setUseCaches(false);
     // 设置请求的超时时间
     connection.setReadTimeout(TIME_OUT);
     connection.setConnectTimeout(TIME_OUT);
     connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
     connection.setRequestProperty("Connection", "keep-alive");
     connection.setRequestProperty("Response-Type", "json");
     connection.setChunkedStreamingMode(0);
   } catch (IOException e) {
     e.printStackTrace();
   }
   return connection;
 }
Example #7
0
  public HTTPForm(URL form) throws IOException {
    connection = (HttpURLConnection) form.openConnection();
    connection.setChunkedStreamingMode(1024 * 64);
    connection.setDoOutput(true);
    connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

    this.out = connection.getOutputStream();
  }
Example #8
0
 public static void configConnection(HttpURLConnection connection) throws ProtocolException {
   connection.setConnectTimeout(5000);
   connection.setDoOutput(true);
   connection.setDoInput(true);
   connection.setChunkedStreamingMode(0);
   connection.setRequestMethod("POST");
   connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
   connection.setUseCaches(false);
 }
    public void uploadFile() throws IOException {
      String fileName = url.path().toString();

      DataOutputStream dos = null;
      String lineEnd = "\r\n";
      String twoHyphens = "--";
      String boundary = "*****";
      int bytesRead, bytesAvailable, bufferSize;
      byte[] buffer;
      int maxBufferSize = 1 * 1024 * 1024;

      FileInputStream fileInputStream = new FileInputStream(fileName);

      // Open a HTTP connection to the URL
      request = (HttpURLConnection) url.getUrl().openConnection();
      request.setDoInput(true); // Allow Inputs
      request.setDoOutput(true); // Allow Outputs
      request.setUseCaches(false); // Don't use a Cached Copy
      request.setChunkedStreamingMode(1024);
      request.setRequestMethod("POST");
      request.setRequestProperty("requestection", "Keep-Alive");
      request.setRequestProperty("ENCTYPE", "multipart/form-data");
      request.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
      request.setRequestProperty("uploaded_file", fileName);

      dos = new DataOutputStream(request.getOutputStream());
      dos.writeBytes(twoHyphens + boundary + lineEnd);
      dos.writeBytes(
          "Content-Disposition: form-data; name=\"file\";filename=\"" + fileName + "\"" + lineEnd);
      dos.writeBytes(lineEnd);
      // create a buffer of maximum size
      bytesAvailable = fileInputStream.available();

      bufferSize = Math.min(bytesAvailable, maxBufferSize);
      buffer = new byte[bufferSize];

      // read file and write it into form...
      bytesRead = fileInputStream.read(buffer, 0, bufferSize);

      while (bytesRead > 0) {

        dos.write(buffer, 0, bufferSize);
        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
      }

      // send multipart form data necesssary after file data...
      dos.writeBytes(lineEnd);
      dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
      // close the streams //
      fileInputStream.close();
      dos.flush();
      dos.close();
    }
Example #10
0
 /**
  * This method is responsible to prepare a PUT request to add documents to an existing collection.
  *
  * @param collection Collection name.
  * @param name The name of the collection.
  * @throws IOException Exception occurred.
  */
 public void initAdd(final String collection, final String name) throws IOException {
   URL url = new URL(mServers[0] + "/" + collection + "/" + name);
   HttpURLConnection conn = (HttpURLConnection) url.openConnection();
   conn.setDoOutput(true);
   conn.setRequestMethod(PUT);
   conn.setRequestProperty(CONTENT_TYPE_STRING, TEXT_XML);
   conn.setChunkedStreamingMode(1);
   OutputStream out = new BufferedOutputStream(conn.getOutputStream());
   mOutput = out;
   this.mConn = conn;
 }
Example #11
0
 /**
  * @param uploadUrl
  * @param srcPath
  * @return
  */
 public static String uploadFile(String uploadUrl, String srcPath) {
   String end = "\r\n";
   String twoHyphens = "--";
   String boundary = "******";
   try {
     URL url = new URL(uploadUrl);
     HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
     // 设置每次传输的流大小,可以有效防止手机因为内存不足崩溃
     // 此方法用于在预先不知道内容长度时启用没有进行内部缓冲的 HTTP 请求正文的流。
     httpURLConnection.setChunkedStreamingMode(128 * 1024); // 128K
     // 允许输入输出流
     httpURLConnection.setDoInput(true);
     httpURLConnection.setDoOutput(true);
     httpURLConnection.setUseCaches(false);
     // 使用POST方法
     httpURLConnection.setRequestMethod("POST");
     httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
     httpURLConnection.setRequestProperty("Charset", "UTF-8");
     httpURLConnection.setRequestProperty(
         "Content-Type", "multipart/form-data;boundary=" + boundary);
     DataOutputStream dos = new DataOutputStream(httpURLConnection.getOutputStream());
     dos.writeBytes(twoHyphens + boundary + end);
     dos.writeBytes(
         "Content-Disposition: form-data; name=\"myFile\"; filename=\""
             + URLEncoder.encode(srcPath.substring(srcPath.lastIndexOf("/") + 1))
             + "\""
             + end);
     dos.writeBytes(end);
     FileInputStream fis = new FileInputStream(srcPath);
     byte[] buffer = new byte[8192]; // 8k
     int count = 0;
     // 读取文件
     while ((count = fis.read(buffer)) != -1) {
       dos.write(buffer, 0, count);
     }
     fis.close();
     dos.writeBytes(end);
     dos.writeBytes(twoHyphens + boundary + twoHyphens + end);
     dos.flush();
     InputStream is = httpURLConnection.getInputStream();
     InputStreamReader isr = new InputStreamReader(is, "utf-8");
     BufferedReader br = new BufferedReader(isr);
     String result = br.readLine();
     dos.close();
     is.close();
     return result;
   } catch (Exception e) {
     e.printStackTrace();
     return null;
   }
 }
Example #12
0
  private OutputStream connectRaw(
      String uri, HashMap<String, String> httpHeaders, boolean enableCompression)
      throws IOException {
    url = new URL(uri);

    connection = createConnection(config, url, httpHeaders, enableCompression);
    connection.setRequestMethod("POST");
    connection.setDoInput(true);
    connection.setDoOutput(true);
    if (config.useChunkedPost()) {
      connection.setChunkedStreamingMode(4096);
    }

    return connection.getOutputStream();
  }
Example #13
0
  private static void putVMFiles(String remoteFilePath, String localFilePath) throws Exception {
    String serviceUrl = url.substring(0, url.lastIndexOf("sdk") - 1);
    String httpUrl =
        serviceUrl + "/folder" + remoteFilePath + "?dcPath=" + datacenter + "&dsName=" + datastore;
    httpUrl = httpUrl.replaceAll("\\ ", "%20");
    System.out.println("Putting VM File " + httpUrl);
    URL fileURL = new URL(httpUrl);
    HttpURLConnection conn = (HttpURLConnection) fileURL.openConnection();
    conn.setDoInput(true);
    conn.setDoOutput(true);
    conn.setAllowUserInteraction(true);

    // Maintain session
    List cookies = (List) headers.get("Set-cookie");
    cookieValue = (String) cookies.get(0);
    StringTokenizer tokenizer = new StringTokenizer(cookieValue, ";");
    cookieValue = tokenizer.nextToken();
    String path = "$" + tokenizer.nextToken();
    String cookie = "$Version=\"1\"; " + cookieValue + "; " + path;

    // set the cookie in the new request header
    Map map = new HashMap();
    map.put("Cookie", Collections.singletonList(cookie));
    ((BindingProvider) vimPort).getRequestContext().put(MessageContext.HTTP_REQUEST_HEADERS, map);

    conn.setRequestProperty("Cookie", cookie);
    conn.setRequestProperty("Content-Type", "application/octet-stream");
    conn.setRequestMethod("PUT");
    conn.setRequestProperty("Content-Length", "1024");
    long fileLen = new File(localFilePath).length();
    System.out.println("File size is: " + fileLen);
    conn.setChunkedStreamingMode((int) fileLen);
    OutputStream out = conn.getOutputStream();
    InputStream in = new BufferedInputStream(new FileInputStream(localFilePath));
    int bufLen = 9 * 1024;
    byte[] buf = new byte[bufLen];
    byte[] tmp = null;
    int len = 0;
    while ((len = in.read(buf, 0, bufLen)) != -1) {
      tmp = new byte[len];
      System.arraycopy(buf, 0, tmp, 0, len);
      out.write(tmp, 0, len);
    }
    in.close();
    out.close();
    conn.getResponseMessage();
    conn.disconnect();
  }
Example #14
0
  @Override
  public String doInBackground(JSONObject... params) {
    HttpURLConnection urlConnection = null;
    String answer = null;
    URL url = null;
    try {
      url = new URL("http://folk.ntnu.no/thomborr/NoTheftAuto/deleteCar.php");
      String message = params[0].toString();

      urlConnection = (HttpURLConnection) url.openConnection();
      // Setter at jeg kan sende data til serveren
      urlConnection.setDoOutput(true);
      // Setter at jeg kan motta data fra serveren
      urlConnection.setDoInput(true);
      // Gj�r noe med byte-streamen s� ikke hele lagres i minnet samtidig (?)
      urlConnection.setChunkedStreamingMode(0);
      // Setter request method til POST
      urlConnection.setReadTimeout(10000 /*milliseconds*/);
      urlConnection.setConnectTimeout(15000 /* milliseconds */);
      urlConnection.setRequestMethod("POST");
      urlConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
      urlConnection.setRequestProperty("X-Requested-With", "XMLHttpRequest");

      // Send request
      OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
      out.write(message.getBytes());

      // clean up
      out.flush();
      out.close();

      // Receive answer

      InputStream in = new BufferedInputStream(urlConnection.getInputStream());
      answer = convertStreamToString(in);
      in.close();

    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (urlConnection != null) {
        urlConnection.disconnect();
      }
    }
    return answer;
  }
Example #15
0
  public static HttpURLConnection createConnection(String method, UrlCreator urlCreator) {
    HttpURLConnection connection = null;
    try {
      URL url = urlCreator.createURL();
      connection = (HttpURLConnection) url.openConnection();
      connection.setRequestMethod(method);
      connection.setDoInput(true);
      connection.setChunkedStreamingMode(0);
    } catch (IOException e) {
      e.printStackTrace();
      if (connection != null) {
        connection.disconnect();
      }
    }

    return connection;
  }
  @Override
  protected String doInBackground(InputStream... speech) {
    String response = null;
    try {
      Log.d("Wit", "Requesting SPEECH ...." + _contentType);
      WitRequest witRequest = new WitRequest(_witListener, _context);
      String urlStr = witRequest.buildUri("speech").build().toString();
      URL url = new URL(urlStr);
      Log.d("Wit", "Posting speech to " + url.toString());
      HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
      urlConnection.setDoOutput(true);
      urlConnection.setRequestProperty(
          AUTHORIZATION_HEADER, String.format(BEARER_FORMAT, _accessToken));
      urlConnection.setRequestProperty(ACCEPT_HEADER, ACCEPT_VERSION);
      urlConnection.setRequestProperty(CONTENT_TYPE_HEADER, _contentType);
      urlConnection.setRequestProperty(TRANSFER_ENCODING_HEADER, "chunked");
      urlConnection.setChunkedStreamingMode(0);

      try {
        OutputStream out = urlConnection.getOutputStream();
        int n;
        byte[] buffer = new byte[1024];
        while ((n = speech[0].read(buffer)) > -1) {
          out.write(buffer, 0, n); // Don't allow any extra bytes to creep in, final write
        }
        out.close();
        Log.d("Wit", "Done sending data");
        int statusCode = urlConnection.getResponseCode();
        InputStream in;
        if (statusCode != 200) {
          in = urlConnection.getErrorStream();
        } else {
          in = new BufferedInputStream(urlConnection.getInputStream());
        }
        response = IOUtils.toString(in);
        in.close();
      } finally {
        urlConnection.disconnect();
      }
    } catch (Exception e) {
      Log.d("Wit", "An error occurred during the request: " + e.getMessage());
    }
    return response;
  }
    public void uploadData() throws IOException {
      DataOutputStream dos;

      request.setDoInput(true); // Allow Inputs
      request.setDoOutput(true); // Allow Outputs
      request.setUseCaches(false); // Don't use a Cached Copy
      request.setChunkedStreamingMode(1024);
      request.setRequestMethod("POST");
      request.setRequestProperty("connection", "Keep-Alive");
      request.setRequestProperty("ENCTYPE", "multipart/form-data");

      dos = new DataOutputStream(request.getOutputStream());
      byte[] databyte = data.bytes();

      dos.write(databyte);

      dos.flush();
      dos.close();
    }
  void prepareRequest(HttpURLConnection connection, Request request) throws IOException {
    connection.setRequestMethod(request.getMethod());
    connection.setDoInput(true);

    for (Header header : request.getHeaders()) {
      connection.addRequestProperty(header.getName(), header.getValue());
    }

    TypedOutput body = request.getBody();
    if (body != null) {
      connection.setDoOutput(true);
      connection.addRequestProperty("Content-Type", body.mimeType());
      long length = body.length();
      if (length != -1) {
        connection.setFixedLengthStreamingMode((int) length);
        connection.addRequestProperty("Content-Length", String.valueOf(length));
      } else {
        connection.setChunkedStreamingMode(CHUNK_SIZE);
      }
      body.writeTo(connection.getOutputStream());
    }
  }
  @Override
  public void createConnection(String conType) {
    try {
      InputStream inputStream = null;
      setUpHttpsConnection();
      // set up the request header
      URL urlToConnect = new URL(networkConnection.url);
      httpsURLConnection = (HttpURLConnection) urlToConnect.openConnection();
      setUpHttpsRequestHeader(httpsURLConnection);
      setRequestMethod(conType);
      httpsURLConnection.setConnectTimeout(TIMEOUT_DURATION);
      // httpsURLConnection.setDoInput(true);
      httpsURLConnection.setChunkedStreamingMode(0);
      // Connect to the server.
      httpsURLConnection.connect();
      // write output stream the client info.
      if (networkConnection.datatowrite != null && networkConnection.datatowrite.length > 0) {
        OutputStream outputStream = null;
        try {
          outputStream = httpsURLConnection.getOutputStream();
          outputStream.write(networkConnection.datatowrite);

        } catch (Exception e) {

        } finally {
          try {
            if (outputStream != null) {
              outputStream.close();
              outputStream = null; // release resource for GC
              // support
            }
          } catch (IOException e) {
            // if unable to close the stream
            outputStream = null; // release resource for GC
          }
        }
        networkConnection.datatowrite = null;
      }
      // get teh response code
      int responseCode = httpsURLConnection.getResponseCode();

      if (responseCode == HttpURLConnection.HTTP_OK) {
        // read the data stream from the network.
        inputStream = httpsURLConnection.getInputStream();
        DataInputStream dataInputStream = new DataInputStream(inputStream);
        int a = -1;
        byte b[] = new byte[1024];
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        while ((a = dataInputStream.read(b)) != -1) {
          byteArrayOutputStream.write(b, 0, a);
        }
        // Set the data into the networkUpdater
        networkConnection.networkStatus.setServerResponseData(byteArrayOutputStream.toByteArray());
        networkConnection.networkStatus.setNetworkConnectionException(null);
        byteArrayOutputStream.close();
        dataInputStream.close();
        httpsURLConnection.disconnect();
      } else {
        // Something went wrong
        setErrorMessage(responseCode);
        httpsURLConnection.disconnect();
        networkConnection.networkStatus.setServerResponseData(null);
        networkConnection.networkStatus.setNetworkError(true);
        // networkConnection.networkStatus.setNetorkErrorMessage();
      }

    } catch (Exception e) {
      // Something went wrong
      // setErrorMessage(httpsURLConnection);
      networkConnection.networkStatus.setServerResponseData(null);
      networkConnection.networkStatus.setNetworkConnectionException(e);
      networkConnection.networkStatus.setNetworkError(true);
    } finally {
      if (byteArrayOutputStream != null) {
        try {
          byteArrayOutputStream.close();
        } catch (IOException e) {
        }
        byteArrayOutputStream = null;
      }
      if (dataInputStream != null) {
        try {
          dataInputStream.close();
        } catch (IOException e) {
        }
        dataInputStream = null;
      }
      if (httpsURLConnection != null) {
        httpsURLConnection.disconnect();
        httpsURLConnection = null;
      }
    }
  }
  @Override
  protected HttpURLConnection convert(HttpRequest request)
      throws IOException, InterruptedException {
    boolean chunked = "chunked".equals(request.getFirstHeaderOrNull("Transfer-Encoding"));
    URL url = request.getEndpoint().toURL();

    HttpURLConnection connection =
        (HttpURLConnection) url.openConnection(proxyForURI.apply(request.getEndpoint()));
    if (connection instanceof HttpsURLConnection) {
      HttpsURLConnection sslCon = (HttpsURLConnection) connection;
      if (utils.relaxHostname()) sslCon.setHostnameVerifier(verifier);
      if (sslContextSupplier != null) {
        // used for providers which e.g. use certs for authentication (like FGCP)
        // Provider provides SSLContext impl (which inits context with key manager)
        sslCon.setSSLSocketFactory(sslContextSupplier.get().getSocketFactory());
      } else if (utils.trustAllCerts()) {
        sslCon.setSSLSocketFactory(untrustedSSLContextProvider.get().getSocketFactory());
      }
    }
    connection.setConnectTimeout(utils.getConnectionTimeout());
    connection.setReadTimeout(utils.getSocketOpenTimeout());
    connection.setAllowUserInteraction(false);
    // do not follow redirects since https redirects don't work properly
    // ex. Caused by: java.io.IOException: HTTPS hostname wrong: should be
    // <adriancole.s3int0.s3-external-3.amazonaws.com>
    connection.setInstanceFollowRedirects(false);
    try {
      connection.setRequestMethod(request.getMethod());
    } catch (ProtocolException e) {
      try {
        methodField.set(connection, request.getMethod());
      } catch (IllegalAccessException e1) {
        logger.error(e, "could not set request method: ", request.getMethod());
        propagate(e1);
      }
    }

    for (Map.Entry<String, String> entry : request.getHeaders().entries()) {
      connection.setRequestProperty(entry.getKey(), entry.getValue());
    }

    String host = request.getEndpoint().getHost();
    if (request.getEndpoint().getPort() != -1) {
      host += ":" + request.getEndpoint().getPort();
    }
    connection.setRequestProperty(HOST, host);
    if (connection.getRequestProperty(USER_AGENT) == null) {
      connection.setRequestProperty(USER_AGENT, DEFAULT_USER_AGENT);
    }
    Payload payload = request.getPayload();
    if (payload != null) {
      MutableContentMetadata md = payload.getContentMetadata();
      for (Map.Entry<String, String> entry : contentMetadataCodec.toHeaders(md).entries()) {
        connection.setRequestProperty(entry.getKey(), entry.getValue());
      }
      if (chunked) {
        connection.setChunkedStreamingMode(8196);
        writePayloadToConnection(payload, "streaming", connection);
      } else {
        Long length = checkNotNull(md.getContentLength(), "payload.getContentLength");
        // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6755625
        checkArgument(
            length < Integer.MAX_VALUE,
            "JDK 1.6 does not support >2GB chunks. Use chunked encoding, if possible.");
        if (length > 0) {
          connection.setRequestProperty(CONTENT_LENGTH, length.toString());
          connection.setFixedLengthStreamingMode(length.intValue());
          writePayloadToConnection(payload, length, connection);
        } else {
          writeNothing(connection);
        }
      }
    } else {
      writeNothing(connection);
    }
    return connection;
  }
Example #21
0
  public Response executeTask() throws Exception {
    if (lite.isCacheAble(this)) lite.addCacheHeaders(request);
    String urlStr = request.getUrl();
    URL url = new URL(urlStr);
    HttpURLConnection connection;
    if (lite.settings.getProxy() != null) {
      connection = (HttpURLConnection) url.openConnection(lite.settings.getProxy());
    } else {
      connection = (HttpURLConnection) url.openConnection();
    }
    assertCanceled();
    connection.setReadTimeout(lite.settings.getReadTimeout());
    connection.setConnectTimeout(lite.settings.getConnectTimeout());
    connection.setInstanceFollowRedirects(lite.settings.isFollowRedirects());
    if (connection instanceof HttpsURLConnection) {
      HttpsURLConnection httpsURLConnection = (HttpsURLConnection) connection;
      httpsURLConnection.setSSLSocketFactory(lite.settings.getSslSocketFactory());
      httpsURLConnection.setHostnameVerifier(lite.settings.getHostnameVerifier());
    }
    lite.processCookie(urlStr, request.getHeaders());
    if (request.getHeaders() != null && !request.getHeaders().isEmpty()) {
      boolean first;
      for (String name : request.getHeaders().keySet()) {
        first = true;
        for (String value : request.getHeaders().get(name)) {
          if (first) {
            connection.setRequestProperty(name, value);
            first = false;
          } else {
            connection.addRequestProperty(name, value);
          }
        }
      }
    }
    connection.setRequestMethod(request.getMethod().name());

    connection.setDoInput(true);
    if (request.getMethod().permitsRequestBody && request.getBody() != null) {
      connection.setRequestProperty("Content-Type", request.getBody().contentType().toString());
      long contentLength = request.getBody().contentLength();
      if (contentLength < 0) {
        connection.setChunkedStreamingMode(256 * 1024);
      } else {
        if (contentLength < Integer.MAX_VALUE) {
          connection.setFixedLengthStreamingMode((int) contentLength);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
          connection.setFixedLengthStreamingMode(contentLength);
        } else {
          connection.setChunkedStreamingMode(256 * 1024);
        }
      }
      connection.setRequestProperty("Content-Length", String.valueOf(contentLength));
      connection.setDoOutput(true);
      request.getBody().writeTo(connection.getOutputStream());
    }

    Response response = URLite.createResponse(connection, request);
    lite.saveCookie(urlStr, response.headers());
    isExecuted = true;
    if (!lite.isCacheAble(this)) {
      return response;
    } else {
      return lite.createCacheResponse(response);
    }
  }
 @Override
 public void setChunkedStreamingMode(int chunklen) {
   super.setChunkedStreamingMode(chunklen);
 }
Example #23
0
  /**
   * invoke via Loader
   *
   * @throws IOException
   */
  @Override
  @TargetApi(Build.VERSION_CODES.KITKAT)
  public void sendRequest() throws IOException {
    isLoading = false;

    URL url = new URL(queryUrl);
    { // init connection
      Proxy proxy = params.getProxy();
      if (proxy != null) {
        connection = (HttpURLConnection) url.openConnection(proxy);
      } else {
        connection = (HttpURLConnection) url.openConnection();
      }
      connection.setInstanceFollowRedirects(true);
      connection.setReadTimeout(params.getConnectTimeout());
      connection.setConnectTimeout(params.getConnectTimeout());
      if (connection instanceof HttpsURLConnection) {
        ((HttpsURLConnection) connection).setSSLSocketFactory(params.getSslSocketFactory());
      }
    }

    { // add headers
      try {
        Map<String, List<String>> singleMap =
            COOKIE_MANAGER.get(url.toURI(), new HashMap<String, List<String>>(0));
        List<String> cookies = singleMap.get("Cookie");
        if (cookies != null) {
          connection.setRequestProperty("Cookie", TextUtils.join(";", cookies));
        }
      } catch (Throwable ex) {
        LogUtil.e(ex.getMessage(), ex);
      }

      HashMap<String, String> headers = params.getHeaders();
      if (headers != null) {
        for (Map.Entry<String, String> entry : headers.entrySet()) {
          String name = entry.getKey();
          String value = entry.getValue();
          if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(value)) {
            connection.setRequestProperty(name, value);
          }
        }
      }
    }

    { // write body
      HttpMethod method = params.getMethod();
      connection.setRequestMethod(method.toString());
      if (HttpMethod.permitsRequestBody(method)) {
        RequestBody body = params.getRequestBody();
        if (body != null) {
          if (body instanceof ProgressBody) {
            ((ProgressBody) body).setProgressHandler(progressHandler);
          }
          String contentType = body.getContentType();
          if (!TextUtils.isEmpty(contentType)) {
            connection.setRequestProperty("Content-Type", contentType);
          }
          long contentLength = body.getContentLength();
          if (contentLength < 0) {
            connection.setChunkedStreamingMode(256 * 1024);
          } else {
            if (contentLength < Integer.MAX_VALUE) {
              connection.setFixedLengthStreamingMode((int) contentLength);
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
              connection.setFixedLengthStreamingMode(contentLength);
            } else {
              connection.setChunkedStreamingMode(256 * 1024);
            }
          }
          connection.setRequestProperty("Content-Length", String.valueOf(contentLength));
          connection.setDoOutput(true);
          body.writeTo(connection.getOutputStream());
        }
      }
    }

    LogUtil.d(queryUrl);
    int code = connection.getResponseCode();
    if (code >= 300) {
      HttpException httpException = new HttpException(code, connection.getResponseMessage());
      try {
        httpException.setResult(IOUtil.readStr(connection.getInputStream(), params.getCharset()));
      } catch (Throwable ignored) {
      }
      throw httpException;
    }

    { // save cookies
      try {
        Map<String, List<String>> headers = connection.getHeaderFields();
        if (headers != null) {
          COOKIE_MANAGER.put(url.toURI(), headers);
        }
      } catch (Throwable ex) {
        LogUtil.e(ex.getMessage(), ex);
      }
    }

    isLoading = true;
  }
 public void setChunkedStreamingMode(int i) {
   _flddelegate.setChunkedStreamingMode(i);
 }
 /**
  * Set chunked encoding for the file to be uploaded. This avoid the output stream to buffer all
  * data before transmitting it.
  *
  * @param chunkLength the length of the single chunk
  */
 public void setChunkedStreamingMode(int chunkLength) throws IOException {
   if (conn == null) {
     throw new IOException("Cannot open output stream on non opened connection");
   }
   conn.setChunkedStreamingMode(chunkLength);
 }