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:alluxio.rest.TestCase.java

/**
 * Runs the test case and returns the output.
 *//*ww w  .  j a  v  a2 s.  c  om*/
public String call() throws Exception {
    HttpURLConnection connection = (HttpURLConnection) createURL().openConnection();
    connection.setRequestMethod(mMethod);
    if (mOptions.getInputStream() != null) {
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", "application/octet-stream");
        ByteStreams.copy(mOptions.getInputStream(), connection.getOutputStream());
    }
    if (mOptions.getBody() != null) {
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", "application/json");
        ObjectMapper mapper = new ObjectMapper();
        // make sure that serialization of empty objects does not fail
        mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        OutputStream os = connection.getOutputStream();
        os.write(mapper.writeValueAsString(mOptions.getBody()).getBytes());
        os.close();
    }

    connection.connect();
    if (connection.getResponseCode() != Response.Status.OK.getStatusCode()) {
        InputStream errorStream = connection.getErrorStream();
        if (errorStream != null) {
            Assert.fail("Request failed: " + IOUtils.toString(errorStream));
        }
        Assert.fail("Request failed with status code " + connection.getResponseCode());
    }
    return getResponse(connection);
}

From source file:de.wpsverlinden.otrsspy.OtrsSpy.java

private void login() throws MalformedURLException, IOException, ExtractException {
    logger.info("Login...");
    HttpURLConnection conn = (HttpURLConnection) (new URL(host + "index.pl")).openConnection();
    conn.setRequestMethod("POST");
    conn.setInstanceFollowRedirects(false);
    conn.setDoOutput(true);
    try (DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {
        wr.writeBytes("Action=Login&RequestedURL=&Lang=" + lang + "&TimeOffset=-120&User=" + user + "&Password="
                + password);/* ww w .jav  a2 s. c  o m*/
        wr.flush();
    }
    session = extractSession(conn);
}

From source file:com.jiramot.foursquare.android.Util.java

/**
 * Connect to an HTTP URL and return the response as a string.
 *
 * 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/*from   ww w. j  a  v a2 s .c  o m*/
 * @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 {
    // random string as boundary for multi-part http post
    String strBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f";
    String endLine = "\r\n";

    OutputStream os;

    if (method.equals("GET")) {
        url = url + "?" + encodeUrl(params);
    }
    Log.d("Foursquare-Util", method + " URL: " + url);
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestProperty("User-Agent",
            System.getProperties().getProperty("http.agent") + " FoursquareAndroidSDK");
    if (!method.equals("GET")) {
        Bundle dataparams = new Bundle();
        for (String key : params.keySet()) {
            if (params.getByteArray(key) != null) {
                dataparams.putByteArray(key, params.getByteArray(key));
            }
        }

        // use method override
        if (!params.containsKey("method")) {
            params.putString("method", method);
        }

        if (params.containsKey("access_token")) {
            String decoded_token = URLDecoder.decode(params.getString("access_token"));
            params.putString("access_token", decoded_token);
        }

        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + strBoundary);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.connect();
        os = new BufferedOutputStream(conn.getOutputStream());

        os.write(("--" + strBoundary + endLine).getBytes());
        os.write((encodePostBody(params, strBoundary)).getBytes());
        os.write((endLine + "--" + strBoundary + endLine).getBytes());

        if (!dataparams.isEmpty()) {

            for (String key : dataparams.keySet()) {
                os.write(("Content-Disposition: form-data; filename=\"" + key + "\"" + endLine).getBytes());
                os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes());
                os.write(dataparams.getByteArray(key));
                os.write((endLine + "--" + strBoundary + endLine).getBytes());

            }
        }
        os.flush();
    }

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

From source file:com.yahoo.druid.hadoop.DruidHelper.java

