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.fluidops.iwb.luxid.LuxidExtractor.java

public static String authenticate() throws Exception {
    String token = "";

    /* ***** Authentication ****** */
    String auth = "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" "
            + "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"> <SOAP-ENV:Body> <ns1:authenticate xmlns:ns1=\"http://luxid.temis.com/ws/types\"> "
            + "<ns1:userName>" + Config.getConfig().getLuxidUserName() + "</ns1:userName> <ns1:userPassword>"
            + Config.getConfig().getLuxidPassword()
            + "</ns1:userPassword> </ns1:authenticate> </SOAP-ENV:Body> </SOAP-ENV:Envelope>";
    URL authURL = new URL(Config.getConfig().getLuxidServerURL());

    HttpURLConnection authconn = (HttpURLConnection) authURL.openConnection();
    authconn.setRequestMethod("POST");
    authconn.setDoOutput(true);

    authconn.getOutputStream().write(auth.getBytes());

    if (authconn.getResponseCode() == HttpURLConnection.HTTP_OK) {
        InputStream stream = authconn.getInputStream();

        InputStreamReader read = new InputStreamReader(stream);
        BufferedReader rd = new BufferedReader(read);

        String line = "";

        if ((line = rd.readLine()) != null) {
            token = line.substring(line.indexOf("<token>") + "<token>".length(), line.indexOf("</token>"));
        }// w w  w  . ja  va 2s . com
        rd.close();
    }
    return token;
}

From source file:io.jari.geenstijl.API.API.java

public static String postUrl(String url, List<NameValuePair> params, String cheader, boolean refererandorigin)
        throws IOException {
    HttpURLConnection http = (HttpURLConnection) new URL(url).openConnection();
    http.setRequestMethod("POST");
    http.setDoInput(true);/*from   w  ww  .  ja  v a 2  s .co m*/
    http.setDoOutput(true);
    if (cheader != null)
        http.setRequestProperty("Cookie", cheader);
    if (refererandorigin) {
        http.setRequestProperty("Referer",
                "http://www.geenstijl.nl/mt/archieven/2014/01/brein_chanteert_ondertitelaars.html");
        http.setRequestProperty("Origin", "http://www.geenstijl.nl");
    }
    OutputStream os = http.getOutputStream();
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
    writer.write(getQuery(params));
    writer.flush();
    writer.close();
    os.close();

    http.connect();

    InputStream in = http.getInputStream();
    String encoding = http.getContentEncoding();
    encoding = encoding == null ? "UTF-8" : encoding;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] buf = new byte[8192];
    int len = 0;
    while ((len = in.read(buf)) != -1) {
        baos.write(buf, 0, len);
    }
    return new String(baos.toByteArray(), encoding);
}

From source file:com.melniqw.instagramsdk.Network.java

private static String sendDummyRequest(String url, String body, Request request) throws IOException {
    HttpURLConnection connection = null;
    try {/* ww  w.  ja v  a 2s  .  c om*/
        connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setConnectTimeout(10000);
        connection.setReadTimeout(10000);
        connection.setUseCaches(false);
        connection.setDoInput(true);
        //            connection.setRequestProperty("Content-Type", "text/plain; charset=utf-8");
        if (request == Request.GET) {
            connection.setDoOutput(false);
            connection.setRequestMethod("GET");
        } else if (request == Request.POST) {
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
        }
        if (REQUEST_ENABLE_COMPRESSION)
            connection.setRequestProperty("Accept-Encoding", "gzip");
        if (request == Request.POST)
            connection.getOutputStream().write(body.getBytes("utf-8"));
        int code = connection.getResponseCode();
        System.out.println(TAG + " responseCode = " + code);
        //It may happen due to keep-alive problem http://stackoverflow.com/questions/1440957/httpurlconnection-getresponsecode-returns-1-on-second-invocation
        if (code == -1)
            throw new WrongResponseCodeException("Network error");
        // ?    200
        //on error can also read error stream from connection.
        InputStream inputStream = new BufferedInputStream(connection.getInputStream(), 8192);
        String encoding = connection.getHeaderField("Content-Encoding");
        if (encoding != null && encoding.equalsIgnoreCase("gzip"))
            inputStream = new GZIPInputStream(inputStream);
        String response = Utils.convertStreamToString(inputStream);
        System.out.println(TAG + " response = " + response);
        return response;
    } finally {
        if (connection != null)
            connection.disconnect();
    }
}

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

