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.heraldapp.share.facebook.Util.java

/**
 * Connect to an HTTP URL and return the response as a string.
 * /*from w  w w. j  a  v a 2s  . co  m*/
 * Note that the HTTP method override is used on non-GET requests. (i.e.
 * requests are made as "POST" with method specified in the body).
 * 
 * @param url
 *            - the resource to open: must be a welformed URL
 * @param method
 *            - the HTTP method to use ("GET", "POST", etc.)
 * @param params
 *            - the query parameter for the URL (e.g. access_token=foo)
 * @return the URL contents as a String
 * @throws MalformedURLException
 *             - if the URL format is invalid
 * @throws IOException
 *             - if a network problem occurs
 */
public static String openUrl(String url, String method, Bundle params)
        throws MalformedURLException, IOException {
    if (method.equals("GET")) {
        url = url + "?" + encodeUrl(params);
    }
    String response = "";
    HttpURLConnection conn = null;
    try {
        conn = (HttpURLConnection) new URL(url).openConnection();
        conn.setRequestProperty("User-Agent",
                System.getProperties().getProperty("http.agent") + " FacebookAndroidSDK");
        conn.setReadTimeout(10000);
        conn.setConnectTimeout(10000);
        if (!method.equals("GET")) {
            // use method override
            params.putString("method", method);
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.getOutputStream().write(encodeUrl(params).getBytes("UTF-8"));
        }

        response = read(conn.getInputStream());
    } catch (FileNotFoundException e) {
        // Error Stream contains JSON that we can parse to a FB error
        response = read(conn.getErrorStream());
    } catch (SocketTimeoutException e) {
        return response;
    }
    return response;
}

From source file:com.cloudbees.workflow.Util.java

public static int postToJenkins(Jenkins jenkins, String url, String content, String contentType)
        throws IOException {
    String jenkinsUrl = jenkins.getRootUrl();
    URL urlObj = new URL(jenkinsUrl + url.replace("/jenkins/job/", "job/"));
    HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection();

    try {/*from  w ww  . jav a  2 s.  co  m*/
        conn.setRequestMethod("POST");

        // Set the crumb header, otherwise the POST may be rejected.
        NameValuePair crumbHeader = getCrumbHeaderNVP(jenkins);
        conn.setRequestProperty(crumbHeader.getName(), crumbHeader.getValue());

        if (contentType != null) {
            conn.setRequestProperty("Content-Type", contentType);
        }
        if (content != null) {
            byte[] bytes = content.getBytes(Charset.forName("UTF-8"));

            conn.setDoOutput(true);

            conn.setRequestProperty("Content-Length", String.valueOf(bytes.length));
            final OutputStream os = conn.getOutputStream();
            try {
                os.write(bytes);
                os.flush();
            } finally {
                os.close();
            }
        }

        return conn.getResponseCode();
    } finally {
        conn.disconnect();
    }
}

From source file:com.alibaba.akita.io.HttpInvoker.java

/**
 * post with files using URLConnection Impl
 * @param actionUrl URL to post/* w  w  w. j a  v a  2s .c  o  m*/
 * @param params params to post
 * @param files files to post, support multi-files
 * @return response in String format
 * @throws IOException
 */
public static String postWithFilesUsingURLConnection(String actionUrl, ArrayList<NameValuePair> params,
        Map<String, File> files) throws AkInvokeException {
    try {
        String BOUNDARY = java.util.UUID.randomUUID().toString();
        String PREFIX = "--", LINEND = "\r\n";
        String MULTIPART_FROM_DATA = "multipart/form-data";
        String CHARSET = "UTF-8";

        URL uri = new URL(actionUrl);
        HttpURLConnection conn = (HttpURLConnection) uri.openConnection();

        conn.setReadTimeout(60 * 1000);
        conn.setDoInput(true); // permit input
        conn.setDoOutput(true); // permit output
        conn.setUseCaches(false);
        conn.setRequestMethod("POST"); // Post Method
        conn.setRequestProperty("connection", "keep-alive");
        conn.setRequestProperty("Charsert", "UTF-8");
        conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY);

        // firstly string params to add
        StringBuilder sb = new StringBuilder();
        for (NameValuePair nameValuePair : params) {
            sb.append(PREFIX);
            sb.append(BOUNDARY);
            sb.append(LINEND);
            sb.append("Content-Disposition: form-data; name=\"" + nameValuePair.getName() + "\"" + LINEND);
            sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);
            sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
            sb.append(LINEND);
            sb.append(nameValuePair.getValue());
            sb.append(LINEND);
        }

        DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
        outStream.write(sb.toString().getBytes());
        // send files secondly
        if (files != null) {
            int num = 0;
            for (Map.Entry<String, File> file : files.entrySet()) {
                num++;
                if (file.getKey() == null || file.getValue() == null)
                    continue;
                else {
                    if (!file.getValue().exists()) {
                        throw new AkInvokeException(AkInvokeException.CODE_FILE_NOT_FOUND,
                                "The file to upload is not found.");
                    }
                }
                StringBuilder sb1 = new StringBuilder();
                sb1.append(PREFIX);
                sb1.append(BOUNDARY);
                sb1.append(LINEND);
                sb1.append("Content-Disposition: form-data; name=\"file" + num + "\"; filename=\""
                        + file.getKey() + "\"" + LINEND);
                sb1.append("Content-Type: application/octet-stream; charset=" + 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());
            }
        }

        // request end flag
        byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
        outStream.write(end_data);
        outStream.flush();
        // get response code
        int res = conn.getResponseCode();
        InputStream in = conn.getInputStream();
        StringBuilder sb2 = new StringBuilder();
        if (res == 200) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf-8"), 8192);
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb2.append(line + "\n");
            }
            reader.close();
        }
        outStream.close();
        conn.disconnect();
        return sb2.toString();
    } catch (IOException ioe) {
        throw new AkInvokeException(AkInvokeException.CODE_IO_EXCEPTION, "IO Exception", ioe);
    }
}

