Example usage for java.net HttpURLConnection setDoOutput

List of usage examples for java.net HttpURLConnection setDoOutput

Introduction

In this page you can find the example usage for java.net HttpURLConnection setDoOutput.

Prototype

public void setDoOutput(boolean dooutput) 

Source Link

Document

Sets the value of the doOutput field for this URLConnection to the specified value.

Usage

From source file:com.zzl.zl_app.cache.Utility.java

public static String uploadFile(File file, String RequestURL, String fileName) {
    Tools.log("IO", "RequestURL:" + RequestURL);
    String result = null;//from   ww  w.  ja  v  a 2  s .com
    String BOUNDARY = UUID.randomUUID().toString(); //  ??
    String PREFIX = "--", LINE_END = "\r\n";
    String CONTENT_TYPE = "multipart/form-data"; // 

    try {
        URL url = new URL(RequestURL);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(Utility.SET_SOCKET_TIMEOUT);
        conn.setConnectTimeout(Utility.SET_CONNECTION_TIMEOUT);
        conn.setDoInput(true); // ??
        conn.setDoOutput(true); // ??
        conn.setUseCaches(false); // ??
        conn.setRequestMethod("POST"); // ?
        conn.setRequestProperty("Charset", CHARSET); // ?
        conn.setRequestProperty("connection", "keep-alive");
        conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);

        if (file != null) {
            /**
             * ?
             */
            DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
            StringBuffer sb = new StringBuffer();
            sb.append(PREFIX);
            sb.append(BOUNDARY);
            sb.append(LINE_END);
            /**
             * ?? name???key ?key ??
             * filename?????? :abc.png
             */
            sb.append("Content-Disposition: form-data; name=\"voice\"; filename=\"" + file.getName() + "\""
                    + LINE_END);
            sb.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINE_END);
            sb.append(LINE_END);
            dos.write(sb.toString().getBytes());
            Tools.log("FileSize", "file:" + file.length());
            InputStream is = new FileInputStream(file);
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = is.read(bytes)) != -1) {
                dos.write(bytes, 0, len);
                Tools.log("FileSize", "size:" + len);
            }

            dos.write(LINE_END.getBytes());
            byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes();
            dos.write(end_data);
            dos.flush();
            dos.close();
            is.close();
            /**
             * ??? 200=? ?????
             */
            int res = conn.getResponseCode();
            Tools.log("IO", "ResponseCode:" + res);
            if (res == 200) {
                InputStream input = conn.getInputStream();
                StringBuffer sb1 = new StringBuffer();
                int ss;
                while ((ss = input.read()) != -1) {
                    sb1.append((char) ss);
                }
                result = sb1.toString();
            }

        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return result;
}

From source file:com.miya38.connection.volley.CustomHurlStack.java

@SuppressWarnings("deprecation")
/* package */static void setConnectionParametersForRequest(final HttpURLConnection connection,
        final Request<?> request) throws IOException, AuthFailureError {
    switch (request.getMethod()) {
    case Method.DEPRECATED_GET_OR_POST:
        // This is the deprecated way that needs to be handled for backwards compatibility.
        // If the request's post body is null, then the assumption is that the request is
        // GET.  Otherwise, it is assumed that the request is a POST.
        final byte[] postBody = request.getPostBody();
        if (postBody != null) {
            // Prepare output. There is no need to set Content-Length explicitly,
            // since this is handled by HttpURLConnection using the size of the prepared
            // output stream.
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getPostBodyContentType());
            final DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            out.write(postBody);/*from w ww .ja v a  2s  . com*/
            out.close();
        }
        break;
    case Method.GET:
        // Not necessary to set the request method because connection defaults to GET but
        // being explicit here.
        connection.setRequestMethod("GET");
        break;
    case Method.DELETE:
        connection.setRequestMethod("DELETE");
        break;
    case Method.POST:
        connection.setRequestMethod("POST");
        addBodyIfExists(connection, request);
        break;
    case Method.PUT:
        connection.setRequestMethod("PUT");
        addBodyIfExists(connection, request);
        break;
    case Method.HEAD:
        connection.setRequestMethod("HEAD");
        break;
    case Method.OPTIONS:
        connection.setRequestMethod("OPTIONS");
        break;
    case Method.TRACE:
        connection.setRequestMethod("TRACE");
        break;
    case Method.PATCH:
        connection.setRequestMethod("PATCH");
        addBodyIfExists(connection, request);
        break;
    default:
        throw new IllegalStateException("Unknown method type.");
    }
}

