Example usage for java.net URLConnection setDoInput

List of usage examples for java.net URLConnection setDoInput

Introduction

In this page you can find the example usage for java.net URLConnection setDoInput.

Prototype

public void setDoInput(boolean doinput) 

Source Link

Document

Sets the value of the doInput field for this URLConnection to the specified value.

Usage

From source file:org.motechproject.mmnaija.web.util.HTTPCommunicator.java

public static String doPost(String serviceUrl, String queryString) {
    URLConnection connection = null;
    try {//from   w w  w  . jav  a 2  s.co  m

        URL url = new URL(serviceUrl);
        URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(),
                url.getQuery(), url.getRef());
        url = uri.toURL();
        // Open the connection
        connection = url.openConnection();
        connection.setDoInput(true);
        connection.setUseCaches(false); // Disable caching the document
        connection.setDoOutput(true); // Triggers POST.
        connection.setRequestProperty("Content-Type", "text/html");

        OutputStreamWriter writer = null;

        log.info("About to write");
        try {
            if (null != connection.getOutputStream()) {
                writer = new OutputStreamWriter(connection.getOutputStream());
                writer.write(queryString); // Write POST query

            } else {
                log.warn("connection Null");
            }
            // string.
        } catch (ConnectException ex) {
            log.warn("Exception : " + ex);
            // ex.printStackTrace();
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (Exception lg) {
                    log.warn("Exception lg: " + lg.toString());
                    //lg.printStackTrace();
                }
            }
        }

        InputStream in = connection.getInputStream();

        //            StringWriter writer = new StringWriter();
        IOUtils.copy(in, writer, "utf-8");
        String theString = writer.toString();
        return theString;
    } catch (Exception e) {
        //e.printStackTrace();
        log.warn("Error URL " + e.toString());
        return "";
    }
}

From source file:BihuHttpUtil.java

public static String doHttpPost(String xmlInfo, String URL) {
    System.out.println("??:" + xmlInfo);
    byte[] xmlData = xmlInfo.getBytes();
    InputStream instr = null;//from w w w .  j a v  a 2 s  .c  o m
    java.io.ByteArrayOutputStream out = null;
    try {
        URL url = new URL(URL);
        URLConnection urlCon = url.openConnection();
        urlCon.setDoOutput(true);
        urlCon.setDoInput(true);
        urlCon.setUseCaches(false);
        urlCon.setRequestProperty("Content-Type", "text/xml");
        urlCon.setRequestProperty("Content-length", String.valueOf(xmlData.length));
        System.out.println(String.valueOf(xmlData.length));
        DataOutputStream printout = new DataOutputStream(urlCon.getOutputStream());
        printout.write(xmlData);
        printout.flush();
        printout.close();
        instr = urlCon.getInputStream();
        byte[] bis = IOUtils.toByteArray(instr);
        String ResponseString = new String(bis, "UTF-8");
        if ((ResponseString == null) || ("".equals(ResponseString.trim()))) {
            System.out.println("");
        }
        System.out.println("?:" + ResponseString);
        return ResponseString;

    } catch (Exception e) {
        e.printStackTrace();
        return "0";
    } finally {
        try {
            out.close();
            instr.close();
        } catch (Exception ex) {
            return "0";
        }
    }
}

From source file:net.pms.util.OpenSubtitle.java

public static String postPage(URLConnection connection, String query) throws IOException {
    connection.setDoOutput(true);/*  www.  j ava 2s. c  om*/
    connection.setDoInput(true);
    connection.setUseCaches(false);
    connection.setDefaultUseCaches(false);
    connection.setRequestProperty("Content-Type", "text/xml");
    connection.setRequestProperty("Content-Length", "" + query.length());
    ((HttpURLConnection) connection).setRequestMethod("POST");
    //LOGGER.debug("opensub query "+query);
    // open up the output stream of the connection
    if (!StringUtils.isEmpty(query)) {
        try (DataOutputStream output = new DataOutputStream(connection.getOutputStream())) {
            output.writeBytes(query);
            output.flush();
        }
    }

    StringBuilder page;
    try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
        page = new StringBuilder();
        String str;
        while ((str = in.readLine()) != null) {
            page.append(str.trim());
            page.append("\n");
        }
    }
    //LOGGER.debug("opensubs result page "+page.toString());
    return page.toString();
}

From source file:dictinsight.utils.io.HttpUtils.java

