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:au.com.tyo.sn.shortener.GooGl.java

private static String post(String url) {
    HttpURLConnection httpcon = null;

    try {/*ww  w .jav  a  2  s . c o m*/
        httpcon = (HttpURLConnection) ((new URL(GOO_GL_REQUEST_URL).openConnection()));

        httpcon.setDoOutput(true);
        httpcon.setRequestProperty("Content-Type", "application/json");
        httpcon.setRequestProperty("Accept", "application/json");
        httpcon.setRequestMethod("POST");
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    byte[] outputBytes = { 0 };
    OutputStream os = null;
    InputStream is = null;
    BufferedReader in = null;
    StringBuilder text = new StringBuilder();

    try {
        outputBytes = ("{'longUrl': \"" + url + "\"}").getBytes("UTF-8");
        httpcon.setRequestProperty("Content-Length", Integer.toString(outputBytes.length));
        httpcon.connect();
        os = httpcon.getOutputStream();
        os.write(outputBytes);
        is = httpcon.getInputStream();
        in = new BufferedReader(new InputStreamReader(is, "UTF-8"));

        if (in != null) {
            // get page text
            String line;

            while ((line = in.readLine()) != null) {
                text.append(line);
                text.append("\n");
            }
        }

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (os != null)
                os.close();
            if (is != null)
                is.close();
            if (in != null)
                in.close();
        } catch (IOException e) {
        }
    }

    return text.toString();
}

From source file:Main.java

public static String httpPost(String urlStr, List<NameValuePair> params) {

    String paramsEncoded = "";
    if (params != null) {
        paramsEncoded = URLEncodedUtils.format(params, "UTF-8");
    }//  w  ww .ja  v a  2 s.  c om

    String result = null;
    URL url = null;
    HttpURLConnection connection = null;
    InputStreamReader in = null;
    try {
        url = new URL(urlStr);
        connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("Charset", "utf-8");
        DataOutputStream dop = new DataOutputStream(connection.getOutputStream());
        dop.writeBytes(paramsEncoded);
        dop.flush();
        dop.close();

        in = new InputStreamReader(connection.getInputStream());
        BufferedReader bufferedReader = new BufferedReader(in);
        StringBuffer strBuffer = new StringBuffer();
        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            strBuffer.append(line);
        }
        result = strBuffer.toString();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
    return result;
}

From source file:Main.java

public static String UdatePlayerBT(String userName, String device) {

    String retStr = "";

    try {//from  w w w  .  j  ava2  s . c  o m
        URL url = new URL("http://" + IP_ADDRESS + "/RiddleQuizApp/ServerSide/PostaviBTdevice.php");

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(15000);
        conn.setReadTimeout(10000);
        conn.setRequestMethod("POST");
        conn.setDoInput(true);
        conn.setDoOutput(true);

        Log.e("http", "por1");

        JSONObject data = new JSONObject();

        data.put("username", userName);
        data.put("bt_device", device);

        Log.e("http", "por3");

        Uri.Builder builder = new Uri.Builder().appendQueryParameter("action", data.toString());
        String query = builder.build().getEncodedQuery();

        Log.e("http", "por4");

        OutputStream os = conn.getOutputStream();
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
        bw.write(query);
        Log.e("http", "por5");
        bw.flush();
        bw.close();
        os.close();
        int responseCode = conn.getResponseCode();

        Log.e("http", String.valueOf(responseCode));
        if (responseCode == HttpURLConnection.HTTP_OK) {
            retStr = inputStreamToString(conn.getInputStream());
        } else
            retStr = String.valueOf("Error: " + responseCode);

        Log.e("http", retStr);

    } catch (Exception e) {
        Log.e("http", "greska");
    }
    return retStr;
}

From source file:io.github.retz.scheduler.MesosHTTPFetcher.java

static List<Map<String, Object>> fetchTasks(String master, String frameworkId, int offset, int limit)
        throws MalformedURLException {
    URL url = new URL("http://" + master + "/tasks?offset=" + offset + "&limit=" + limit);
    HttpURLConnection conn;
    try {/* w w w. j a v a  2  s  .co  m*/
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setDoOutput(true);
        return parseTasks(conn.getInputStream(), frameworkId);
    } catch (IOException e) {
        return new LinkedList<>();
    }
}

From source file:GoogleAPI.java

/**
 * Forms an HTTP request, sends it using POST method and returns the result of the request as a JSONObject.
 * //from w  w  w  .j av a2s. c  o m
 * @param url The URL to query for a JSONObject.
 * @param parameters Additional POST parameters
 * @return The translated String.
 * @throws Exception on error.
 */
