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.book.jtm.chap03.HttpClientDemo.java

public static void sendRequest(String method, String url) throws IOException {
    InputStream is = null;/*from w  ww.  ja  va  2s .  c o  m*/
    try {
        URL newUrl = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) newUrl.openConnection();
        // ?10
        conn.setReadTimeout(10000);
        // 15
        conn.setConnectTimeout(15000);
        // ?,GET"GET",post"POST"
        conn.setRequestMethod("GET");
        // ??
        conn.setDoInput(true);
        // ??,????
        conn.setDoOutput(true);
        // Header
        conn.setRequestProperty("Connection", "Keep-Alive");
        // ?
        List<NameValuePair> paramsList = new ArrayList<NameValuePair>();
        paramsList.add(new BasicNameValuePair("username", "mr.simple"));
        paramsList.add(new BasicNameValuePair("pwd", "mypwd"));
        writeParams(conn.getOutputStream(), paramsList);

        // ?
        conn.connect();
        is = conn.getInputStream();
        // ?
        String result = convertStreamToString(is);
        Log.i("", "###  : " + result);
    } finally {
        if (is != null) {
            is.close();
        }
    }
}

From source file:com.thyn.backend.gcm.GcmSender.java

public static String addDeviceToDeviceGroup(String notification_key_name, String notification_key,
        String registration_token) {
    String resp = null;//from w  w  w  . j a  v a  2s .c o  m
    try {
        // Prepare JSON containing the GCM message content. What to send and where to send.
        JSONObject jGcmData = new JSONObject();

        // Where to send GCM message.
        if (notification_key_name != null && registration_token != null) {
            jGcmData.put("operation", "add");
            jGcmData.put("notification_key_name", notification_key_name.trim());
            jGcmData.put("notification_key", notification_key.trim());
            jGcmData.put("registration_ids", new JSONArray("[\"" + registration_token + "\"]"));
        } else {
            Logger.logError("Error", new NullPointerException());
            return null;
        }

        // Create connection to send GCM Message request.
        URL url = new URL("https://android.googleapis.com/gcm/notification");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestProperty("Authorization", "key=" + API_KEY);
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("project_id", SENDER_ID);
        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();
        resp = IOUtils.toString(inputStream);

    } catch (IOException e) {
        Logger.logError("Unable to add Device to Device group.", e);

    }
    return resp;
}

From source file:com.thyn.backend.gcm.GcmSender.java

public static String createDeviceGroup(String notification_key_name, String registration_token) {
    String Response_Notification_Key = null;
    try {//w w w.java  2s  .c om
        // Prepare JSON containing the GCM message content. What to send and where to send.
        JSONObject jGcmData = new JSONObject();

        // Where to send GCM message.
        if (notification_key_name != null && registration_token != null) {
            jGcmData.put("operation", "create");
            jGcmData.put("notification_key_name", notification_key_name.trim());
            jGcmData.put("registration_ids", new JSONArray("[\"" + registration_token + "\"]"));
        } else {
            Logger.logError("Error", new NullPointerException());
            return null;
        }
        Logger.logInfo(jGcmData.toString());

        // Create connection to send GCM Message request.
        URL url = new URL("https://android.googleapis.com/gcm/notification");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestProperty("Authorization", "key=" + API_KEY);
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("project_id", SENDER_ID);
        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);
        Logger.logInfo("the response from GCM server is: " + resp);
        JSONObject jResp = new JSONObject(resp);
        Response_Notification_Key = jResp.getString("notification_key");

    } catch (IOException e) {
        Logger.logError("Unable to create a device group.", e);

    }
    return Response_Notification_Key;
}

From source file:com.denimgroup.threadfix.service.defects.RestUtils.java