From source file:com.gmobi.poponews.util.HttpHelper.java

public static Response upload(String url, InputStream is) {
    Response response = new Response();
    String boundary = Long.toHexString(System.currentTimeMillis());
    HttpURLConnection connection = null;
    try {// w ww. j  a  v a 2 s .  c  om
        URL httpURL = new URL(url);
        connection = (HttpURLConnection) httpURL.openConnection();
        connection.setConnectTimeout(15000);
        connection.setReadTimeout(30000);
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        byte[] st = ("--" + boundary + "\r\n"
                + "Content-Disposition: form-data; name=\"file\"; filename=\"data\"\r\n"
                + "Content-Type: application/octet-stream; charset=UTF-8\r\n"
                + "Content-Transfer-Encoding: binary\r\n\r\n").getBytes();
        byte[] en = ("\r\n--" + boundary + "--\r\n").getBytes();
        connection.setRequestProperty("Content-Length", String.valueOf(st.length + en.length + is.available()));
        OutputStream os = connection.getOutputStream();
        os.write(st);
        FileHelper.copy(is, os);
        os.write(en);
        os.flush();
        os.close();
        response.setStatusCode(connection.getResponseCode());
        connection = null;
    } catch (Exception e) {
        Logger.error(e);
    }

    return response;
}

From source file:com.rutarget.UpsourceReviewStatsExtension.PageExtension.java

private static <T> T request(String method, @Nullable Object parameter, Class<T> clazz) throws IOException {
    String address = UPSOURCE_API_URL + method;
    URL url = new URL(address);
    @SuppressWarnings("ConstantConditions")
    HttpURLConnection c = (HttpURLConnection) (PROXY != null ? url.openConnection(PROXY)
            : url.openConnection());//from  w w  w . j a  va  2 s . com
    String authString = UPSOURCE_USERNAME + ":" + UPSOURCE_PASSWORD;
    //Base64 doesn't look thread safe, therefore we create new instance for each occasion
    c.setRequestProperty("Authorization", "Basic " + new String(new Base64().encode(authString.getBytes())));

    if (parameter != null) {
        String output = GSON.toJson(parameter);
        c.setDoOutput(true);
        c.setRequestMethod("POST");
        c.setRequestProperty("Content-Type", "application/json");
        c.setRequestProperty("Content-Length", String.valueOf(output.length()));
        c.getOutputStream().write(output.getBytes("UTF-8"));
    }
    InputStream inputStream = c.getInputStream();
    String response = IOUtils.toString(inputStream);
    try {
        JsonObject element = (JsonObject) new JsonParser().parse(response);
        return GSON.fromJson(element.get("result"), clazz);
    } catch (Exception e) {
        throw new IOException(
                "Failed to parse response " + escapeToHtmlAttribute(response) + ": " + e.getMessage());
    }
}

From source file:com.codelanx.codelanxlib.logging.Debugger.java

/**
 * Sends a JSON payload to a URL specified by the string parameter
 * //w  w  w. j  a v  a2 s .  c om
 * @since 0.1.0
 * @version 0.1.0
 * 
 * @param url The URL to report to
 * @param payload The JSON payload to send via POST
 * @throws IOException If the sending failed
 */
