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:Main.java

public static String getToken(String email, String password) throws IOException {
    // Create the post data
    // Requires a field with the email and the password
    StringBuilder builder = new StringBuilder();
    builder.append("Email=").append(email);
    builder.append("&Passwd=").append(password);
    builder.append("&accountType=GOOGLE");
    builder.append("&source=markson.visuals.sitapp");
    builder.append("&service=ac2dm");

    // Setup the Http Post
    byte[] data = builder.toString().getBytes();
    URL url = new URL("https://www.google.com/accounts/ClientLogin");
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setUseCaches(false);/*w w w.  j a  v  a  2 s  . c  o m*/
    con.setDoOutput(true);
    con.setRequestMethod("POST");
    con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    con.setRequestProperty("Content-Length", Integer.toString(data.length));

    // Issue the HTTP POST request
    OutputStream output = con.getOutputStream();
    output.write(data);
    output.close();

    // Read the response
    BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String line = null;
    String auth_key = null;
    while ((line = reader.readLine()) != null) {
        if (line.startsWith("Auth=")) {
            auth_key = line.substring(5);
        }
    }

    // Finally get the authentication token
    // To something useful with it
    return auth_key;
}

From source file:FainClasses.HttpBasicAuth.java

public static void auth() {

    String sHTML = "Can not load page";
    URL url;//from  w  w w  .ja v  a2s  .  c  o  m
    InputStream is;
    BufferedReader buff = null;

    try {
        url = new URL("http://vrgaz.ru/lk/index.php?page=ls&lss=1600013620");
        url.getAuthority();

        String encoding = Base64.encodeBase64String("md_dimka@mail.ru:ufpyflt;ls".getBytes());

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.setRequestProperty("Cookie", "PHPSESSID=343266771f5de3a489ba82fe79809854");
        // connection.
        //connection.setRequestProperty("Authorization", "Basic " + encoding);

        /*connection.setRequestProperty("avl","md_dimka@mail.ru");
        connection.setRequestProperty("avp","ufpyflt;ls");
         */
        //connection.setRequestProperty("page", "ls");
        //connection.setRequestProperty("lss", "1600013620");

        //URL url = new URL("http://vrgaz.ru/lk/");  
        // url = new URL(sUrl);
        //is = url.openStream();
        is = connection.getInputStream();
        buff = new BufferedReader(new InputStreamReader(is, "windows-1251"));
        StringBuilder page = new StringBuilder();
        String tmp;
        while ((tmp = buff.readLine()) != null) {
            page.append(tmp).append("\n");
        }

        sHTML = page.toString();
        System.out.println(sHTML);
        //            InputStream content = (InputStream) connection.getInputStream();
        //            BufferedReader in
        //                    = new BufferedReader(new InputStreamReader(content));
        //            String line;
        //            while ((line = in.readLine()) != null) {
        //                System.out.println(line);
        //            }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:Main.java

private static HttpURLConnection defineHttpsURLConnection(HttpURLConnection connection, JSONObject jsonObject) {
    try {/*from  w  w  w . j a  va2s . co m*/
        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);

        /* Add headers to the request */
        connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");

        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
        wr.write(jsonObject.toString().getBytes(Charset.forName("UTF-8")));
        wr.flush();
        wr.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return connection;
}

From source file:Main.java

public static String customrequest(String url, HashMap<String, String> params, String method) {
    try {/*  w  w  w .  j ava2 s  . c o  m*/

        URL postUrl = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) postUrl.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setConnectTimeout(5 * 1000);

        conn.setRequestMethod(method);
        conn.setUseCaches(false);
        conn.setInstanceFollowRedirects(true);
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows XP; DigExt)");

        conn.connect();
        OutputStream out = conn.getOutputStream();
        StringBuilder sb = new StringBuilder();
        if (null != params) {
            int i = params.size();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                if (i == 1) {
                    sb.append(entry.getKey() + "=" + entry.getValue());
                } else {
                    sb.append(entry.getKey() + "=" + entry.getValue() + "&");
                }

                i--;
            }
        }
        String content = sb.toString();
        out.write(content.getBytes("UTF-8"));
        out.flush();
        out.close();
        InputStream inStream = conn.getInputStream();
        String result = inputStream2String(inStream);
        conn.disconnect();
        return result;
    } catch (Exception e) {
        // TODO: handle exception
    }
    return null;
}

From source file:io.helixservice.feature.configuration.cloudconfig.CloudConfigDecrypt.java

/**
 * Decrypt an encrypted string//from w  w  w  . j a  va 2  s .  c  om
 * <p>
 * This method blocks on a HTTP request.
 *
 * @param name property or filename for reference/logging
 * @param encryptedValue Encrypted string
 * @param cloudConfigUri URI of the Cloud Config server
 * @param httpBasicHeader HTTP Basic header containing username and password for Cloud Config server
 * @return
 */