protected List<DataSegment> getSegmentsToLoad(String dataSource, Interval interval, String overlordUrl) {
    String urlStr = "http://" + overlordUrl + "/druid/indexer/v1/action";
    logger.info("Sending request to overlord at " + urlStr);

    String requestJson = getSegmentListUsedActionJson(dataSource, interval.toString());
    logger.info("request json is " + requestJson);

    int numTries = 3; //TODO: should be configurable?
    for (int trial = 0; trial < numTries; trial++) {
        try {/*  www .j  ava 2  s  . c o  m*/
            logger.info("attempt number {} to get list of segments from overlord", trial);
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("content-type", "application/json");
            conn.setUseCaches(false);
            conn.setDoOutput(true);
            conn.setConnectTimeout(60000); //TODO: 60 secs, shud be configurable?
            OutputStream out = conn.getOutputStream();
            out.write(requestJson.getBytes());
            out.close();
            int responseCode = conn.getResponseCode();
            if (responseCode == 200) {
                ObjectMapper mapper = DruidInitialization.getInstance().getObjectMapper();
                Map<String, Object> obj = mapper.readValue(conn.getInputStream(),
                        new TypeReference<Map<String, Object>>() {
                        });
                return mapper.convertValue(obj.get("result"), new TypeReference<List<DataSegment>>() {
                });
            } else {
                logger.warn(
                        "Attempt Failed to get list of segments from overlord. response code {} , response {}",
                        responseCode, IOUtils.toString(conn.getInputStream()));
            }
        } catch (Exception ex) {
            logger.warn("Exception in getting list of segments from overlord", ex);
        }

        try {
            Thread.sleep(5000); //wait before next trial
        } catch (InterruptedException ex) {
            Throwables.propagate(ex);
        }
    }

    throw new RuntimeException(
            String.format("failed to find list of segments, dataSource[%s], interval[%s], overlord[%s]",
                    dataSource, interval, overlordUrl));
}

From source file:br.bireme.accounts.Authentication.java

public JSONObject getUser(final String user, final String password) throws IOException, ParseException {
    if (user == null) {
        throw new NullPointerException("user");
    }//from  w  w w  .  j  a  v a  2s.  co m
    if (password == null) {
        throw new NullPointerException("password");
    }

    final JSONObject parameters = new JSONObject();
    parameters.put("username", user);
    parameters.put("password", password);
    parameters.put("service", SERVICE_NAME);
    parameters.put("format", "json");

    //final URL url = new URL("http", host, port, DEFAULT_PATH);
    final URL url = new URL("http://" + host + DEFAULT_PATH);
    final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestProperty("Content-Type", "application/json");
    connection.setDoInput(true);
    connection.setDoOutput(true);
    connection.connect();

    final StringBuilder builder = new StringBuilder();
    final BufferedWriter writer = new BufferedWriter(
            new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));

    //final String message = parameters.toJSONString();
    //System.out.println(message);

    writer.write(parameters.toJSONString());
    writer.newLine();
    writer.close();

    final int respCode = connection.getResponseCode();
    final boolean respCodeOk = (respCode == 200);
    final BufferedReader reader;

    if (respCodeOk) {
        reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    } else {
        reader = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
    }

    while (true) {
        final String line = reader.readLine();
        if (line == null) {
            break;
        }
        builder.append(line);
        builder.append("\n");
    }

    reader.close();

    if (!respCodeOk && (respCode != 401)) {
        throw new IOException(builder.toString());
    }

    return (JSONObject) new JSONParser().parse(builder.toString());
}

From source file:br.com.ufc.palestrasufc.twitter.Util.java

/**
 * Connect to an HTTP URL and return the response as a string.
 * /*from ww  w .j ava  2  s . c  o 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 {
    // random string as boundary for multi-part http post
    String strBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f";
    String endLine = "\r\n";

    OutputStream os;

    if (method.equals("GET")) {
        url = url + "?" + encodeUrl(params);
    }
    Log.d("Twitter-Util", method + " URL: " + url);
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestProperty("User-Agent",
            System.getProperties().getProperty("http.agent") + " TwitterAndroidSDK");
    if (!method.equals("GET")) {
        Bundle dataparams = new Bundle();
        for (String key : params.keySet()) {
            if (params.getByteArray(key) != null) {
                dataparams.putByteArray(key, params.getByteArray(key));
            }
        }

        // use method override
        if (!params.containsKey("method")) {
            params.putString("method", method);
        }

        if (params.containsKey("access_token")) {
            String decoded_token = URLDecoder.decode(params.getString("access_token"));
            params.putString("access_token", decoded_token);
        }

        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + strBoundary);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.connect();
        os = new BufferedOutputStream(conn.getOutputStream());

        os.write(("--" + strBoundary + endLine).getBytes());
        os.write((encodePostBody(params, strBoundary)).getBytes());
        os.write((endLine + "--" + strBoundary + endLine).getBytes());

        if (!dataparams.isEmpty()) {

            for (String key : dataparams.keySet()) {
                os.write(("Content-Disposition: form-data; filename=\"" + key + "\"" + endLine).getBytes());
                os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes());
                os.write(dataparams.getByteArray(key));
                os.write((endLine + "--" + strBoundary + endLine).getBytes());

            }
        }
        os.flush();
    }

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

From source file:ext.services.network.TestNetworkUtils.java

/**
 * Test method for.// w w w .  j  a  v a2  s  .  c  o  m
 *
 * @throws Exception the exception
 * {@link ext.services.network.NetworkUtils#getImage(java.net.URLConnection)}.
 */