private static void send(String url, JSONObject payload) throws IOException {
    URL loc = new URL(url);
    HttpURLConnection http = (HttpURLConnection) loc.openConnection();
    http.setRequestMethod("POST");
    http.setRequestProperty("Content-Type", "application/json");
    http.setUseCaches(false);
    http.setDoOutput(true);
    try (DataOutputStream wr = new DataOutputStream(http.getOutputStream())) {
        wr.writeBytes(payload.toJSONString());
        wr.flush();
    }
}

From source file:com.memetix.mst.MicrosoftTranslatorAPI.java

/**
 * Forms an HTTP request, sends it using GET method and returns the result of the request as a String.
 * //from w ww.java2  s  . com
 * @param url The URL to query for a String response.
 * @return The translated String.
 * @throws Exception on error.
 */
private static String retrieveResponse(final URL url) throws Exception {
    if (clientId != null && clientSecret != null && System.currentTimeMillis() > tokenExpiration) {
        String tokenJson = getToken(clientId, clientSecret);
        Integer expiresIn = Integer
                .parseInt((String) ((JSONObject) JSONValue.parse(tokenJson)).get("expires_in"));
        tokenExpiration = System.currentTimeMillis() + ((expiresIn * 1000) - 1);
        token = "Bearer " + (String) ((JSONObject) JSONValue.parse(tokenJson)).get("access_token");
    }
    final HttpURLConnection uc = (HttpURLConnection) url.openConnection();
    if (referrer != null)
        uc.setRequestProperty("referer", referrer);
    uc.setRequestProperty("Content-Type", contentType + "; charset=" + ENCODING);
    uc.setRequestProperty("Accept-Charset", ENCODING);
    if (token != null) {
        uc.setRequestProperty("Authorization", token);
    }
    uc.setRequestMethod("GET");
    uc.setDoOutput(true);

    try {
        final int responseCode = uc.getResponseCode();
        final String result = inputStreamToString(uc.getInputStream());
        if (responseCode != 200) {
            throw new Exception("Error from Microsoft Translator API: " + result);
        }
        return result;
    } finally {
        if (uc != null) {
            uc.disconnect();
        }
    }
}

From source file:org.wso2.carbon.appmanager.integration.ui.Util.HttpUtil.java