public static String decrypt(String name, String encryptedValue, String cloudConfigUri,
        String httpBasicHeader) {
    String result = encryptedValue;

    // Remove prefix if needed
    if (encryptedValue.startsWith(CIPHER_PREFIX)) {
        encryptedValue = encryptedValue.substring(CIPHER_PREFIX.length());
    }

    String decryptUrl = cloudConfigUri + "/decrypt";

    try {
        HttpURLConnection connection = (HttpURLConnection) new URL(decryptUrl).openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);

        connection.setRequestMethod("POST");
        connection.addRequestProperty(AUTHORIZATION_HEADER, httpBasicHeader);
        connection.setRequestProperty("Content-Type", "text/plain");
        connection.setRequestProperty("Content-Length", Integer.toString(encryptedValue.getBytes().length));
        connection.setRequestProperty("Accept", "*/*");

        // Write body
        OutputStream outputStream = connection.getOutputStream();
        outputStream.write(encryptedValue.getBytes());
        outputStream.close();

        if (connection.getResponseCode() == 200) {
            InputStream inputStream = connection.getInputStream();
            result = IOUtils.toString(inputStream);
            inputStream.close();
        } else {
            LOG.error("Unable to Decrypt name=" + name + " due to httpStatusCode="
                    + connection.getResponseCode() + " for decryptUrl=" + decryptUrl);
        }
    } catch (IOException e) {
        LOG.error("Unable to connect to Cloud Config server at decryptUrl=" + decryptUrl, e);
    }

    return result;
}

From source file:Main.java

public static String post(String url, Map<String, String> params) {
    try {/*from w w  w . j av a2 s.co m*/
        URL u = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) u.openConnection();
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setUseCaches(false);
        PrintWriter pw = new PrintWriter(connection.getOutputStream());
        StringBuilder sbParams = new StringBuilder();
        if (params != null) {
            for (String key : params.keySet()) {
                sbParams.append(key + "=" + params.get(key) + "&");
            }
        }
        if (sbParams.length() > 0) {
            String strParams = sbParams.substring(0, sbParams.length() - 1);
            Log.e("cat", "strParams:" + strParams);
            pw.write(strParams);
            pw.flush();
            pw.close();
        }
        BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuffer response = new StringBuffer();
        String readLine = "";
        while ((readLine = br.readLine()) != null) {
            response.append(readLine);
        }
        br.close();
        return response.toString();
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

From source file:Main.java

public static String stringFromHttpPost(String urlStr, String body) {
    HttpURLConnection conn;
    try {/*from w  ww . j  a v a 2s .c  om*/
        URL e = new URL(urlStr);
        conn = (HttpURLConnection) e.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setInstanceFollowRedirects(true);
        conn.setRequestMethod("POST");
        OutputStream os1 = conn.getOutputStream();
        DataOutputStream out1 = new DataOutputStream(os1);
        out1.write(body.getBytes("UTF-8"));
        out1.flush();
        conn.connect();
        String line;
        BufferedReader reader;
        StringBuffer sb = new StringBuffer();
        if ("gzip".equals(conn.getHeaderField("Content-Encoding"))) {
            reader = new BufferedReader(
                    new InputStreamReader(new GZIPInputStream(conn.getInputStream()), "UTF-8"));
        } else {
            reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
        }
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        return sb.toString();
    } catch (Exception e) {
        e.printStackTrace();
        logError(e.getMessage());
    }
    return null;
}

From source file:org.cytoscape.app.internal.net.server.ScreenOriginsBeforeResponseTest.java

private static HttpURLConnection connectToURL(String urlString, String method, String origin) throws Exception {
    final URL url = new URL(urlString);
    final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod(method);
    connection.setDoOutput(true);
    if (origin != null)
        connection.setRequestProperty("Origin", origin);
    connection.setConnectTimeout(1000);//  ww  w. j  a v  a2s  .  c o m
    connection.connect();
    return connection;
}

From source file:org.cytoscape.app.internal.net.server.AddAccessControlAllowOriginHeaderAfterResponseTest.java

private static HttpURLConnection connectToURL(String urlString, String method) throws Exception {
    final URL url = new URL(urlString);
    final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod(method);
    connection.setDoOutput(true);
    connection.setConnectTimeout(1000);/*from  w w  w. j ava2  s.  c  o  m*/
    connection.connect();
    return connection;
}

From source file:com.appdynamics.common.RESTClient.java

public static void sendPost(String urlString, String input, String apiKey) {
    try {//from ww  w .ja v a2 s  .  c  om
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");

        conn.setRequestProperty("Authorization",
                "Basic " + new String(Base64.encodeBase64((apiKey).getBytes())));

        OutputStream os = conn.getOutputStream();
        os.write(input.getBytes());
        os.flush();

        if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
            throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
        }

        BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

        String output;
        logger.info("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            logger.info(output);
        }

        conn.disconnect();

    } catch (MalformedURLException e) {

        e.printStackTrace();

    } catch (IOException e) {

        e.printStackTrace();

    }

}