public static InputStream postUrl(String urlString, String data, String username, String password) {
    URL url = null;/*from   ww  w . j av  a2 s. com*/
    try {
        url = new URL(urlString);
    } catch (MalformedURLException e) {
        log.warn("URL used for POST was bad: '" + urlString + "'");
        return null;
    }

    HttpURLConnection httpConnection = null;
    OutputStreamWriter outputWriter = null;
    try {
        httpConnection = (HttpURLConnection) url.openConnection();

        setupAuthorization(httpConnection, username, password);

        httpConnection.addRequestProperty("Content-Type", "application/json");
        httpConnection.addRequestProperty("Accept", "application/json");

        httpConnection.setDoOutput(true);
        outputWriter = new OutputStreamWriter(httpConnection.getOutputStream());
        outputWriter.write(data);
        outputWriter.flush();

        InputStream is = httpConnection.getInputStream();

        return is;
    } catch (IOException e) {
        log.warn("IOException encountered trying to post to URL with message: " + e.getMessage());
        if (httpConnection == null) {
            log.warn(
                    "HTTP connection was null so we cannot do further debugging of why the HTTP request failed");
        } else {
            try {
                InputStream errorStream = httpConnection.getErrorStream();
                if (errorStream == null) {
                    log.warn("Error stream from HTTP connection was null");
                } else {
                    log.warn(
                            "Error stream from HTTP connection was not null. Attempting to get response text.");
                    String postErrorResponse = IOUtils.toString(errorStream);
                    log.warn("Error text in response was '" + postErrorResponse + "'");
                }
            } catch (IOException e2) {
                log.warn("IOException encountered trying to read the reason for the previous IOException: "
                        + e2.getMessage(), e2);
            }
        }
    } finally {
        if (outputWriter != null) {
            try {
                outputWriter.close();
            } catch (IOException e) {
                log.warn("Failed to close output stream in postUrl.", e);
            }
        }
    }

    return null;
}

From source file:Main.java

