Example usage for java.io DataOutputStream write

List of usage examples for java.io DataOutputStream write

Introduction

In this page you can find the example usage for java.io DataOutputStream write.

Prototype

public synchronized void write(int b) throws IOException 

Source Link

Document

Writes the specified byte (the low eight bits of the argument b) to the underlying output stream.

Usage

From source file:eu.crushedpixel.littlstar.api.upload.S3Uploader.java

/**
 * Executes a multipart form upload to the S3 Bucket as described in
 * <a href="http://docs.aws.amazon.com/AmazonS3/latest/dev/HTTPPOSTExamples.html">the AWS Documentation</a>.
 * @param s3UploadProgressListener An S3UploadProgressListener which is called whenever
 *                               bytes are written to the outgoing connection. May be null.
 * @throws IOException in case of a problem or the connection was aborted
 * @throws ClientProtocolException in case of an http protocol error
 */// w  w w .  j  ava  2  s  .  c  om
public void uploadFileToS3(S3UploadProgressListener s3UploadProgressListener)
        throws IOException, ClientProtocolException {
    //unfortunately, we can't use Unirest to execute the call, because there is no support
    //for Progress listeners (yet). See https://github.com/Mashape/unirest-java/issues/26

    int bufferSize = 1024;

    //opening a connection to the S3 Bucket
    HttpURLConnection urlConnection = (HttpURLConnection) new URL(s3_bucket).openConnection();
    urlConnection.setUseCaches(false);
    urlConnection.setDoOutput(true);
    urlConnection.setRequestMethod("POST");
    urlConnection.setChunkedStreamingMode(bufferSize);
    urlConnection.setRequestProperty("Connection", "Keep-Alive");
    urlConnection.setRequestProperty("Cache-Control", "no-cache");
    String boundary = "*****";
    urlConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

    //writing the request headers
    DataOutputStream dos = new DataOutputStream(urlConnection.getOutputStream());

    String newline = "\r\n";
    String twoHyphens = "--";
    dos.writeBytes(twoHyphens + boundary + newline);

    String attachmentName = "file";
    String attachmentFileName = "file";

    dos.writeBytes("Content-Disposition: form-data; name=\"" + attachmentName + "\";filename=\""
            + attachmentFileName + "\"" + newline);
    dos.writeBytes(newline);

    //sending the actual file
    byte[] buf = new byte[bufferSize];

    FileInputStream fis = new FileInputStream(file);
    long totalBytes = fis.getChannel().size();
    long writtenBytes = 0;

    int len;
    while ((len = fis.read(buf)) != -1) {
        dos.write(buf);
        writtenBytes += len;

        s3UploadProgressListener.onProgressUpdated(new S3UpdateProgressEvent(writtenBytes, totalBytes,
                (float) ((double) writtenBytes / totalBytes)));

        if (interrupt) {
            fis.close();
            dos.close();
            return;
        }
    }

    fis.close();

    //finish the call
    dos.writeBytes(newline);
    dos.writeBytes(twoHyphens + boundary + twoHyphens + newline);

    dos.close();

    urlConnection.disconnect();
}

From source file:org.bungeni.ext.integration.bungeniportal.BungeniAppConnector.java

public File getDownloadUrl(String sPage, boolean prefix) {

    String pageURL = (prefix ? this.urlBase + sPage : sPage);

    final HttpGet geturl = new HttpGet(pageURL);

    try {/*from w  ww  . ja  v a  2s . c o  m*/
        String filenameRandom = RandomStringUtils.randomAlphanumeric(8);
        File fTempODT = TempFileManager.createTempFile(filenameRandom, ".odt");
        HttpResponse response = client.execute(geturl);
        int nStatusCode = response.getStatusLine().getStatusCode();
        HttpEntity entity = response.getEntity();
        if (entity != null && nStatusCode == 200) {
            InputStream istream = entity.getContent();
            DataOutputStream dos = new DataOutputStream(
                    new BufferedOutputStream(new FileOutputStream(fTempODT)));
            //FileWriter fw = new FileWriter(fTempODT);
            byte[] rawFiles = IOUtils.toByteArray(istream);
            dos.write(rawFiles);
            dos.close();
        }
        consumeContent(entity);
        return fTempODT;
    } catch (IOException ex) {
        log.error("Error while accessin url : " + pageURL, ex);

    }
    return null;
}