public static String getDataFromOtherServer(String url, String param) {
    PrintWriter out = null;//from w  w  w.  ja  v a2  s.  c  o  m
    BufferedReader in = null;
    String result = "";
    try {
        URL realUrl = new URL(url);
        URLConnection conn = realUrl.openConnection();
        conn.setConnectTimeout(1000 * 10);
        conn.setRequestProperty("accept", "*/*");
        conn.setRequestProperty("connection", "Keep-Alive");
        conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        out = new PrintWriter(conn.getOutputStream());
        out.print(param);
        out.flush();
        in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;
        while ((line = in.readLine()) != null) {
            result += line;
        }
    } catch (Exception e) {
        System.out.println("get date from " + url + param + " error!");
        e.printStackTrace();
    }
    // finally?????
    finally {
        try {
            if (out != null) {
                out.close();
            }
            if (in != null) {
                in.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    return result;
}

From source file:tkwatch.Utilities.java

/**
 * Issues a TradeKing API request. Adapted from the <i>TradeKing API
 * Reference Guide</i>, 03.25.2011, p. 51.
 * /*from   w  w  w. jav  a 2s  . c o m*/
 * @param resourceUrl
 *            The URL to which API requests must be made.
 * @param body
 *            The body of the API request.
 * @param appKey
 *            The user's application key.
 * @param userKey
 *            The user's key.
 * @param userSecret
 *            The user's secret key.
 * @return Returns the result of the API request.
 */
public static final String tradeKingRequest(final String resourceUrl, final String body, final String appKey,
        final String userKey, final String userSecret) {
    String response = new String();
    try {
        String timestamp = String.valueOf(Calendar.getInstance().getTimeInMillis());
        String request_data = body + timestamp;
        String signature = generateSignature(request_data, userSecret);
        URL url = new URL(resourceUrl);
        URLConnection conn = url.openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setRequestProperty("Content-Type", "application/xml");
        conn.setRequestProperty("Accept", "application/xml");
        conn.setRequestProperty("TKI_TIMESTAMP", timestamp);
        conn.setRequestProperty("TKI_SIGNATURE", signature);
        conn.setRequestProperty("TKI_USERKEY", userKey);
        conn.setRequestProperty("TKI_APPKEY", appKey);
        DataOutputStream out = new DataOutputStream(conn.getOutputStream());
        out.writeBytes(body);
        out.flush();
        out.close();
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String temp;
        while ((temp = in.readLine()) != null) {
            response += temp + "\n";
        }
        in.close();
        return response;
    } catch (java.security.SignatureException e) {
        errorMessage(e.getMessage());
        return "";
    } catch (java.io.IOException e) {
        errorMessage(e.getMessage());
        return "";
    }
}

From source file:edu.stanford.muse.slant.CustomSearchHelper.java

/** returns an oauth token for the user's CSE. returns null if login failed. */
public static String authenticate(String login, String password) {
    //System.out.println("About to post\nURL: "+target+ "content: " + content);
    String authToken = null;/*from w  w  w  .  j a  v  a 2 s . c o m*/
    String response = "";
    try {
        URL url = new URL("https://www.google.com/accounts/ClientLogin");
        URLConnection conn = url.openConnection();
        // Set connection parameters.
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);

        // Make server believe we are form data...

        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        DataOutputStream out = new DataOutputStream(conn.getOutputStream());
        // TODO: escape password, we'll fail if password has &
        // login = "musetestlogin1";
        // password = "whowonthelottery";
        String content = "accountType=HOSTED_OR_GOOGLE&Email=" + login + "&Passwd=" + password
                + "&service=cprose&source=muse.chrome.extension";
        out.writeBytes(content);
        out.flush();
        out.close();

        // Read response from the input stream.
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String temp;
        while ((temp = in.readLine()) != null) {
            response += temp + "\n";
        }
        temp = null;
        in.close();
        log.info("Obtaining auth token: Server response:\n'" + response + "'");

        String delimiter = "Auth=";
        /* given string will be split by the argument delimiter provided. */
        String[] token = response.split(delimiter);
        authToken = token[1];
        authToken = authToken.trim();
        authToken = authToken.replaceAll("(\\r|\\n)", "");
        log.info("auth token: " + authToken);
        return authToken;
    } catch (Exception e) {
        log.warn("Unable to authorize: " + e.getMessage());
        return null;
    }
}

From source file:org.spoutcraft.launcher.util.Utils.java

public static String executePost(String targetURL, String urlParameters, JProgressBar progress)
        throws PermissionDeniedException {
    URLConnection connection = null;
    try {/*from   w  w  w  . ja  va 2 s . c om*/
        URL url = new URL(targetURL);
        connection = url.openConnection();
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        connection.setRequestProperty("Content-Length", Integer.toString(urlParameters.getBytes().length));
        connection.setRequestProperty("Content-Language", "en-US");

        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);

        connection.setConnectTimeout(10000);

        connection.connect();

        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();

        InputStream is = connection.getInputStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));

        StringBuilder response = new StringBuilder();
        String line;
        while ((line = rd.readLine()) != null) {
            response.append(line);
            response.append('\r');
        }
        rd.close();

        return response.toString();
    } catch (SocketException e) {
        if (e.getMessage().equalsIgnoreCase("Permission denied: connect")) {
            throw new PermissionDeniedException("Permission to login was denied");
        }
    } catch (Exception e) {
        String message = "Login failed...";
        progress.setString(message);
    }
    return null;
}

