Example usage for java.net URLConnection setDoOutput

List of usage examples for java.net URLConnection setDoOutput

Introduction

In this page you can find the example usage for java.net URLConnection 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: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 a2 s . com*/
    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   ww w.  jav  a  2 s.c o m*/
        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/*ww  w  . j  ava 2s .c  o m*/
 *
 * @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  .ja va2 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.imsglobal.simplelti.SimpleLTIUtil.java

public static Properties doLaunch(String lti2EndPoint, Properties newMap) {
    M_log.warning("Warning: SimpleLTIUtil using deprecated non-POST launch to -" + lti2EndPoint);
    Properties retProp = new Properties();
    retProp.setProperty("status", "fail");

    String postData = "";
    // Yikes - iterating through properties is nasty
    for (Object okey : newMap.keySet()) {
        if (!(okey instanceof String))
            continue;
        String key = (String) okey;
        if (key == null)
            continue;
        String value = newMap.getProperty(key);
        if (value == null)
            continue;
        if (value.equals(""))
            continue;
        value = encodeFormText(value);//from  ww w.j  a v a  2s . c om
        if (postData.length() > 0)
            postData = postData + "&";
        postData = postData + encodeFormText(key) + "=" + value;
    }
    if (postData != null)
        retProp.setProperty("_post_data", postData);
    dPrint("LTI2 POST=" + postData);

    String postResponse = null;

    URLConnection urlc = null;
    try {
        // Thanks: http://xml.nig.ac.jp/tutorial/rest/index.html
        URL url = new URL(lti2EndPoint);

        InputStream inp = null;
        // make connection, use post mode, and send query
        urlc = url.openConnection();
        urlc.setDoOutput(true);
        urlc.setAllowUserInteraction(false);
        PrintStream ps = new PrintStream(urlc.getOutputStream());
        ps.print(postData);
        ps.close();
        dPrint("Post Complete");
        inp = urlc.getInputStream();

        // Retrieve result
        BufferedReader br = new BufferedReader(new InputStreamReader(inp));
        String str;
        StringBuffer sb = new StringBuffer();
        while ((str = br.readLine()) != null) {
            sb.append(str);
            sb.append("\n");
        }
        br.close();
        postResponse = sb.toString();

        if (postResponse == null) {
            setErrorMessage(retProp, "Launch REST Web Service returned nothing");
            return retProp;
        }
    } catch (Exception e) {
        // Retrieve error stream if it exists
        if (urlc != null && urlc instanceof HttpURLConnection) {
            try {
                HttpURLConnection urlh = (HttpURLConnection) urlc;
                BufferedReader br = new BufferedReader(new InputStreamReader(urlh.getErrorStream()));
                String str;
                StringBuffer sb = new StringBuffer();
                while ((str = br.readLine()) != null) {
                    sb.append(str);
                    sb.append("\n");
                }
                br.close();
                postResponse = sb.toString();
                dPrint("LTI ERROR response=" + postResponse);
            } catch (Exception f) {
                dPrint("LTI Exception in REST call=" + e);
                // e.printStackTrace();
                setErrorMessage(retProp, "Failed REST service call. Exception=" + e);
                postResponse = null;
                return retProp;
            }
        } else {
            dPrint("LTI General Failure" + e.getMessage());
            // e.printStackTrace();
        }
    }

    if (postResponse != null)
        retProp.setProperty("_post_response", postResponse);
    dPrint("LTI2 Response=" + postResponse);
    // Check to see if we received anything - and then parse it
    Map<String, String> respMap = null;
    if (postResponse == null) {
        setErrorMessage(retProp, "Web Service Returned Nothing");
        return retProp;
    } else {
        if (postResponse.indexOf("<?xml") != 0) {
            int pos = postResponse.indexOf("<launchResponse");
            if (pos > 0) {
                M_log.warning("Warning: Dropping first " + pos
                        + " non-XML characters of response to find <launchResponse");
                postResponse = postResponse.substring(pos);
            }
        }
        respMap = XMLMap.getMap(postResponse);
    }
    if (respMap == null) {
        String errorOut = postResponse;
        if (errorOut.length() > 500) {
            errorOut = postResponse.substring(0, 500);
        }
        M_log.warning("Error Parsing Web Service XML:\n" + errorOut + "\n");
        setErrorMessage(retProp, "Error Parsing Web Service XML");
        return retProp;
    }

    // We will tolerate this one backwards compatibility
    String launchUrl = respMap.get("/launchUrl");
    String launchWidget = null;

    if (launchUrl == null) {
        launchUrl = respMap.get("/launchResponse/launchUrl");
    }

    if (launchUrl == null) {
        launchWidget = respMap.get("/launchResponse/widget");

        /* Remove until we have jTidy 0.8 or later in the repository
        if ( launchWidget != null && launchWidget.length() > 0 ) {
                 M_log.warning("Pre Tidy:\n"+launchWidget);
                 Tidy tidy = new Tidy();
                 tidy.setIndentContent(true);
                 tidy.setSmartIndent(true);
                 tidy.setPrintBodyOnly(true);
                 tidy.setTidyMark(false);
                 // tidy.setQuiet(true);
                 // tidy.setShowWarnings(false);
                 InputStream is = new ByteArrayInputStream(launchWidget.getBytes());
                 OutputStream os = new ByteArrayOutputStream();
                 tidy.parse(is,os);
                 String tidyOutput = os.toString();
                 M_log.warning("Post Tidy:\n"+tidyOutput);
                 if ( tidyOutput != null && tidyOutput.length() > 0 ) launchWidget = os.toString();
              }
        */
    }

    dPrint("launchUrl = " + launchUrl);
    dPrint("launchWidget = " + launchWidget);

    if (launchUrl == null && launchWidget == null) {
        String eMsg = respMap.get("/launchResponse/code") + ":" + respMap.get("/launchResponse/description");
        setErrorMessage(retProp, "Error on Launch:" + eMsg);
        return retProp;
    }

    if (launchUrl != null)
        retProp.setProperty("launchurl", launchUrl);
    if (launchWidget != null)
        retProp.setProperty("launchwidget", launchWidget);
    String postResp = respMap.get("/launchResponse/type");
    if (postResp != null)
        retProp.setProperty("type", postResp);
    retProp.setProperty("status", "success");

    return retProp;
}