public static void sendMessageToTopic(String topic, String message) {
    try {// www. ja v  a  2  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", message);
        // Where to send GCM message.
        String topicName = "/topics/topic_thyN_" + topic.trim();
        if (topic != null) {
            jGcmData.put("to", topicName);
        } 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("Sending message: '" + message + "' to " + topicName);
        System.out.println("Check your device/emulator for notification or logcat for "
                + "confirmation of the receipt of the GCM message.");
    } catch (NullPointerException e) {
        e.printStackTrace();
    } 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();
    }
}

From source file:net.daporkchop.porkselfbot.util.HTTPUtils.java

/**
 * Performs a POST request to the specified URL and returns the result.
 * <p />/*from   www  . ja  va  2s. c  om*/
 * The POST data will be encoded in UTF-8 as the specified contentType. The response will be parsed as UTF-8.
 * If the server returns an error but still provides a body, the body will be returned as normal.
 * If the server returns an error without any body, a relevant {@link java.io.IOException} will be thrown.
 *
 * @param url URL to submit the POST request to
 * @param post POST data in the correct format to be submitted
 * @param contentType Content type of the POST data
 * @return Raw text response from the server
 * @throws IOException The request was not successful
 */
public static String performPostRequestWithAuth(final URL url, final String post, final String contentType,
        final String auth) throws IOException {
    Validate.notNull(url);
    Validate.notNull(post);
    Validate.notNull(contentType);
    final HttpURLConnection connection = createUrlConnection(url);
    final byte[] postAsBytes = post.getBytes(Charsets.UTF_8);

    connection.setRequestProperty("Authorization", auth);
    connection.setRequestProperty("Content-Type", contentType + "; charset=utf-8");
    connection.setRequestProperty("Content-Length", "" + postAsBytes.length);
    connection.setDoOutput(true);

    OutputStream outputStream = null;
    try {
        outputStream = connection.getOutputStream();
        IOUtils.write(postAsBytes, outputStream);
    } finally {
        IOUtils.closeQuietly(outputStream);
    }

    InputStream inputStream = null;
    try {
        inputStream = connection.getInputStream();
        final String result = IOUtils.toString(inputStream, Charsets.UTF_8);
        return result;
    } catch (final IOException e) {
        IOUtils.closeQuietly(inputStream);
        inputStream = connection.getErrorStream();

        if (inputStream != null) {
            final String result = IOUtils.toString(inputStream, Charsets.UTF_8);
            return result;
        } else {
            throw e;
        }
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
}

From source file:yodlee.ysl.api.io.HTTP.java

public static String doPostRegisterUser(String url, String registerParam, Map<String, String> cobTokens,
        boolean isEncodingNeeded) throws IOException {
    //String processedURL = url+"?registerParam="+registerParam;
    /* String registerUserJson="{"
    + "      \"user\" : {"/*from   w ww .  j ava  2 s.  c o  m*/
    + "            \"loginName\" : \"TestT749\","
    + "            \"password\" : \"TESTT@123\","
    + "            \"email\" : \"testet@yodlee.com\","
    + "            \"firstName\" : \"Rehhsty\","
    + "            \"lastName\" :\"ysl\""
    +"             } ,"
            
    + "      \"preference\" : {"
    + "      \"address\" : {"
    + "            \"street\" : \"abcd\","
    + "            \"state\" : \"CA\","
    + "            \"city\" : \"RWS\","
    + "            \"postalCode\" : \"98405\","
    + "            \"countryIsoCode\" : \"USA\""
    +"             } ,"
    + "            \"currency\" : \"USD\","
    + "            \"timeZone\" : \"PST\","
    + "            \"dateFormat\" : \"MM/dd/yyyy\""
    + "}"
    + "}";*/

    //encoding url
    registerParam = java.net.URLEncoder.encode(registerParam, "UTF-8");
    String processedURL = url + "?registerParam=" + registerParam;
    String mn = "doIO(POST : " + processedURL + ", " + registerParam + "sessionTokens : " + " )";
    System.out.println(fqcn + " :: " + mn);
    URL restURL = new URL(processedURL);
    HttpURLConnection conn = (HttpURLConnection) restURL.openConnection();
    conn.setRequestMethod("POST");
    conn.setRequestProperty("User-Agent", userAgent);
    conn.setRequestProperty("Content-Type", contentTypeURLENCODED);
    conn.setRequestProperty("Content-Type", "text/plain;charset=UTF-8");
    conn.setRequestProperty("Authorization", cobTokens.toString());
    conn.setDoOutput(true);
    conn.setRequestProperty("Accept-Charset", "UTF-8");
    int responseCode = conn.getResponseCode();
    if (responseCode == 200) {
        System.out.println(fqcn + " :: " + mn + " : " + "Sending 'HTTP POST' request");
        System.out.println(fqcn + " :: " + mn + " : " + "Response Code : " + responseCode);
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String inputLine;
        StringBuilder jsonResponse = new StringBuilder();
        while ((inputLine = in.readLine()) != null) {
            jsonResponse.append(inputLine);
        }
        in.close();
        System.out.println(fqcn + " :: " + mn + " : " + jsonResponse.toString());
        return new String(jsonResponse);
    } else {
        System.out.println("Invalid input");
        return new String();

    }
}

From source file:com.chiorichan.util.WebUtils.java

/**
 * Establishes an HttpURLConnection from a URL, with the correct configuration to receive content from the given URL.
 * //  ww  w  .j a  va 2 s.  c  o  m
 * @param url
 *            The URL to set up and receive content from
 * @return A valid HttpURLConnection
 * 
 * @throws IOException
 *             The openConnection() method throws an IOException and the calling method is responsible for handling it.
 */
public static HttpURLConnection openHttpConnection(URL url) throws IOException {
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoInput(true);
    conn.setDoOutput(false);
    System.setProperty("http.agent", getUserAgent());
    conn.setRequestProperty("User-Agent", getUserAgent());
    HttpURLConnection.setFollowRedirects(true);
    conn.setUseCaches(false);
    conn.setInstanceFollowRedirects(true);
    return conn;
}

From source file:com.wisdombud.right.client.common.HttpKit.java

private static HttpURLConnection getHttpConnection(String url, String method, Map<String, String> headers)
        throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
    final URL _url = new URL(url);
    final HttpURLConnection conn = (HttpURLConnection) _url.openConnection();
    if (conn instanceof HttpsURLConnection) {
        ((HttpsURLConnection) conn).setSSLSocketFactory(sslSocketFactory);
        ((HttpsURLConnection) conn).setHostnameVerifier(trustAnyHostnameVerifier);
    }/*from  w  w  w.  jav a 2s. c om*/

    conn.setRequestMethod(method);
    conn.setDoOutput(true);
    conn.setDoInput(true);

    conn.setConnectTimeout(19000);
    conn.setReadTimeout(19000);

    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    conn.setRequestProperty("User-Agent",
            "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");

    if (headers != null && !headers.isEmpty()) {
        for (final Entry<String, String> entry : headers.entrySet()) {
            conn.setRequestProperty(entry.getKey(), entry.getValue());
        }
    }

    return conn;
}

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