From source file:cn.com.xxutils.volley.toolbox.HurlStack.java

@SuppressWarnings("deprecation")
/* package */ static void setConnectionParametersForRequest(HttpURLConnection connection, Request<?> request)
        throws IOException, AuthFailureError {
    switch (request.getMethod()) {
    case Request.Method.DEPRECATED_GET_OR_POST:
        // This is the deprecated way that needs to be handled for backwards compatibility.
        // If the request's post body is null, then the assumption is that the request is
        // GET.  Otherwise, it is assumed that the request is a POST.
        byte[] postBody = request.getPostBody();
        if (postBody != null) {
            // Prepare output. There is no need to set Content-Length explicitly,
            // since this is handled by HttpURLConnection using the size of the prepared
            // output stream.
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getPostBodyContentType());
            DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            out.write(postBody);/*from ww w  . j a  v a 2  s  .  c om*/
            out.close();
        }
        break;
    case Request.Method.GET:
        // Not necessary to set the request method because connection defaults to GET but
        // being explicit here.
        connection.setRequestMethod("GET");
        break;
    case Request.Method.DELETE:
        connection.setRequestMethod("DELETE");
        break;
    case Request.Method.POST:
        connection.setRequestMethod("POST");
        addBodyIfExists(connection, request);
        break;
    case Request.Method.PUT:
        connection.setRequestMethod("PUT");
        addBodyIfExists(connection, request);
        break;
    case Request.Method.HEAD:
        connection.setRequestMethod("HEAD");
        break;
    case Request.Method.OPTIONS:
        connection.setRequestMethod("OPTIONS");
        break;
    case Request.Method.TRACE:
        connection.setRequestMethod("TRACE");
        break;
    case Request.Method.PATCH:
        connection.setRequestMethod("PATCH");
        addBodyIfExists(connection, request);
        break;
    default:
        throw new IllegalStateException("Unknown method type.");
    }
}

From source file:neal.http.impl.httpstack.HurlStack.java

@SuppressWarnings("deprecation")
/* package */ static void setConnectionParametersForRequest(HttpURLConnection connection, Request<?> request)
        throws IOException, HttpErrorCollection.AuthFailureError {
    switch (request.getMethod()) {
    case Request.Method.DEPRECATED_GET_OR_POST:
        // This is the deprecated way that needs to be handled for backwards compatibility.
        // If the request's post body is null, then the assumption is that the request is
        // GET.  Otherwise, it is assumed that the request is a POST.
        byte[] postBody = request.getPostBody();
        if (postBody != null) {
            // Prepare output. There is no need to set Content-Length explicitly,
            // since this is handled by HttpURLConnection using the size of the prepared
            // output stream.
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getPostBodyContentType());
            DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            out.write(postBody);//from  w w  w  .  j a v  a2 s  .  c  o m
            out.close();
        }
        break;
    case Method.GET:
        // Not necessary to set the request method because connection defaults to GET but
        // being explicit here.
        connection.setRequestMethod("GET");
        break;
    case Method.DELETE:
        connection.setRequestMethod("DELETE");
        break;
    case Method.POST:
        connection.setRequestMethod("POST");
        addBodyIfExists(connection, request);
        break;
    case Method.PUT:
        connection.setRequestMethod("PUT");
        addBodyIfExists(connection, request);
        break;
    case Method.HEAD:
        connection.setRequestMethod("HEAD");
        break;
    case Method.OPTIONS:
        connection.setRequestMethod("OPTIONS");
        break;
    case Method.TRACE:
        connection.setRequestMethod("TRACE");
        break;
    case Method.PATCH:
        connection.setRequestMethod("PATCH");
        addBodyIfExists(connection, request);
        break;
    default:
        throw new IllegalStateException("Unknown method type.");
    }
}