From source file:com.yahoo.pulsar.testclient.LoadSimulationClient.java

private void handle(final byte command, final DataInputStream inputStream, final DataOutputStream outputStream)
        throws Exception {
    final TradeConfiguration tradeConf = new TradeConfiguration();
    tradeConf.command = command;//  w  w w  . ja  va 2s  .c  o m
    switch (command) {
    case CHANGE_COMMAND:
        // Change the topic's settings if it exists. Report whether the
        // topic was found on this server.
        decodeProducerOptions(tradeConf, inputStream);
        if (topicsToTradeUnits.containsKey(tradeConf.topic)) {
            topicsToTradeUnits.get(tradeConf.topic).change(tradeConf);
            outputStream.write(FOUND_TOPIC);
        } else {
            outputStream.write(NO_SUCH_TOPIC);
        }
        break;
    case STOP_COMMAND:
        // Stop the topic if it exists. Report whether the topic was found,
        // and whether it was already stopped.
        tradeConf.topic = inputStream.readUTF();
        if (topicsToTradeUnits.containsKey(tradeConf.topic)) {
            final boolean wasStopped = topicsToTradeUnits.get(tradeConf.topic).stop.getAndSet(true);
            outputStream.write(wasStopped ? REDUNDANT_COMMAND : FOUND_TOPIC);
        } else {
            outputStream.write(NO_SUCH_TOPIC);
        }
        break;
    case TRADE_COMMAND:
        // Create the topic. It is assumed that the topic does not already
        // exist.
        decodeProducerOptions(tradeConf, inputStream);
        final TradeUnit tradeUnit = new TradeUnit(tradeConf, client, producerConf, consumerConf, payloadCache);
        topicsToTradeUnits.put(tradeConf.topic, tradeUnit);
        executor.submit(() -> {
            try {
                tradeUnit.start();
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        });
        // Tell controller topic creation is finished.
        outputStream.write(NO_SUCH_TOPIC);
        break;
    case CHANGE_GROUP_COMMAND:
        // Change the settings of all topics belonging to a group. Report
        // the number of topics changed.
        decodeGroupOptions(tradeConf, inputStream);
        tradeConf.size = inputStream.readInt();
        tradeConf.rate = inputStream.readDouble();
        // See if a topic belongs to this tenant and group using this regex.
        final String groupRegex = ".*://.*/" + tradeConf.tenant + "/" + tradeConf.group + "-.*/.*";
        int numFound = 0;
        for (Map.Entry<String, TradeUnit> entry : topicsToTradeUnits.entrySet()) {
            final String destination = entry.getKey();
            final TradeUnit unit = entry.getValue();
            if (destination.matches(groupRegex)) {
                ++numFound;
                unit.change(tradeConf);
            }
        }
        outputStream.writeInt(numFound);
        break;
    case STOP_GROUP_COMMAND:
        // Stop all topics belonging to a group. Report the number of topics
        // stopped.
        decodeGroupOptions(tradeConf, inputStream);
        // See if a topic belongs to this tenant and group using this regex.
        final String regex = ".*://.*/" + tradeConf.tenant + "/" + tradeConf.group + "-.*/.*";
        int numStopped = 0;
        for (Map.Entry<String, TradeUnit> entry : topicsToTradeUnits.entrySet()) {
            final String destination = entry.getKey();
            final TradeUnit unit = entry.getValue();
            if (destination.matches(regex) && !unit.stop.getAndSet(true)) {
                ++numStopped;
            }
        }
        outputStream.writeInt(numStopped);
        break;
    default:
        throw new IllegalArgumentException("Unrecognized command code received: " + command);
    }
    outputStream.flush();
}

From source file:org.apache.hadoop.hive.ql.metadata.formatting.TextMetaDataFormatter.java

/**
 * Show the table partitions.//ww w . ja va 2 s  .co m
 */
@Override
public void showTablePartitions(DataOutputStream outStream, List<String> parts) throws HiveException {
    try {
        for (String part : parts) {
            // Partition names are URL encoded. We decode the names unless Hive
            // is configured to use the encoded names.
            SessionState ss = SessionState.get();
            if (ss != null && ss.getConf() != null
                    && !ss.getConf().getBoolVar(HiveConf.ConfVars.HIVE_DECODE_PARTITION_NAME)) {
                outStream.write(part.getBytes("UTF-8"));
            } else {
                outStream.write(FileUtils.unescapePathName(part).getBytes("UTF-8"));
            }
            outStream.write(terminator);
        }
    } catch (IOException e) {
        throw new HiveException(e);
    }
}

From source file:com.zpci.firstsignhairclipdemo.MainActivity.java

public void savewavefile(byte[] ra) {
    //prepend 44 byte wave header to data

    int sampleRate = 8000; // audio sample rate is 8000 SPS
    int numSecs = ra.length / sampleRate; // number of seconds of audio to record
    int samples = sampleRate * numSecs; // number of samples in file
    short bitsPerSample = 8; // one byte per sample
    int filesize = samples + 44; // check this?
    int fmtChunkSize = 16; // size of 'fmt' chunk
    short channels = 1; // mono
    int byteRate = sampleRate * channels * bitsPerSample / 8; // will be 8K for us
    short format = 1; // 1 == uncompressed pcm
    short blockalign = (short) (channels * bitsPerSample / 8); // bytes per sample
    int audiolen = samples * channels * bitsPerSample / 8; // length of audio in bytes

    try {/*from   w  ww.j  a  v a  2 s  .c  o m*/
        //OutputStream os = openFileOutput("diagaudio.wav", Context.MODE_PRIVATE);
        String state = Environment.getExternalStorageState();
        Log.d(TAG, "External storage state: " + state);
        if (Environment.MEDIA_MOUNTED.equals(state)) {

            //create firstsign directory
            File rootPath = new File(Environment.getExternalStorageDirectory(), "firstsign");
            if (!rootPath.exists()) {
                rootPath.mkdirs();
                Log.d(TAG, "mkdirs");
            }
            File file = new File(rootPath, "hairclipaudio.wav");
            file.createNewFile();
            OutputStream os = new FileOutputStream(file);
            BufferedOutputStream bos = new BufferedOutputStream(os);
            DataOutputStream wf = new DataOutputStream(bos);

            wf.write("RIFF".getBytes());
            wf.writeInt(Integer.reverseBytes(filesize - 8));
            wf.write("WAVE".getBytes());
            wf.write("fmt ".getBytes());
            wf.writeInt(Integer.reverseBytes(fmtChunkSize));
            wf.writeShort(Short.reverseBytes(format));
            wf.writeShort(Short.reverseBytes(channels));
            wf.writeInt(Integer.reverseBytes(sampleRate));
            wf.writeInt(Integer.reverseBytes(byteRate));
            wf.writeShort(Short.reverseBytes(blockalign));
            wf.writeShort(Short.reverseBytes(bitsPerSample));
            wf.write("data".getBytes());
            wf.writeInt(Integer.reverseBytes(audiolen));
            wf.write(ra);

            wf.close();
            bos.close();
            os.close();

            Log.d(TAG, "wavefile write complete");
        } else {
            Toast.makeText(this, "SDCard not mounted", Toast.LENGTH_LONG).show();
        } //what do i do?

    } catch (Exception e) {
        Log.e(TAG, "exception in savewavefile");
        e.printStackTrace();
    }

}

From source file:com.igormaznitsa.jhexed.hexmap.HexFieldLayer.java

public void write(final OutputStream out) throws IOException {
    final DataOutputStream dout = out instanceof DataOutputStream ? (DataOutputStream) out
            : new DataOutputStream(out);
    dout.writeUTF(this.name);
    dout.writeUTF(this.comments);

    dout.writeShort(this.values.size());
    for (int i = 0; i < this.values.size(); i++) {
        this.values.get(i).write(dout);
    }/*from  w w w  .  jav  a 2 s.c o  m*/

    dout.writeInt(this.columns);
    dout.writeInt(this.rows);
    dout.writeBoolean(this.visible);

    final byte[] packed = Utils.packByteArray(this.array);
    dout.writeInt(packed.length);
    dout.write(packed);
    dout.flush();
}

From source file:com.benefit.buy.library.http.query.callback.AbstractAjaxCallback.java

private static void writeField(DataOutputStream dos, String name, String value) throws IOException {
    dos.writeBytes(twoHyphens + boundary + lineEnd);
    dos.writeBytes("Content-Disposition: form-data; name=\"" + name + "\"");
    dos.writeBytes(lineEnd);// w  w w .j  a v a 2 s .  co m
    dos.writeBytes(lineEnd);
    byte[] data = value.getBytes("UTF-8");
    dos.write(data);
    dos.writeBytes(lineEnd);
}

From source file:br.com.anteros.android.synchronism.communication.HttpConnectionClient.java

public MobileResponse sendReceiveData(MobileRequest mobileRequest) {
    sessionId = HttpConnectionSession.getInstance().getSessionId();

    add(mobileRequest.getFormattedHeader(), mobileRequest.getFormatedActions());
    MobileResponse mobileResponse = new MobileResponse();
    try {/* w  w  w .  j ava  2  s. co m*/
        if (this.getSendData() != null) {
            for (MobileSendDataListener listener : this.getSendData().getListeners())
                listener.onWaitServer();
        }

        if (this.getSendData() != null) {
            for (MobileSendDataListener listener : this.getSendData().getListeners())
                listener.onStatusConnectionServer("Conectando Servidor...");
        }

        /*
         * Define url e estabelece conexo
         */

        HttpPost httpPost = new HttpPost(url);

        HttpParams httpParameters = new BasicHttpParams();
        // Set the timeout in milliseconds until a connection is
        // established.
        // The default value is zero, that means the timeout is not used.
        HttpConnectionParams.setConnectionTimeout(httpParameters, TIMEOUT_CONNECTION);
        // Set the default socket timeout (SO_TIMEOUT)
        // in milliseconds which is the timeout for waiting for data.
        HttpConnectionParams.setSoTimeout(httpParameters, TIMEOUT_SOCKET);

        if (httpClient == null)
            httpClient = new DefaultHttpClient(httpParameters);

        //

        /*
         * Setar o cookie da sesso
         */
        if ((sessionId != null) && (!"".equals(sessionId))) {
            httpPost.setHeader("Cookie", "JSESSIONID=" + sessionId);
        }
        httpPost.setHeader("User-Agent", "Android");
        httpPost.setHeader("Accept-Encoding", "gzip");

        if (this.getSendData() != null) {
            for (MobileSendDataListener listener : this.getSendData().getListeners())
                listener.onStatusConnectionServer("Enviando requisio...");
        }

        //
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DataOutputStream out = new DataOutputStream(baos);
        //

        /*
         * Escrever no output
         */
        out.writeInt(numOption);
        String aux[];
        for (int i = 0; i < opPOST.size(); i++) {
            aux = (String[]) opPOST.get(i);

            out.writeUTF(aux[0]);

            byte[] b = aux[1].getBytes();
            out.writeInt(b.length);
            out.write(b);

            aux = null;
        }
        out.flush();

        ByteArrayEntity entity = new ByteArrayEntity(baos.toByteArray());
        entity.setContentEncoding("UTF-8");
        httpPost.setEntity(entity);
        httpPost.addHeader("Connection", "Keep-Alive");
        httpPost.addHeader("Keep-Alive", "timeout=120000");

        out.close();
        //

        if (this.getSendData() != null) {
            for (MobileSendDataListener listener : this.getSendData().getListeners())
                listener.onStatusConnectionServer("Recebendo dados...");
        }

        if (this.getSendData() != null) {
            for (MobileSendDataListener listener : this.getSendData().getListeners())
                listener.onDebugMessage("Recebendo dados conexo");
        }

        /*
         * Aguardar resposta
         */
        HttpResponse httpResponse = httpClient.execute(httpPost);
        List result = null;
        StatusLine statusLine = httpResponse.getStatusLine();
        int code = statusLine.getStatusCode();
        if (code != 200) {
            String msg = "Erro RECEBENDO resposta do Servidor " + url + " - Cdigo do Erro HTTP " + code + "-"
                    + statusLine.getReasonPhrase();
            mobileResponse.setStatus(msg);
        } else {
            if (this.getSendData() != null) {
                for (MobileSendDataListener listener : this.getSendData().getListeners())
                    listener.onStatusConnectionServer("Resposta OK !");
            }

            /*
             * Ler cookie
             */
            String tmpSessionId = null;

            for (Cookie c : httpClient.getCookieStore().getCookies()) {
                if ("JSESSIONID".equals(c.getName())) {
                    tmpSessionId = c.getValue();
                }
            }

            if (tmpSessionId != null) {
                sessionId = tmpSessionId;
                HttpConnectionSession.getInstance().setSessionId(sessionId);
            }
            //

            if (this.getSendData() != null) {
                for (MobileSendDataListener listener : this.getSendData().getListeners())
                    listener.onStatusConnectionServer("Lendo dados...");
            }

            /*
             * Le os dados
             */
            HttpEntity entityResponse = httpResponse.getEntity();
            InputStream in = AndroidHttpClient.getUngzippedContent(entityResponse);

            BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));

            String content = null;

            content = reader.readLine();
            String line = null;
            while ((line = reader.readLine()) != null) {
                content += line;
            }
            line = "";

            reader.close();
            reader = null;
            in.close();
            in = null;
            entityResponse.consumeContent();
            entityResponse = null;
            //

            StringTokenizer messagePart = new StringTokenizer(content, "#");
            content = null;

            if (this.getSendData() != null) {
                for (MobileSendDataListener listener : this.getSendData().getListeners())
                    listener.onDebugMessage("RECEBEU dados conexo");
            }

            if (this.getSendData() != null) {
                for (MobileSendDataListener listener : this.getSendData().getListeners())
                    listener.onStatusConnectionServer("Processando resposta... ");
            }

            if (this.getSendData() != null) {
                for (MobileSendDataListener listener : this.getSendData().getListeners())
                    listener.onDebugMessage("Converteu string dados conexo");
            }

            while (messagePart.hasMoreTokens()) {
                String resultData = messagePart.nextToken();
                resultData = resultData.substring(resultData.indexOf("*") + 1, resultData.length());
                if (result == null)
                    result = formatData(resultData);
                else
                    result.addAll(formatData(resultData));
            }
            messagePart = null;
        }

        if (result != null) {
            mobileResponse.setFormattedParameters(result);
            result.clear();
            result = null;
        }

        if (this.getSendData() != null) {
            for (MobileSendDataListener listener : this.getSendData().getListeners())
                listener.onEndServer();
        }

    } catch (SocketTimeoutException exTimeout) {
        exTimeout.printStackTrace();
        wrapException(mobileResponse, "No foi possvel CONECTAR ao Servidor " + url
                + ". Verifique sua conexo e se o servidor est em funcionamento.");
    } catch (Exception e) {
        e.printStackTrace();
        if ((e.getMessage() + "").contains("unreachable"))
            wrapException(mobileResponse,
                    "Voc est sem acesso a internet. Verifique sua conexo. No foi possvel conectar ao servidor  "
                            + url);
        else
            wrapException(mobileResponse,
                    "No foi possivel CONECTAR ao Servidor " + url + " " + e.getMessage());
    }
    return mobileResponse;
}

