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:org.omegat.languagetools.LanguageToolNetworkBridge.java

@SuppressWarnings("unchecked")
protected List<Object> getSupportedLanguages() throws Exception {
    // This is a really stupid way to get the /languages endpoint URL, but it'll do for now.
    String langsUrl = serverUrl.replace(CHECK_PATH, LANGS_PATH);

    URL url = new URL(langsUrl);
    URLConnection conn = url.openConnection();
    conn.setRequestProperty("User-Agent", OStrings.getNameAndVersion());
    conn.setDoOutput(true);

    checkHttpError(conn);/*from  w  w w.j a  v  a2s.  co  m*/

    String json = "";
    try (InputStream in = conn.getInputStream()) {
        json = IOUtils.toString(in, StandardCharsets.UTF_8);
    }

    return (List<Object>) JsonParser.parse(json);
}

From source file:org.infoglue.common.util.RemoteCacheUpdater.java

/**
 * This method post information to an URL and returns a string.It throws
 * an exception if anything goes wrong./*  ww w  . j a  va2  s  .  c o m*/
 * (Works like most 'doPost' methods)
 * 
 * @param urlAddress The address of the URL you would like to post to.
 * @param inHash The parameters you would like to post to the URL.
 * @return The result of the postToUrl method as a string.
 * @exception java.lang.Exception
 */

private String postToUrl(String urlAddress, Hashtable inHash) throws Exception {
    URL url = new URL(urlAddress);
    URLConnection urlConn = url.openConnection();
    urlConn.setConnectTimeout(3000);
    urlConn.setReadTimeout(3000);
    urlConn.setAllowUserInteraction(false);
    urlConn.setDoOutput(true);
    urlConn.setDoInput(true);
    urlConn.setUseCaches(false);
    urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    PrintWriter printout = new PrintWriter(urlConn.getOutputStream(), true);
    String argString = "";
    if (inHash != null) {
        argString = toEncodedString(inHash);
    }
    printout.print(argString);
    printout.flush();
    printout.close();
    InputStream inStream = null;
    inStream = urlConn.getInputStream();
    InputStreamReader inStreamReader = new InputStreamReader(inStream);
    BufferedReader buffer = new BufferedReader(inStreamReader);
    StringBuffer strbuf = new StringBuffer();
    String line;
    while ((line = buffer.readLine()) != null) {
        strbuf.append(line);
    }
    String readData = strbuf.toString();
    buffer.close();
    return readData;
}

From source file:Store.AfricasTalkingGateway.java

private String sendPOSTRequest(HashMap<String, String> dataMap_, String urlString_) throws Exception {
    try {/*from w  ww .  j a v a 2  s  .co m*/
        String data = new String();
        Iterator<Map.Entry<String, String>> it = dataMap_.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, String> pairs = (Map.Entry<String, String>) it.next();
            data += URLEncoder.encode(pairs.getKey().toString(), "UTF-8");
            data += "=" + URLEncoder.encode(pairs.getValue().toString(), "UTF-8");
            if (it.hasNext())
                data += "&";
        }
        URL url = new URL(urlString_);
        URLConnection conn = url.openConnection();
        conn.setRequestProperty("Accept", "application/json");
        conn.setRequestProperty("apikey", _apiKey);
        conn.setDoOutput(true);
        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
        writer.write(data);
        writer.flush();

        HttpURLConnection http_conn = (HttpURLConnection) conn;
        responseCode = http_conn.getResponseCode();

        BufferedReader reader;
        if (responseCode == HTTP_CODE_OK || responseCode == HTTP_CODE_CREATED)
            reader = new BufferedReader(new InputStreamReader(http_conn.getInputStream()));
        else
            reader = new BufferedReader(new InputStreamReader(http_conn.getErrorStream()));
        String response = reader.readLine();

        if (DEBUG)
            System.out.println(response);

        reader.close();
        return response;

    } catch (Exception e) {
        throw e;
    }
}

From source file:org.omegat.languagetools.LanguageToolNetworkBridge.java