public static String sendMessageToDeviceGroup(String to, String message, String sender, Long profileID,
        Long taskID) {/*from  ww w.  jav  a2s  .com*/
    String resp = null;
    try {
        // 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", message);
        jData.put("sender", sender);
        jData.put("profileID", profileID);
        jData.put("taskID", taskID);
        // Where to send GCM message.
        if (to != null && message != null) {
            jGcmData.put("to", to.trim());
        } else {
            Logger.logError("Error", new NullPointerException());
            return null;
        }
        // What to send in GCM message.
        jGcmData.put("data", jData);

        // Create connection to send GCM Message request.
        URL url = new URL("https://gcm-http.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);

        System.out.println("The payload is: " + jGcmData.toString());
        // Send GCM message content.
        OutputStream outputStream = conn.getOutputStream();
        outputStream.write(jGcmData.toString().getBytes());

        // Read GCM response.
        InputStream inputStream = conn.getInputStream();
        resp = IOUtils.toString(inputStream);

        if (resp == null || resp.trim().equals("")) {
            System.out.println("Got a Null Response from the server. Unable to send GCM message.");
            return null;
        } else {
            System.out.println("the response from GCM server is: " + resp);
            System.out.println("Check your device/emulator for notification or logcat for "
                    + "confirmation of the receipt of the GCM message.");
        }
        JSONObject jResp = null;
        try {
            jResp = new JSONObject(resp);
        } catch (JSONException jsone) {
            jsone.printStackTrace();
        }
        int rSuccess = jResp.getInt("success");
        int rFailure = jResp.getInt("failure");
        if (rSuccess == 0 && rFailure > 0)
            System.out.println(
                    "Failed sending message to the recipient. Total no. of devices for the user. " + rFailure);
        else if (rSuccess > 0 && rFailure == 0)
            System.out.println("Success sending message to all receipients. Total no. of devices for the user "
                    + rSuccess);
        else
            System.out.println("Partial success. Success sending to " + rSuccess
                    + " devices. And failed sending to " + rFailure + " devices");
    } catch (IOException e) {
        Logger.logError("Unable to send GCM message.", e);
    }

    return resp;
}

From source file:org.apache.mycat.advisor.common.net.http.HttpService.java

/**
 * ? header?//ww w .j  av a  2s  .com
 *
 * @param requestUrl
 * @param requestMethod
 * @param WithTokenHeader
 * @param token
 * @return
 */
public static String doHttpRequest(String requestUrl, String requestMethod, Boolean WithTokenHeader,
        String token) {
    String result = null;
    InetAddress ipaddr;
    int responseCode = -1;
    try {
        ipaddr = InetAddress.getLocalHost();
        StringBuffer buffer = new StringBuffer();
        URL url = new URL(requestUrl);
        HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
        httpUrlConn.setDoOutput(true);
        httpUrlConn.setDoInput(true);
        httpUrlConn.setUseCaches(false);

        httpUrlConn.setUseCaches(false);
        httpUrlConn.setRequestProperty("Accept-Charset", DEFAULT_CHARSET);
        httpUrlConn.setRequestProperty("Content-Type", "application/json;charset=" + DEFAULT_CHARSET);
        if (WithTokenHeader) {
            if (token == null) {
                throw new IllegalStateException("Oauth2 token is not set!");
            }
            httpUrlConn.setRequestProperty("Authorization", "OAuth2 " + token);
            httpUrlConn.setRequestProperty("API-RemoteIP", ipaddr.getHostAddress());
        }
        // ?GET/POST
        httpUrlConn.setRequestMethod(requestMethod);

        if ("GET".equalsIgnoreCase(requestMethod))
            httpUrlConn.connect();

        //            // ????
        //            if (null != outputJson) {
        //                OutputStream outputStream = httpUrlConn.getOutputStream();
        //                //??
        //                outputStream.write(outputJson.getBytes(DEFAULT_CHARSET));
        //                outputStream.close();
        //            }

        // ???
        InputStream inputStream = httpUrlConn.getInputStream();
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream, DEFAULT_CHARSET);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

        String str = null;
        while ((str = bufferedReader.readLine()) != null) {
            buffer.append(str);
        }
        result = buffer.toString();
        bufferedReader.close();
        inputStreamReader.close();
        // ?
        inputStream.close();
        httpUrlConn.disconnect();
    } catch (ConnectException ce) {
        logger.error("server connection timed out.", ce);
    } catch (Exception e) {
        logger.error("http request error:", e);
    } finally {
        return result;
    }
}