public static HttpResponse doDelete(URL endpoint, Map<String, String> headers) throws Exception {
    HttpURLConnection urlConnection = null;
    try {//from   w  w  w .j  av a 2 s . c om
        urlConnection = (HttpURLConnection) endpoint.openConnection();
        try {
            urlConnection.setRequestMethod("DELETE");
        } catch (ProtocolException e) {
            throw new Exception("Shouldn't happen: HttpURLConnection doesn't support Delete??", e);
        }
        urlConnection.setDoOutput(true);
        urlConnection.setDoInput(true);
        urlConnection.setUseCaches(false);
        urlConnection.setAllowUserInteraction(false);

        // setting headers
        if (headers != null && headers.size() > 0) {
            Iterator<String> itr = headers.keySet().iterator();
            while (itr.hasNext()) {
                String key = itr.next();
                urlConnection.setRequestProperty(key, headers.get(key));
            }
        }

        // Get the response
        StringBuilder sb = new StringBuilder();
        BufferedReader rd = null;
        try {
            rd = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            String line;
            while ((line = rd.readLine()) != null) {
                sb.append(line);
            }
        } catch (FileNotFoundException ignored) {
        } finally {
            if (rd != null) {
                rd.close();
            }
        }
        Iterator<String> itr = urlConnection.getHeaderFields().keySet().iterator();
        Map<String, String> responseHeaders = new HashMap();
        while (itr.hasNext()) {
            String key = itr.next();
            if (key != null) {
                responseHeaders.put(key, urlConnection.getHeaderField(key));
            }
        }
        return new HttpResponse(sb.toString(), urlConnection.getResponseCode(), responseHeaders);

    } catch (IOException e) {
        throw new Exception("Connection error (is server running at " + endpoint + " ?): " + e);
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
}

From source file:org.wso2.carbon.appmanager.integration.ui.Util.HttpUtil.java

public static HttpResponse doPut(URL endpoint, String postBody, Map<String, String> headers) throws Exception {
    HttpURLConnection urlConnection = null;
    try {//from   w w  w.ja  v a 2 s .  c o  m
        urlConnection = (HttpURLConnection) endpoint.openConnection();
        try {
            urlConnection.setRequestMethod("PUT");
        } catch (ProtocolException e) {
            throw new Exception("Shouldn't happen: HttpURLConnection doesn't support POST??", e);
        }
        urlConnection.setDoOutput(true);

        if (headers != null && headers.size() > 0) {
            Iterator<String> itr = headers.keySet().iterator();
            while (itr.hasNext()) {
                String key = itr.next();
                urlConnection.setRequestProperty(key, headers.get(key));
            }
        }
        OutputStream out = urlConnection.getOutputStream();
        try {
            Writer writer = new OutputStreamWriter(out, "UTF-8");
            writer.write(postBody);
            writer.close();
        } catch (IOException e) {
            throw new Exception("IOException while puting data", e);
        } finally {
            if (out != null) {
                out.close();
            }
        }

        // Get the response
        StringBuilder sb = new StringBuilder();
        BufferedReader rd = null;
        try {
            rd = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            String line;
            while ((line = rd.readLine()) != null) {
                sb.append(line);
            }
        } catch (FileNotFoundException ignored) {
        } finally {
            if (rd != null) {
                rd.close();
            }
        }
        Iterator<String> itr = urlConnection.getHeaderFields().keySet().iterator();
        Map<String, String> responseHeaders = new HashMap();
        while (itr.hasNext()) {
            String key = itr.next();
            if (key != null) {
                responseHeaders.put(key, urlConnection.getHeaderField(key));
            }
        }
        return new HttpResponse(sb.toString(), urlConnection.getResponseCode(), responseHeaders);

    } catch (IOException e) {
        throw new Exception("Connection error (is server running at " + endpoint + " ?): " + e);
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
}

From source file:org.akita.io.HttpInvoker.java

/**
 * post with files using URLConnection Impl
 * @param actionUrl URL to post//from  ww  w .j a  va  2s  .  c o m
 * @param params params to post
 * @param files files to post, support multi-files
 * @return response in String format
 * @throws IOException
 */
public static String postWithFilesUsingURLConnection(String actionUrl, ArrayList<NameValuePair> params,
        Map<String, File> files) throws AkInvokeException {
    try {
        Log.v(TAG, "post:" + actionUrl);
        if (params != null) {
            Log.v(TAG, "params:=====================");
            for (NameValuePair nvp : params) {
                Log.v(TAG, nvp.getName() + "=" + nvp.getValue());
            }
            Log.v(TAG, "params end:=====================");
        }

        String BOUNDARY = java.util.UUID.randomUUID().toString();
        String PREFIX = "--", LINEND = "\r\n";
        String MULTIPART_FROM_DATA = "multipart/form-data";
        String CHARSET = "UTF-8";

        URL uri = new URL(actionUrl);
        HttpURLConnection conn = (HttpURLConnection) uri.openConnection();

        conn.setReadTimeout(60 * 1000);
        conn.setDoInput(true); // permit input
        conn.setDoOutput(true); // permit output
        conn.setUseCaches(false);
        conn.setRequestMethod("POST"); // Post Method
        conn.setRequestProperty("connection", "keep-alive");
        conn.setRequestProperty("Charsert", "UTF-8");
        conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY);

        // firstly string params to add
        StringBuilder sb = new StringBuilder();
        for (NameValuePair nameValuePair : params) {
            sb.append(PREFIX);
            sb.append(BOUNDARY);
            sb.append(LINEND);
            sb.append("Content-Disposition: form-data; name=\"" + nameValuePair.getName() + "\"" + LINEND);
            sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);
            sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
            sb.append(LINEND);
            sb.append(nameValuePair.getValue());
            sb.append(LINEND);
        }

        DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
        outStream.write(sb.toString().getBytes());
        // send files secondly
        if (files != null) {
            int num = 0;
            for (Map.Entry<String, File> file : files.entrySet()) {
                num++;
                if (file.getKey() == null || file.getValue() == null)
                    continue;
                else {
                    if (!file.getValue().exists()) {
                        throw new AkInvokeException(AkInvokeException.CODE_FILE_NOT_FOUND,
                                "The file to upload is not found.");
                    }
                }
                StringBuilder sb1 = new StringBuilder();
                sb1.append(PREFIX);
                sb1.append(BOUNDARY);
                sb1.append(LINEND);
                sb1.append("Content-Disposition: form-data; name=\"" + file.getKey() + "\"; filename=\""
                        + file.getKey() + "\"" + LINEND);
                sb1.append("Content-Type: application/octet-stream; charset=" + 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());
            }
        }

        // request end flag
        byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
        outStream.write(end_data);
        outStream.flush();
        // get response code
        int res = conn.getResponseCode();
        InputStream in = conn.getInputStream();
        StringBuilder sb2 = new StringBuilder();
        if (res == 200) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf-8"), 8192);
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb2.append(line + "\n");
            }
            reader.close();
        }
        outStream.close();
        conn.disconnect();
        Log.v(TAG, "response:" + sb2.toString());
        return sb2.toString();
    } catch (IOException ioe) {
        throw new AkInvokeException(AkInvokeException.CODE_IO_EXCEPTION, "IO Exception", ioe);
    }
}