From source file:com.navercorp.volleyextensions.volleyer.multipart.stack.MultipartHurlStack.java

@SuppressWarnings("deprecation")
/* package */ static void setConnectionParametersForRequest(HttpURLConnection connection, Request<?> request)
        throws IOException, AuthFailureError {
    switch (request.getMethod()) {
    case Method.DEPRECATED_GET_OR_POST:
        // This is the deprecated way that needs to be handled for backwards compatibility.
        // If the request's post body is null, then the assumption is that the request is
        // GET.  Otherwise, it is assumed that the request is a POST.
        byte[] postBody = request.getPostBody();
        if (postBody != null) {
            // Prepare output. There is no need to set Content-Length explicitly,
            // since this is handled by HttpURLConnection using the size of the prepared
            // output stream.
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getPostBodyContentType());
            DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            out.write(postBody);//  w  w  w .  j a v  a  2 s. c  o m
            out.close();
        }
        break;
    case Method.GET:
        // Not necessary to set the request method because connection defaults to GET but
        // being explicit here.
        connection.setRequestMethod("GET");
        break;
    case Method.DELETE:
        connection.setRequestMethod("DELETE");
        break;
    case Method.POST:
        connection.setRequestMethod("POST");
        addMultipartIfExists(connection, request);
        break;
    case Method.PUT:
        connection.setRequestMethod("PUT");
        addMultipartIfExists(connection, request);
        break;
    case Method.HEAD:
        connection.setRequestMethod("HEAD");
        break;
    case Method.OPTIONS:
        connection.setRequestMethod("OPTIONS");
        break;
    case Method.TRACE:
        connection.setRequestMethod("TRACE");
        break;
    case Method.PATCH:
        connection.setRequestMethod("PATCH");
        addMultipartIfExists(connection, request);
        break;
    default:
        throw new IllegalStateException("Unknown method type.");
    }
}

From source file:com.kubeiwu.commontool.khttp.toolbox.HurlStack.java

static void setConnectionParametersForRequest(HttpURLConnection connection, Request<?> request)
        throws IOException, AuthFailureError {
    switch (request.getMethod()) {
    case Method.DEPRECATED_GET_OR_POST:
        // This is the deprecated way that needs to be handled for backwards
        // compatibility.
        // If the request's post body is null, then the assumption is that
        // the request is
        // GET. Otherwise, it is assumed that the request is a POST.
        byte[] postBody = request.getBody();
        if (postBody != null) {
            // Prepare output. There is no need to set Content-Length
            // explicitly,
            // since this is handled by HttpURLConnection using the size of
            // the prepared
            // output stream.
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getBodyContentType());
            DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            out.write(postBody);/*w  w  w . j  a v  a2 s.  c  o m*/
            out.close();
        }
        break;
    case Method.GET:
        // Not necessary to set the request method because connection
        // defaults to GET but
        // being explicit here.
        connection.setRequestMethod("GET");
        break;
    case Method.DELETE:
        connection.setRequestMethod("DELETE");
        break;
    case Method.POST:
        connection.setRequestMethod("POST");
        addBodyIfExists(connection, request);
        break;
    case Method.PUT:
        connection.setRequestMethod("PUT");
        addBodyIfExists(connection, request);
        break;
    default:
        throw new IllegalStateException("Unknown method type.");
    }
}

From source file:com.lovebridge.library.volley.toolbox.HurlStack.java