From source file:BihuHttpUtil.java

/**
 * ? URL ??POST/*from  ww w .  j a  v a2 s.  com*/
 *
 * @param url
 *            ?? URL
 * @param param
 *            ?? name1=value1&name2=value2 ?
 * @return ??
 */
public static String sendPost(String url, String param) {
    PrintWriter out = null;
    BufferedReader in = null;
    String result = "";
    try {
        URL realUrl = new URL(url);
        // URL
        URLConnection conn = realUrl.openConnection();
        // 
        conn.setRequestProperty("accept", "*/*");
        conn.setRequestProperty("connection", "Keep-Alive");
        conn.setRequestProperty("content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
        // ??POST
        conn.setDoOutput(true);
        conn.setDoInput(true);
        // ?URLConnection?
        out = new PrintWriter(conn.getOutputStream());
        // ???
        out.print(param);
        // flush?
        out.flush();
        // BufferedReader???URL?
        in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;
        while ((line = in.readLine()) != null) {
            result += line;
        }
    } catch (Exception e) {
        System.out.println("?? POST ?" + e);
        e.printStackTrace();
    }
    // finally?????
    finally {
        try {
            if (out != null) {
                out.close();
            }
            if (in != null) {
                in.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    return result;
}

From source file:mashapeautoloader.MashapeAutoloader.java

/**
 * @param libraryName/* w w w . java2  s  . c  o  m*/
 *
 * Returns false if something wrong, otherwise true (API interface
 * already exists or just well downloaded)
 */
private static boolean downloadLib(String libraryName) {
    URL url;
    URLConnection urlConn;

    // check (or make) for apiStore directory
    File apiStoreDir = new File(apiStore);
    if (!apiStoreDir.isDirectory())
        apiStoreDir.mkdir();

    String javaFilePath = apiStore + libraryName + ".java";
    File javaFile = new File(javaFilePath);

    // check if the API interface exists
    if (javaFile.exists())
        return true;
    try {
        // download the API interface's archive
        url = new URL(MASHAPE_DOWNLOAD_ROOT + libraryName);
        urlConn = url.openConnection();

        HttpURLConnection httpConn = (HttpURLConnection) urlConn;
        httpConn.setInstanceFollowRedirects(false);

        urlConn.setDoInput(true);
        urlConn.setDoOutput(false);
        urlConn.setUseCaches(false);

        // extract the archive stream
        ZipInputStream zip = new ZipInputStream(urlConn.getInputStream());
        String expectedEntryName = libraryName + ".java";
        while (true) {
            ZipEntry nextEntry = zip.getNextEntry();
            if (nextEntry == null)
                return false;

            String name = nextEntry.getName();
            if (name.equals(expectedEntryName)) {
                // save .java locally
                FileOutputStream javaFileStream = new FileOutputStream(javaFilePath);
                byte[] buf = new byte[1024];
                int n;
                while ((n = zip.read(buf, 0, 1024)) > -1)
                    javaFileStream.write(buf, 0, n);

                // compile it into .class file
                JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
                int result = compiler.run(null, null, null, javaFilePath);
                System.out.println(result);
                return result == 0;
            }
        }
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:org.java.plugin.standard.ShadingPathResolver.java

static Date getLastModified(final URL url) throws IOException {
    long result = 0;
    if ("jar".equalsIgnoreCase(url.getProtocol())) { //$NON-NLS-1$
        String urlStr = url.toExternalForm();
        int p = urlStr.indexOf("!/"); //$NON-NLS-1$
        if (p != -1) {
            //sourceFile = IoUtil.url2file(new URL(urlStr.substring(4, p)));
            return getLastModified(new URL(urlStr.substring(4, p)));
        }/*w w w  .j  ava2s . com*/
    }
    File sourceFile = IoUtil.url2file(url);
    if (sourceFile != null) {
        result = sourceFile.lastModified();
    } else {
        URLConnection cnn = url.openConnection();
        try {
            cnn.setUseCaches(false);
            cnn.setDoInput(false); // this should force using HTTP HEAD method
            result = cnn.getLastModified();
        } finally {
            try {
                cnn.getInputStream().close();
            } catch (IOException ioe) {
                // ignore
            }
        }
    }
    if (result == 0) {
        throw new IOException("can't retrieve modification date for resource " //$NON-NLS-1$
                + url);
    }
    // for some reason modification milliseconds for some files are unstable
    Calendar cldr = Calendar.getInstance(Locale.ENGLISH);
    cldr.setTime(new Date(result));
    cldr.set(Calendar.MILLISECOND, 0);
    return cldr.getTime();
}