public void testGetImage() throws Exception {
    HttpURLConnection connection = NetworkUtils.getConnection(URL, null);
    assertNotNull(connection);
    connection.setDoOutput(true);
    assertNull(NetworkUtils.getImage(connection));
}

From source file:io.github.retz.web.WebConsoleTest.java

@Test
public void status() throws Exception {
    Job job = new Job("fooapp", "foocmd", null, new Range(12000, 0), new Range(12000, 0));
    JobQueue.push(job);/*  www. jav  a2  s. co  m*/
    assert webClient.connect();

    URL url = new URL("http://localhost:24301/status");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("GET");
    conn.setDoOutput(true);
    Response res = mapper.readValue(conn.getInputStream(), Response.class);
    assert res instanceof StatusResponse;
    StatusResponse statusResponse = (StatusResponse) res;

    System.err.println(statusResponse.queueLength());
    assert statusResponse.queueLength() == 1;
    assert statusResponse.sessionLength() == 1;
    webClient.disconnect();
}

From source file:com.qburst.android.linkedin.Util.java

/**
 * Connect to an HTTP URL and return the response as a string.
 * /*w  w w .j  a v  a2 s  .com*/
 * 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 {
    // random string as boundary for multi-part http post
    String strBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f";
    String endLine = "\r\n";

    OutputStream os;

    if (method.equals("GET")) {
        url = url + "?" + encodeUrl(params);
    }
    Log.d("Twitter-Util", method + " URL: " + url);
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestProperty("User-Agent",
            System.getProperties().getProperty("http.agent") + " LinkedInAndroidSDK");
    if (!method.equals("GET")) {
        Bundle dataparams = new Bundle();
        for (String key : params.keySet()) {
            if (params.getByteArray(key) != null) {
                dataparams.putByteArray(key, params.getByteArray(key));
            }
        }

        // use method override
        if (!params.containsKey("method")) {
            params.putString("method", method);
        }

        if (params.containsKey("access_token")) {
            String decoded_token = URLDecoder.decode(params.getString("access_token"));
            params.putString("access_token", decoded_token);
        }

        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + strBoundary);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.connect();
        os = new BufferedOutputStream(conn.getOutputStream());

        os.write(("--" + strBoundary + endLine).getBytes());
        os.write((encodePostBody(params, strBoundary)).getBytes());
        os.write((endLine + "--" + strBoundary + endLine).getBytes());

        if (!dataparams.isEmpty()) {

            for (String key : dataparams.keySet()) {
                os.write(("Content-Disposition: form-data; filename=\"" + key + "\"" + endLine).getBytes());
                os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes());
                os.write(dataparams.getByteArray(key));
                os.write((endLine + "--" + strBoundary + endLine).getBytes());

            }
        }
        os.flush();
    }

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

From source file:ext.services.network.TestNetworkUtils.java

/**
 * Test get image disabled./*w  w w.  ja  v a 2s. c o  m*/
 * 
 *
 * @throws Exception the exception
 */
public void testGetImageDisabled() throws Exception {
    HttpURLConnection connection = NetworkUtils.getConnection(URL, null);
    assertNotNull(connection);
    connection.setDoOutput(true);
    Conf.setProperty(Const.CONF_NETWORK_NONE_INTERNET_ACCESS, "true");
    assertNull(NetworkUtils.getImage(connection));
}