@SuppressWarnings("deprecation")
/* package */ static void setConnectionParametersForRequest(HttpURLConnection connection, Request<?> request)
        throws IOException, AuthFailureError {
    switch (request.getMethod()) {
    case Method.DEPRECATED_GET_OR_POST:
        // This is the deprecated way that needs to be handled for
        // backwards compatibility.
        // If the request's post body is null, then the assumption is
        // that the request is
        // GET. Otherwise, it is assumed that the request is a POST.
        byte[] postBody = request.getPostBody();
        if (postBody != null) {
            // Prepare output. There is no need to set Content-Length
            // explicitly,
            // since this is handled by HttpURLConnection using the size
            // of the prepared
            // output stream.
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getPostBodyContentType());
            DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            out.write(postBody);/*from www  . java2 s .  co  m*/
            out.close();
        }
        break;
    case Method.GET:
        // Not necessary to set the request method because connection
        // defaults to GET but
        // being explicit here.
        connection.setRequestMethod("GET");
        break;
    case Method.DELETE:
        connection.setRequestMethod("DELETE");
        break;
    case Method.POST:
        connection.setRequestMethod("POST");
        addBodyIfExists(connection, request);
        break;
    case Method.PUT:
        connection.setRequestMethod("PUT");
        addBodyIfExists(connection, request);
        break;
    case Method.HEAD:
        connection.setRequestMethod("HEAD");
        break;
    case Method.OPTIONS:
        connection.setRequestMethod("OPTIONS");
        break;
    case Method.TRACE:
        connection.setRequestMethod("TRACE");
        break;
    case Method.PATCH:
        connection.setRequestMethod("PATCH");
        addBodyIfExists(connection, request);
        break;
    default:
        throw new IllegalStateException("Unknown method type.");
    }
}

From source file:de.fu_berlin.inf.dpp.netbeans.feedback.FileSubmitter.java

/**
 * Tries to upload the given file to the given HTTP server (via POST
 * method).//from www.j av a 2s  .  co  m
 * 
 * @param file
 *            the file to upload
 * @param url
 *            the URL of the server, that is supposed to handle the file
 * @param monitor
 *            a monitor to report progress to
 * @throws IOException
 *             if an I/O error occurs
 * 
 */

public static void uploadFile(final File file, final String url, IProgressMonitor monitor) throws IOException {

    final String CRLF = "\r\n";
    final String doubleDash = "--";
    final String boundary = generateBoundary();

    HttpURLConnection connection = null;
    OutputStream urlConnectionOut = null;
    FileInputStream fileIn = null;

    if (monitor == null)
        monitor = new NullProgressMonitor();

    int contentLength = (int) file.length();

    if (contentLength == 0) {
        log.warn("file size of file " + file.getAbsolutePath() + " is 0 or the file does not exist");
        return;
    }

    monitor.beginTask("Uploading file " + file.getName(), contentLength);

    try {
        URL connectionURL = new URL(url);

        if (!"http".equals(connectionURL.getProtocol()))
            throw new IOException("only HTTP protocol is supported");

        connection = (HttpURLConnection) connectionURL.openConnection();
        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setReadTimeout(TIMEOUT);
        connection.setConnectTimeout(TIMEOUT);

        connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

        String contentDispositionLine = "Content-Disposition: form-data; name=\"" + file.getName()
                + "\"; filename=\"" + file.getName() + "\"" + CRLF;

        String contentTypeLine = "Content-Type: application/octet-stream; charset=ISO-8859-1" + CRLF;

        String contentTransferEncoding = "Content-Transfer-Encoding: binary" + CRLF;

        contentLength += 2 * boundary.length() + contentDispositionLine.length() + contentTypeLine.length()
                + contentTransferEncoding.length() + 4 * CRLF.length() + 3 * doubleDash.length();

        connection.setFixedLengthStreamingMode(contentLength);

        connection.connect();

        urlConnectionOut = connection.getOutputStream();

        PrintWriter writer = new PrintWriter(new OutputStreamWriter(urlConnectionOut, "US-ASCII"), true);

        writer.append(doubleDash).append(boundary).append(CRLF);
        writer.append(contentDispositionLine);
        writer.append(contentTypeLine);
        writer.append(contentTransferEncoding);
        writer.append(CRLF);
        writer.flush();

        fileIn = new FileInputStream(file);
        byte[] buffer = new byte[8192];

        for (int read = 0; (read = fileIn.read(buffer)) > 0;) {
            if (monitor.isCanceled())
                return;

            urlConnectionOut.write(buffer, 0, read);
            monitor.worked(read);
        }

        urlConnectionOut.flush();

        writer.append(CRLF);
        writer.append(doubleDash).append(boundary).append(doubleDash).append(CRLF);
        writer.close();

        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            log.debug("uploaded file " + file.getAbsolutePath() + " to " + connectionURL.getHost());
            return;
        }

        throw new IOException("failed to upload file " + file.getAbsolutePath() + connectionURL.getHost() + " ["
                + connection.getResponseMessage() + "]");
    } finally {
        IOUtils.closeQuietly(fileIn);
        IOUtils.closeQuietly(urlConnectionOut);

        if (connection != null)
            connection.disconnect();

        monitor.done();
    }
}