From source file:org.nuxeo.ecm.automation.core.operations.blob.PostBlob.java

@OperationMethod(collector = BlobCollector.class)
public Blob run(Blob blob) throws IOException {
    URL target = new URL(url);
    URLConnection conn = target.openConnection();
    conn.setDoOutput(true);
    try (InputStream in = blob.getStream(); OutputStream out = conn.getOutputStream()) {
        IOUtils.copy(in, out);//from w  w  w  .java 2 s.com
        out.flush();
    }
    return blob;
}

From source file:net.noday.cat.web.admin.DwzManager.java

@RequestMapping(method = RequestMethod.POST)
public Model gen(@RequestParam("url") String url, @RequestParam("alias") String alias, Model m) {
    try {/* w  w w  . j a v a  2 s  .  co  m*/
        String urlstr = "http://dwz.cn/create.php";
        URL requrl = new URL(urlstr);
        URLConnection conn = requrl.openConnection();
        conn.setDoOutput(true);
        OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
        String param = String.format(Locale.CHINA, "url=%s&alias=%s", url, alias);
        out.write(param);
        out.flush();
        out.close();
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line = reader.readLine();
        //{"longurl":"http:\/\/www.hao123.com\/","status":0,"tinyurl":"http:\/\/dwz.cn\/1RIKG"}
        ObjectMapper mapper = new ObjectMapper();
        Dwz dwz = mapper.readValue(line, Dwz.class);
        if (dwz.getStatus() == 0) {
            responseData(m, dwz.getTinyurl());
        } else {
            responseMsg(m, false, dwz.getErr_msg());
        }
    } catch (MalformedURLException e) {
        log.error(e.getMessage(), e);
        responseMsg(m, false, e.getMessage());
    } catch (IOException e) {
        log.error(e.getMessage(), e);
        responseMsg(m, false, e.getMessage());
    }
    return m;
}

From source file:org.apache.servicemix.samples.cxf_osgi.Client.java

public void sendRequest() throws Exception {
    URLConnection connection = new URL("http://localhost:8181/cxf/HelloWorld").openConnection();
    connection.setDoInput(true);/*from   w  w  w  .jav a  2s . com*/
    connection.setDoOutput(true);
    OutputStream os = connection.getOutputStream();
    // Post the request file.
    InputStream fis = getClass().getClassLoader()
            .getResourceAsStream("org/apache/servicemix/samples/cxf_osgi/request.xml");
    IOUtils.copy(fis, os);
    // Read the response.
    InputStream is = connection.getInputStream();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    IOUtils.copy(is, baos);
    System.out.println("the response is =====>");
    System.out.println(baos.toString());
}

From source file:org.apache.servicemix.examples.cxf.Client.java

public void sendRequest() throws Exception {
    URLConnection connection = new URL("http://localhost:8181/cxf/HelloWorldSecurity").openConnection();
    connection.setDoInput(true);//from  w ww.  j  a  v  a2 s  .c  o  m
    connection.setDoOutput(true);
    OutputStream os = connection.getOutputStream();
    // Post the request file.
    InputStream fis = getClass().getClassLoader()
            .getResourceAsStream("org/apache/servicemix/examples/cxf/request.xml");
    IOUtils.copy(fis, os);
    // Read the response.
    InputStream is = connection.getInputStream();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    IOUtils.copy(is, baos);
    System.out.println("the response is =====>");
    System.out.println(baos.toString());
}

From source file:org.apache.servicemix.examples.cxf.wsaddressing.Client.java

public void sendRequest() throws Exception {
    URLConnection connection = new URL("http://localhost:8181/cxf/SoapContext/SoapPort").openConnection();
    connection.setDoInput(true);/*from w  w  w  .j a  v a  2  s . com*/
    connection.setDoOutput(true);
    OutputStream os = connection.getOutputStream();
    // Post the request file.
    InputStream fis = getClass().getClassLoader()
            .getResourceAsStream("org/apache/servicemix/examples/cxf/wsaddressing/request.xml");
    IOUtils.copy(fis, os);
    // Read the response.
    InputStream is = connection.getInputStream();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    IOUtils.copy(is, baos);
    System.out.println("the response is =====>");
    System.out.println(baos.toString());
}