public static String getPosthtml(String posturl, String postData, String encode) {

    String html = "";
    URL url;//from w  w w. java2  s .  c om
    try {
        url = new URL(posturl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("User-Agent", userAgent);

        String postDataStr = postData;
        byte[] bytes = postDataStr.getBytes("utf-8");
        connection.setRequestProperty("Content-Length", "" + bytes.length);
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setRequestProperty("Cache-Control", "no-cache");
        connection.setDoOutput(true);
        connection.setReadTimeout(timeout);
        connection.setFollowRedirects(true);
        connection.connect();
        OutputStream outStrm = connection.getOutputStream();
        outStrm.write(bytes);
        outStrm.flush();
        outStrm.close();
        InputStream inStrm = connection.getInputStream();

        BufferedReader br = new BufferedReader(new InputStreamReader(inStrm, encode));

        String temp = "";
        while ((temp = br.readLine()) != null) {
            html += (temp + '\n');
        }
        br.close();
        connection.disconnect();

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

}

From source file:com.thyn.backend.gcm.GcmSender.java

public static String removeDeviceFromDeviceGroup(String notification_key_name, String notification_key,
        String registration_token) {
    String Response_Notification_Key = null;
    try {/*from w w w .  j a va2s .  c o m*/
        // Prepare JSON containing the GCM message content. What to send and where to send.
        JSONObject jGcmData = new JSONObject();

        // Where to send GCM message.
        if (notification_key_name != null && registration_token != null) {
            jGcmData.put("operation", "remove");
            jGcmData.put("notification_key_name", notification_key_name.trim());
            jGcmData.put("notification_key", notification_key.trim());
            jGcmData.put("registration_ids", new JSONArray("[\"" + registration_token + "\"]"));
        } else {
            Logger.logError("Error", new NullPointerException());
            return null;
        }

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

        // Send GCM message content.
        OutputStream outputStream = conn.getOutputStream();
        Logger.logInfo("the message sent is" + jGcmData.toString());
        outputStream.write(jGcmData.toString().getBytes());

        // Read GCM response.
        InputStream inputStream = conn.getInputStream();
        String resp = IOUtils.toString(inputStream);
        Logger.logInfo("the response from GSM server is: " + resp);
        JSONObject jResp = new JSONObject(resp);
        Response_Notification_Key = jResp.getString("notification_key");

    } catch (IOException e) {
        Logger.logError("Unable to remove Device from Device group.", e);

    }
    return Response_Notification_Key;
}

From source file:bluevia.SendSMS.java

public static void setFacebookWallPost(String userEmail, String post) {
    try {//  w ww.  j a v a  2s.  c o m

        Properties facebookAccount = Util.getNetworkAccount(userEmail, Util.FaceBookOAuth.networkID);

        if (facebookAccount != null) {
            String access_key = facebookAccount.getProperty(Util.FaceBookOAuth.networkID + ".access_key");

            com.google.appengine.api.urlfetch.FetchOptions.Builder.doNotValidateCertificate();

            Entity blueviaUser = Util.getUser(userEmail);

            //FIXME
            URL fbAPI = new URL(
                    "https://graph.facebook.com/" + (String) blueviaUser.getProperty("alias") + "/feed");
            HttpURLConnection request = (HttpURLConnection) fbAPI.openConnection();

            String content = String.format("access_token=%s&message=%s", access_key,
                    URLEncoder.encode(post, "UTF-8"));

            request.setRequestMethod("POST");
            request.setRequestProperty("Content-Type", "javascript/text");
            request.setRequestProperty("Content-Length", "" + Integer.toString(content.getBytes().length));
            request.setDoOutput(true);
            request.setDoInput(true);

            OutputStream os = request.getOutputStream();
            os.write(content.getBytes());
            os.flush();
            os.close();

            BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
            int rc = request.getResponseCode();
            if (rc == HttpURLConnection.HTTP_OK) {
                StringBuffer body = new StringBuffer();
                String line;

                do {
                    line = br.readLine();
                    if (line != null)
                        body.append(line);
                } while (line != null);

                JSONObject id = new JSONObject(body.toString());
            } else
                log.severe(
                        String.format("Error %d posting FaceBook wall:%s\n", rc, request.getResponseMessage()));
        }
    } catch (Exception e) {
        log.severe(String.format("Exception posting FaceBook wall: %s", e.getMessage()));
    }
}

From source file:com.android.volley.toolbox.http.HurlStack.java

private static void addBodyIfExists(HttpURLConnection connection, Request<?> request)
        throws IOException, AuthFailureError {
    if (request.containsFile()) {
        setConnectionParametersForMultipartRequest(connection, request);
    } else {//  w  ww.  ja  v  a2s.  com
        byte[] body = request.getBody();
        if (body != null) {
            connection.setDoOutput(true);
            connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getBodyContentType());
            DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            out.write(body);
            out.close();
        }
    }
}

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

/**
 * Gets the OAuth access token.//from   w  ww.  ja va  2 s . com
 * @param clientId The Client key.
 * @param clientSecret The Client Secret
 */
public static String getToken(final String clientId, final String clientSecret) throws Exception {
    final String params = "grant_type=client_credentials&scope=http://api.microsofttranslator.com"
            + "&client_id=" + URLEncoder.encode(clientId, ENCODING) + "&client_secret="
            + URLEncoder.encode(clientSecret, ENCODING);

    final URL url = new URL(DatamarketAccessUri);
    final HttpURLConnection uc = (HttpURLConnection) url.openConnection();
    if (referrer != null)
        uc.setRequestProperty("referer", referrer);
    uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=" + ENCODING);
    uc.setRequestProperty("Accept-Charset", ENCODING);
    uc.setRequestMethod("POST");
    uc.setDoOutput(true);

    OutputStreamWriter wr = new OutputStreamWriter(uc.getOutputStream());
    wr.write(params);
    wr.flush();

    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:com.reactivetechnologies.jaxrs.RestServerTest.java

static String sendPost(String url, String content) throws IOException {

    StringBuilder response = new StringBuilder();
    HttpURLConnection con = null;
    BufferedReader in = null;// w  ww.j  a v  a  2  s . com
    try {
        URL obj = new URL(url);
        con = (HttpURLConnection) obj.openConnection();

        // optional default is GET
        con.setRequestMethod("POST");

        //add request header
        con.setRequestProperty("User-Agent", "Mozilla/5.0");
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

        // Send post request
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeUTF(content);
        wr.flush();
        wr.close();

        int responseCode = con.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
        } else {
            throw new IOException("Response Code: " + responseCode);
        }

        return response.toString();
    } catch (IOException e) {
        throw e;
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {

            }
        }
        if (con != null) {
            con.disconnect();
        }
    }

}