@Override
@SuppressWarnings("unchecked")
protected List<LanguageToolResult> getCheckResultsImpl(String sourceText, String translationText)
        throws Exception {
    if (targetLang == null) {
        return Collections.emptyList();
    }/*from   w  w w  . ja v a  2  s.com*/

    URL url = new URL(serverUrl);
    URLConnection conn = url.openConnection();
    conn.setRequestProperty("User-Agent", OStrings.getNameAndVersion());
    conn.setDoOutput(true);
    try (OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream())) {
        String srcLang = sourceLang == null ? null : sourceLang.toString();
        writer.write(buildPostData(srcLang, targetLang.toString(), sourceText, translationText,
                disabledCategories, disabledRules, enabledRules));
        writer.flush();
    }

    checkHttpError(conn);

    String json = "";
    try (InputStream in = conn.getInputStream()) {
        json = IOUtils.toString(in, StandardCharsets.UTF_8);
    }

    Map<String, Object> response = (Map<String, Object>) JsonParser.parse(json);
    Map<String, String> software = (Map<String, String>) response.get("software");

    if (!software.get("apiVersion").equals(API_VERSION)) {
        Log.logWarningRB("LT_API_VERSION_MISMATCH");
    }

    List<Map<String, Object>> matches = (List<Map<String, Object>>) response.get("matches");

    return matches.stream().map(match -> {
        String message = addSuggestionTags((String) match.get("message"));
        int start = (int) match.get("offset");
        int end = start + (int) match.get("length");
        Map<String, Object> rule = (Map<String, Object>) match.get("rule");
        String ruleId = (String) rule.get("id");
        String ruleDescription = (String) rule.get("description");
        return new LanguageToolResult(message, start, end, ruleId, ruleDescription);
    }).collect(Collectors.toList());
}

From source file:shapeways.api.robocreator.RoboCreatorWeb.java

/**
 * Get the public facing hostname for this machine.  Uses AWS metadata service.
 *//* ww w  .j a v a 2s.c  o m*/
protected String getInstanceMetadata(String name, String defValue) {
    ByteArrayOutputStream baos = null;
    BufferedOutputStream bout = null;
    String ret_val = null;
    InputStream is = null;

    try {
        URL url = new URL("http://169.254.169.254/latest/meta-data/" + name);

        URLConnection urlConn = url.openConnection();
        urlConn.setConnectTimeout(5000);
        urlConn.setReadTimeout(15000);
        urlConn.setAllowUserInteraction(false);
        urlConn.setDoOutput(true);
        is = new BufferedInputStream(urlConn.getInputStream());

        baos = new ByteArrayOutputStream();
        bout = new BufferedOutputStream(baos, 1024);

        int buffSize = 8 * 1024;
        byte data[] = new byte[buffSize];
        int count;

        while ((count = is.read(data, 0, buffSize)) >= 0) {
            baos.write(data, 0, count);
        }

        ret_val = baos.toString();
    } catch (Exception e) {
        // ignore
        //e.printStackTrace();
    } finally {
        try {
            bout.close();
            is.close();
        } catch (Exception e) {
            // ignore
        }
    }

    if (ret_val == null) {
        ret_val = defValue;
    }

    return ret_val;
}

From source file:com.controller.CuotasController.java

@RequestMapping("cuotas.htm")
public ModelAndView getCuotas(HttpServletRequest request) {
    sesion = request.getSession();//from  w  w  w  . j av a  2  s  .c  om
    ModelAndView mav = new ModelAndView();
    String mensaje = null;
    Detalles detalle = (Detalles) sesion.getAttribute("cuenta");

    String country = detalle.getCiudad();
    String amount = "5";
    String myURL = "http://192.168.5.39/app_dev.php/public/get/rates";
    // System.out.println("Requested URL:" + myURL);
    StringBuilder sb = new StringBuilder();
    URLConnection urlConn = null;
    InputStreamReader in = null;
    try {
        URL url = new URL(myURL);
        urlConn = url.openConnection();
        if (urlConn != null) {
            urlConn.setReadTimeout(60 * 1000);
            urlConn.setDoOutput(true);
            String data = URLEncoder.encode("country", "UTF-8") + "=" + URLEncoder.encode(country, "UTF-8");
            data += "&" + URLEncoder.encode("amount", "UTF-8") + "=" + URLEncoder.encode(amount, "UTF-8");

            System.out.println("los Datos a enviar por POST son " + data);

            try ( //obtenemos el flujo de escritura
                    OutputStreamWriter wr = new OutputStreamWriter(urlConn.getOutputStream())) {
                //escribimos
                wr.write(data);
                wr.flush();
                //cerramos la conexin
            }
        }
        if (urlConn != null && urlConn.getInputStream() != null) {
            in = new InputStreamReader(urlConn.getInputStream(), Charset.defaultCharset());

            BufferedReader bufferedReader = new BufferedReader(in);
            if (bufferedReader != null) {
                int cp;
                while ((cp = bufferedReader.read()) != -1) {
                    sb.append((char) cp);
                }
                bufferedReader.close();
            }
        }
        in.close();
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("Exception while calling URL:" + myURL, e);
    }
    String resultado = sb.toString();

    if (sesion.getAttribute("usuario") == null) {

        mav.setViewName("login/login");

    } else {
        sesionUser = sesion.getAttribute("usuario").toString();
        //Detalles detalle = (Detalles) sesion.getAttribute("cuenta");
        mav.addObject("country", detalle.getCiudad());
        mav.addObject("resultado", resultado);

        if (sesion.getAttribute("tipoUsuario").toString().compareTo("Administrador") == 0) {
            mav.setViewName("viewsAdmin/cuotasAdmin");
            System.out.println("el usuario es administrador");
        } else {
            mav.setViewName("panel/cuotas");
        }
    }
    return mav;
}