From source file:com.mebigfatguy.polycasso.URLFetcher.java

/**
 * retrieve arbitrary data found at a specific url
 * - either http or file urls//from   w w  w.j  a  va2 s  .  c  om
 * for http requests, sets the user-agent to mozilla to avoid
 * sites being cranky about a java sniffer
 * 
 * @param url the url to retrieve
 * @param proxyHost the host to use for the proxy
 * @param proxyPort the port to use for the proxy
 * @return a byte array of the content
 * 
 * @throws IOException the site fails to respond
 */
public static byte[] fetchURLData(String url, String proxyHost, int proxyPort) throws IOException {
    HttpURLConnection con = null;
    InputStream is = null;

    try {
        URL u = new URL(url);
        if (url.startsWith("file://")) {
            is = new BufferedInputStream(u.openStream());
        } else {
            Proxy proxy;
            if (proxyHost != null) {
                proxy = new Proxy(Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
            } else {
                proxy = Proxy.NO_PROXY;
            }
            con = (HttpURLConnection) u.openConnection(proxy);
            con.addRequestProperty("User-Agent",
                    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1092.0 Safari/536.6");
            con.addRequestProperty("Accept-Charset", "UTF-8");
            con.addRequestProperty("Accept-Language", "en-US,en");
            con.addRequestProperty("Accept", "text/html,image/*");
            con.setDoInput(true);
            con.setDoOutput(false);
            con.connect();

            is = new BufferedInputStream(con.getInputStream());
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        IOUtils.copy(is, baos);
        return baos.toByteArray();
    } finally {
        IOUtils.closeQuietly(is);
        if (con != null) {
            con.disconnect();
        }
    }
}

From source file:cn.bidaround.ytcore.util.HurlStack.java

@SuppressWarnings("deprecation")
/* package */static void setConnectionParametersForRequest(HttpURLConnection connection, Request<?> request)
        throws IOException, AuthFailureError {
    switch (request.getMethod()) {
    case Method.DEPRECATED_GET_OR_POST:
        // This is the deprecated way that needs to be handled for backwards
        // compatibility.
        // If the request's post body is null, then the assumption is that
        // the request is
        // GET. Otherwise, it is assumed that the request is a POST.
        byte[] postBody = request.getPostBody();
        if (postBody != null) {
            // Prepare output. There is no need to set Content-Length
            // explicitly,
            // since this is handled by HttpURLConnection using the size of
            // the prepared
            // output stream.
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getPostBodyContentType());
            DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            out.write(postBody);//from www .j a  v a  2 s .c o m
            out.close();
        }
        break;
    case Method.GET:
        // Not necessary to set the request method because connection
        // defaults to GET but
        // being explicit here.
        connection.setRequestMethod("GET");
        break;
    case Method.DELETE:
        connection.setRequestMethod("DELETE");
        break;
    case Method.POST:
        connection.setRequestMethod("POST");
        addBodyIfExists(connection, request);
        break;
    case Method.PUT:
        connection.setRequestMethod("PUT");
        addBodyIfExists(connection, request);
        break;
    case Method.HEAD:
        connection.setRequestMethod("HEAD");
        break;
    case Method.OPTIONS:
        connection.setRequestMethod("OPTIONS");
        break;
    case Method.TRACE:
        connection.setRequestMethod("TRACE");
        break;
    case Method.PATCH:
        connection.setRequestMethod("PATCH");
        addBodyIfExists(connection, request);
        break;
    default:
        throw new IllegalStateException("Unknown method type.");
    }
}