protected static JSONObject retrieveJSON(final URL url, final String parameters) throws Exception {
    try {
        final HttpURLConnection uc = (HttpURLConnection) url.openConnection();
        uc.setRequestProperty("referer", referrer);
        uc.setRequestMethod("POST");
        uc.setDoOutput(true);

        final PrintWriter pw = new PrintWriter(uc.getOutputStream());
        pw.write(parameters);
        pw.close();
        uc.getOutputStream().close();

        try {
            final String result = inputStreamToString(uc.getInputStream());

            return new JSONObject(result);
        } finally { // http://java.sun.com/j2se/1.5.0/docs/guide/net/http-keepalive.html
            if (uc.getInputStream() != null) {
                uc.getInputStream().close();
            }
            if (uc.getErrorStream() != null) {
                uc.getErrorStream().close();
            }
            if (pw != null) {
                pw.close();
            }
        }
    } catch (Exception ex) {
        throw new Exception("[google-api-translate-java] Error retrieving translation.", ex);
    }
}

From source file:com.android.dialer.omni.PlaceUtil.java

/**
 * Executes a GET request and return a JSON object
 * @param url The API URL//  ww w.j av  a2s  .c o m
 * @return the JSON object
 * @throws IOException
 * @throws JSONException
 */
public static JSONObject getJsonRequest(String url) throws IOException, JSONException {
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    con.setRequestMethod("GET");

    if (DEBUG)
        Log.d(TAG, "Getting JSON from: " + url);

    con.setDoOutput(true);
    int responseCode = con.getResponseCode();

    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();

    JSONObject json = new JSONObject(response.toString());
    return json;
}

From source file:com.linkedin.pinot.controller.helix.ControllerTest.java

public static String sendDeleteRequest(String urlString) throws IOException {
    final long start = System.currentTimeMillis();

    final URL url = new URL(urlString);
    final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setRequestMethod("DELETE");
    conn.connect();/*from  ww w  . j  av  a2 s .com*/

    final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));

    final StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
        sb.append(line);
    }

    final long stop = System.currentTimeMillis();

    LOGGER.info(" Time take for Request : " + urlString + " in ms:" + (stop - start));

    return sb.toString();
}

From source file:com.linkedin.pinot.controller.helix.ControllerTest.java

public static String sendPutRequest(String urlString, String payload) throws IOException {
    LOGGER.info("Sending PUT to " + urlString + " with payload " + payload);
    final long start = System.currentTimeMillis();
    final URL url = new URL(urlString);
    final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setRequestMethod("PUT");
    final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8"));

    writer.write(payload, 0, payload.length());
    writer.flush();//from   w w w . j  a v  a  2s.com

    final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
    final StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
        sb.append(line);
    }

    final long stop = System.currentTimeMillis();

    LOGGER.info(" Time take for Request : " + urlString + " in ms:" + (stop - start));

    return sb.toString();
}

From source file:io.github.retz.scheduler.MesosHTTPFetcher.java

private static Optional<String> fetchSlaveAddr(String master, String slaveId) {
    URL url;//from  w  ww .j  a  v a 2s.c o m
    try {
        url = new URL("http://" + master + "/slaves");
    } catch (MalformedURLException e) {
        return Optional.empty();
    }
    HttpURLConnection conn;
    try {
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setDoOutput(true);
        return extractSlaveAddr(conn.getInputStream(), slaveId);
    } catch (IOException e) {
        return Optional.empty();
    }
}

From source file:com.android.nunes.sophiamobile.gsm.GcmSender.java

public static void enviar(String msg, String token) {

    try {//from  w  ww  .  j a v  a2 s.  co m
        // Prepare JSON containing the GCM message content. What to send and where to send.
        JSONObject jGcmData = new JSONObject();
        JSONObject jData = new JSONObject();
        jData.put("message", msg.trim());
        // Where to send GCM message.
        if (token != null) {
            jGcmData.put("to", token.trim());
        } else {
            jGcmData.put("to", "/topics/global");
        }
        // What to send in GCM message.
        jGcmData.put("data", jData);

        // Create connection to send GCM Message request.
        URL url = new URL("https://android.googleapis.com/gcm/send");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestProperty("Authorization", "key=" + API_KEY);
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);

        // Send GCM message content.
        OutputStream outputStream = conn.getOutputStream();
        outputStream.write(jGcmData.toString().getBytes());

        // Read GCM response.
        InputStream inputStream = conn.getInputStream();
        String resp = IOUtils.toString(inputStream);
        System.out.println(resp);
        System.out.println("Check your device/emulator for notification or logcat for "
                + "confirmation of the receipt of the GCM message.");
    } catch (IOException e) {
        System.out.println("Unable to send GCM message.");
        System.out.println("Please ensure that API_KEY has been replaced by the server "
                + "API key, and that the device's registration token is correct (if specified).");
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }
}