From source file:com.controller.CuotasController.java

@RequestMapping("cuotasAdmin.htm")
public ModelAndView getCuotasAdmin(HttpServletRequest request) {
    sesion = request.getSession();//from   ww w .  java  2 s . c  o m
    ModelAndView mav = new ModelAndView();
    String mensaje = null;
    Detalles detalle = (Detalles) sesion.getAttribute("cuenta");

    String country = detalle.getCiudad();
    String amount = "5";
    String myURL = "http://192.168.5.39/app_dev.php/public/get/rates";
    // System.out.println("Requested URL:" + myURL);
    StringBuilder sb = new StringBuilder();
    URLConnection urlConn = null;
    InputStreamReader in = null;
    try {
        URL url = new URL(myURL);
        urlConn = url.openConnection();
        if (urlConn != null) {
            urlConn.setReadTimeout(60 * 1000);
            urlConn.setDoOutput(true);
            String data = URLEncoder.encode("country", "UTF-8") + "=" + URLEncoder.encode(country, "UTF-8");
            data += "&" + URLEncoder.encode("amount", "UTF-8") + "=" + URLEncoder.encode(amount, "UTF-8");

            System.out.println("los Datos a enviar por POST son " + data);

            try ( //obtenemos el flujo de escritura
                    OutputStreamWriter wr = new OutputStreamWriter(urlConn.getOutputStream())) {
                //escribimos
                wr.write(data);
                wr.flush();
                //cerramos la conexin
            }
        }
        if (urlConn != null && urlConn.getInputStream() != null) {
            in = new InputStreamReader(urlConn.getInputStream(), Charset.defaultCharset());

            BufferedReader bufferedReader = new BufferedReader(in);
            if (bufferedReader != null) {
                int cp;
                while ((cp = bufferedReader.read()) != -1) {
                    sb.append((char) cp);
                }
                bufferedReader.close();
            }
        }
        in.close();
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("Exception while calling URL:" + myURL, e);
    }
    String resultado = sb.toString();

    if (sesion.getAttribute("usuario") == null) {

        mav.setViewName("login/login");

    } else {
        sesionUser = sesion.getAttribute("usuario").toString();
        //Detalles detalle = (Detalles) sesion.getAttribute("cuenta");
        mav.addObject("country", detalle.getCiudad());
        mav.addObject("resultado", resultado);

        if (sesion.getAttribute("tipoUsuario").toString().compareTo("Administrador") == 0) {
            mav.setViewName("viewsAdmin/cuotasAdmin");
            System.out.println("el usuario es administrador");
        } else {
            mav.setViewName("panel/cuotas");
        }
    }
    return mav;
}

From source file:com.controller.CuotasController.java