From source file:com.zpci.firstsignhairclipdemo.MainActivity.java

public void saverawdata(byte[] ra, int type) {
    String filename;// w  w w.j  a v a  2s.c  om
    boolean usetext = true;

    if (type == FILETYPEAUDIO)
        filename = "rawaudio.dat";
    else {
        if (usetext)
            filename = "rawsensor.csv";
        else
            filename = "rawsensor.dat";
    }

    try {
        //FileOutputStream adfos = openFileOutput(filename, Context.MODE_PRIVATE);
        //FileOutputStream adfos = openFileOutput(filename, Context.MODE_WORLD_READABLE);
        String state = Environment.getExternalStorageState();
        Log.d(TAG, "External storage state: " + state);
        if (Environment.MEDIA_MOUNTED.equals(state)) {

            //create firstsign directory
            File rootPath = new File(Environment.getExternalStorageDirectory(), "firstsign");
            if (!rootPath.exists()) {
                rootPath.mkdirs();
                Log.d(TAG, "mkdirs");
            }
            File file = new File(rootPath, filename);
            file.createNewFile();
            OutputStream os = new FileOutputStream(file);
            BufferedOutputStream bos = new BufferedOutputStream(os);
            DataOutputStream rf = new DataOutputStream(bos);

            if (usetext) {
                rf.write("Ax Ay Az Rr Rp Ry\n".getBytes());
                for (int i = 0, j = 0; i < ra.length; i += 2) {
                    short sval = (short) ((ra[i] << 8) | (ra[i + 1] & 0xff));
                    //Log.d(TAG,"sval = " + sval);
                    String ssval = Short.toString(sval) + " ";
                    j++;
                    if (j % 6 == 0)
                        ssval += "\n";
                    rf.write(ssval.getBytes());
                }
            } else {
                rf.write(ra);
            }

            File rfile = getFileStreamPath(filename);
            Log.d(TAG, "path: " + rfile);
            Log.d(TAG, "raw file write: " + filename + ra + "size = " + ra.length);
            rf.close();
            bos.close();
            os.close();
        } else {
            Toast.makeText(this, "SDCard not mounted", Toast.LENGTH_LONG).show();
        } //what do i do?

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.kymjs.kjframe.http.httpclient.HttpRequestBuilder.java

public HttpResponse execute(HashMap<String, File> files) throws HttpClientException {
    HttpURLConnection conn = null;
    UncloseableInputStream payloadStream = null;
    try {/*w w  w  .  j  av a2s  .  c  om*/
        //            if (parameters != null && !parameters.isEmpty()) {
        //                final StringBuilder buf = new StringBuilder(256);
        //                if (HTTP_GET.equals(method) || HTTP_HEAD.equals(method)) {
        //                    buf.append('?');
        //                }
        //
        //                int paramIdx = 0;
        //                for (final Map.Entry<String, String> e : parameters.entrySet()) {
        //                    if (paramIdx != 0) {
        //                        buf.append("&");
        //                    }
        //                    final String name = e.getKey();
        //                    final String value = e.getValue();
        //                    buf.append(URLEncoder.encode(name, CONTENT_CHARSET)).append("=")
        //                            .append(URLEncoder.encode(value, CONTENT_CHARSET));
        //                    ++paramIdx;
        //                }
        //
        //                if (!contentSet
        //                        && (HTTP_POST.equals(method) || HTTP_DELETE.equals(method) || HTTP_PUT.equals(method))) {
        //                    try {
        //                        content = buf.toString().getBytes(CONTENT_CHARSET);
        //                    } catch (UnsupportedEncodingException e) {
        //                        // Unlikely to happen.
        //                        throw new HttpClientException("Encoding error", e);
        //                    }
        //                } else {
        //                    uri += buf;
        //                }
        //            }

        conn = (HttpURLConnection) new URL(uri).openConnection();
        conn.setConnectTimeout(hc.getConnectTimeout());
        conn.setReadTimeout(hc.getReadTimeout());
        conn.setAllowUserInteraction(false);
        conn.setInstanceFollowRedirects(false);
        conn.setRequestMethod(method);
        conn.setUseCaches(false);
        conn.setDoInput(true);

        if (headers != null && !headers.isEmpty()) {
            for (final Map.Entry<String, List<String>> e : headers.entrySet()) {
                final List<String> values = e.getValue();
                if (values != null) {
                    final String name = e.getKey();
                    for (final String value : values) {
                        conn.addRequestProperty(name, value);
                    }
                }
            }
        }

        if (cookies != null && !cookies.isEmpty()
                || hc.getInMemoryCookies() != null && !hc.getInMemoryCookies().isEmpty()) {
            final StringBuilder cookieHeaderValue = new StringBuilder(256);
            prepareCookieHeader(cookies, cookieHeaderValue);
            prepareCookieHeader(hc.getInMemoryCookies(), cookieHeaderValue);
            conn.setRequestProperty("Cookie", cookieHeaderValue.toString());
        }

        final String userAgent = hc.getUserAgent();
        if (userAgent != null) {
            conn.setRequestProperty("User-Agent", userAgent);
        }

        conn.setRequestProperty("Connection", "keep-alive");
        conn.setRequestProperty("Accept-Encoding", "gzip,deflate");
        conn.setRequestProperty("Accept-Charset", CONTENT_CHARSET);
        conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY);

        if (conn instanceof HttpsURLConnection) {
            setupSecureConnection(hc.getContext(), (HttpsURLConnection) conn);
        }

        // ?
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> entry : parameters.entrySet()) {
            sb.append(PREFIX);
            sb.append(BOUNDARY);
            sb.append(LINEND);
            sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINEND);
            sb.append("Content-Type: text/plain; charset=" + CONTENT_CHARSET + LINEND);
            sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
            sb.append(LINEND);
            sb.append(entry.getValue());
            sb.append(LINEND);
        }

        DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
        outStream.write(sb.toString().getBytes());

        // ???
        if (files != null) {
            for (Map.Entry<String, File> file : files.entrySet()) {
                StringBuilder sb1 = new StringBuilder();
                sb1.append(PREFIX);
                sb1.append(BOUNDARY);
                sb1.append(LINEND);
                sb1.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getKey() + "\""
                        + LINEND);
                sb1.append("Content-Type: application/octet-stream; charset=" + CONTENT_CHARSET + LINEND);
                sb1.append(LINEND);
                outStream.write(sb1.toString().getBytes());

                InputStream is = new FileInputStream(file.getValue());
                byte[] buffer = new byte[1024];
                int len = 0;
                while ((len = is.read(buffer)) != -1) {
                    outStream.write(buffer, 0, len);
                }

                is.close();
                outStream.write(LINEND.getBytes());
            }
        }

        // ?
        byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
        outStream.write(end_data);
        outStream.flush();
        final int statusCode = conn.getResponseCode();
        if (statusCode == -1) {
            throw new HttpClientException("Invalid response from " + uri);
        }
        if (!expectedStatusCodes.isEmpty() && !expectedStatusCodes.contains(statusCode)) {
            throw new HttpClientException(
                    "Expected status code " + expectedStatusCodes + ", got " + statusCode);
        } else if (expectedStatusCodes.isEmpty() && statusCode / 100 != 2) {
            throw new HttpClientException("Expected status code 2xx, got " + statusCode);
        }

        final Map<String, List<String>> headerFields = conn.getHeaderFields();
        final Map<String, String> inMemoryCookies = hc.getInMemoryCookies();
        if (headerFields != null) {
            final List<String> newCookies = headerFields.get("Set-Cookie");
            if (newCookies != null) {
                for (final String newCookie : newCookies) {
                    final String rawCookie = newCookie.split(";", 2)[0];
                    final int i = rawCookie.indexOf('=');
                    final String name = rawCookie.substring(0, i);
                    final String value = rawCookie.substring(i + 1);
                    inMemoryCookies.put(name, value);
                }
            }
        }

        if (isStatusCodeError(statusCode)) {
            // Got an error: cannot read input.
            payloadStream = new UncloseableInputStream(getErrorStream(conn));
        } else {
            payloadStream = new UncloseableInputStream(getInputStream(conn));
        }
        final HttpResponse resp = new HttpResponse(statusCode, payloadStream,
                headerFields == null ? NO_HEADERS : headerFields, inMemoryCookies);
        if (handler != null) {
            try {
                handler.onResponse(resp);
            } catch (HttpClientException e) {
                throw e;
            } catch (Exception e) {
                throw new HttpClientException("Error in response handler", e);
            }
        } else {
            final File temp = File.createTempFile("httpclient-req-", ".cache", hc.getContext().getCacheDir());
            resp.preload(temp);
            temp.delete();
        }
        return resp;
    } catch (SocketTimeoutException e) {
        if (handler != null) {
            try {
                handler.onTimeout();
                return null;
            } catch (HttpClientException e2) {
                throw e2;
            } catch (Exception e2) {
                throw new HttpClientException("Error in response handler", e2);
            }
        } else {
            throw new HttpClientException("Response timeout from " + uri, e);
        }
    } catch (IOException e) {
        throw new HttpClientException("Connection failed to " + uri, e);
    } finally {
        if (conn != null) {
            if (payloadStream != null) {
                // Fully read Http response:
                // http://docs.oracle.com/javase/6/docs/technotes/guides/net/http-keepalive.html
                try {
                    while (payloadStream.read(buffer) != -1) {
                        ;
                    }
                } catch (IOException ignore) {
                }
                payloadStream.forceClose();
            }
            conn.disconnect();
        }
    }
}