@RequestMapping(value = "postCuotas.htm", method = RequestMethod.POST)
public ModelAndView postCuotas(HttpServletRequest request) {

    sesion = request.getSession();//w  ww .  j av a 2  s  . c  o m
    String country = request.getParameter("country");
    String amount = request.getParameter("amount");

    Detalles detalle = (Detalles) sesion.getAttribute("cuenta");
    System.out.print(detalle.getCiudad());

    String myURL = "http://192.168.5.39/app_dev.php/public/get/rates";
    // System.out.println("Requested URL:" + myURL);
    StringBuilder sb = new StringBuilder();
    URLConnection urlConn = null;
    InputStreamReader in = null;
    try {
        URL url = new URL(myURL);
        urlConn = url.openConnection();
        if (urlConn != null) {
            urlConn.setReadTimeout(60 * 1000);
            urlConn.setDoOutput(true);
            String data = URLEncoder.encode("country", "UTF-8") + "=" + URLEncoder.encode(country, "UTF-8");
            data += "&" + URLEncoder.encode("amount", "UTF-8") + "=" + URLEncoder.encode(amount, "UTF-8");

            System.out.println("los Datos a enviar por POST son " + data);

            try ( //obtenemos el flujo de escritura
                    OutputStreamWriter wr = new OutputStreamWriter(urlConn.getOutputStream())) {
                //escribimos
                wr.write(data);
                wr.flush();
                //cerramos la conexin
            }
        }
        if (urlConn != null && urlConn.getInputStream() != null) {
            in = new InputStreamReader(urlConn.getInputStream(), Charset.defaultCharset());

            BufferedReader bufferedReader = new BufferedReader(in);
            if (bufferedReader != null) {
                int cp;
                while ((cp = bufferedReader.read()) != -1) {
                    sb.append((char) cp);
                }
                bufferedReader.close();
            }
        }
        in.close();
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("Exception while calling URL:" + myURL, e);
    }
    String resultado = sb.toString();

    ModelAndView mav = new ModelAndView();
    if (sesion.getAttribute("usuario") == null) {

        mav.setViewName("login/login");

    } else {
        sesionUser = sesion.getAttribute("usuario").toString();
        //Detalles detalle = (Detalles) sesion.getAttribute("cuenta");
        mav.addObject("country", detalle.getCiudad());
        mav.addObject("resultado", resultado);

        if (sesion.getAttribute("tipoUsuario").toString().compareTo("Administrador") == 0) {
            mav.setViewName("viewsAdmin/cuotasAdmin");
            System.out.println("el usuario es administrador");
        } else {
            mav.setViewName("panel/cuotas");
        }
    }
    return mav;

}

From source file:org.safecreative.api.SafeCreativeAPI.java

public String call(String params) {
    String uri = baseUrl + API_ENDPOINT;
    OutputStream os = null;/*  w  ww  .j a va  2  s.c o  m*/
    String response = null;
    try {
        log.debug(String.format("api request: \n%s?%s\n", uri, params));
        URL url = new URL(uri);
        URLConnection conn = url.openConnection();
        conn.setRequestProperty("Content-type",
                "application/x-www-form-urlencoded;charset=" + DEFAULT_ENCODING);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        os = conn.getOutputStream();
        os.write(params.getBytes(DEFAULT_ENCODING));
        response = readString(conn.getInputStream());
        log.debug(String.format("api response:\n %s\n", response));
        if (isError(response) && INVALID_TIME_ERROR.equals(getErrorCode(response))) {
            log.warn("Client time needs resyncing");
            timeOffset = null;
        }
        return response;
    } catch (Throwable e) {
        throw new RuntimeException(ApiException.wrap(e, uri + "?" + params, response));
    } finally {
        IOHelper.closeQuietly(os);
    }
}

From source file:org.dspace.license.CCLookup.java

/**
    * Passes a set of "answers" to the web service and retrieves a license.
    */*w w w  .  ja  v a2s  .com*/
    * @param licenseURI The uri of the license.
    *
    * Note: does not support localization in 1.5 -- not yet
    *
    * @throws IOException
    *
    * @see CCLicense
    * @see Map
    */
public void issue(String licenseURI) throws IOException {

    // Determine the issue URL
    // Example: http://api.creativecommons.org/rest/1.5/details?
    //  license-uri=http://creativecommons.org/licenses/by-nc-sa/3.0/
    String issueUrl = cc_root + "/details?license-uri=" + licenseURI;

    URL request_url;
    try {
        request_url = new URL(issueUrl);
    } catch (MalformedURLException e) {
        return;
    }
    URLConnection connection = request_url.openConnection();
    // this will not be needed after I'm done TODO: remove
    connection.setDoOutput(true);
    try {
        // parsing document from input stream
        java.io.InputStream stream = connection.getInputStream();
        license_doc = this.parser.build(stream);
    } catch (JDOMException jde) {
        log.warn(jde.getMessage());
    } catch (Exception e) {
        log.warn(e.getCause());
    }
    return;
}