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

/**
 * ? URL ??POST/*  ww w. j av  a2s .  c  o  m*/
 *
 * @param url
 *               ?? URL
 * @param param
 *               ?? name1=value1&name2=value2 ?
 * @param sessionId
 *             ???
 * @return ??
 */
public static Map<String, String> sendPost(String url, String param, String sessionId) {
    Map<String, String> resultMap = new HashMap<String, String>();
    PrintWriter out = null;
    BufferedReader in = null;
    String result = "";
    try {
        URL realUrl = new URL(url);
        // URL
        URLConnection conn = realUrl.openConnection();
        // 
        //conn.setRequestProperty("Host", "quote.zhonghe-bj.com:8085");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        conn.setRequestProperty("Accept", "*/*");
        conn.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");
        conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
        if (StringUtils.isNotBlank(sessionId)) {
            conn.setRequestProperty("Cookie", sessionId);
        }
        // ??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 cookieValue = conn.getHeaderField("Set-Cookie");
        resultMap.put("cookieValue", cookieValue);
        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();
        }
    }
    resultMap.put("result", result);
    return resultMap;
}

From source file:de.thejeterlp.bukkit.updater.Updater.java

/**
 * Index:// ww  w  . j av a  2 s .  c  o  m
 * 0: downloadUrl
 * 1: name
 * 2: releaseType
 *
 * @return
 */
protected String[] read() {
    debug("Method: read()");
    try {
        URLConnection conn = url.openConnection();
        conn.setConnectTimeout(5000);
        conn.setDoOutput(true);
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String response = reader.readLine();
        JSONArray array = (JSONArray) JSONValue.parse(response);
        if (array.size() == 0)
            return null;
        Map<?, ?> map = (Map) array.get(array.size() - 1);
        String downloadUrl = (String) map.get("downloadUrl");
        String name = (String) map.get("name");
        String releaseType = (String) map.get("releaseType");
        return new String[] { downloadUrl, name, releaseType };
    } catch (Exception e) {
        main.getLogger().severe("Error on trying to check remote versions. Error: " + e);
        return null;
    }
}

From source file:org.apache.cayenne.rop.http.HttpROPConnector.java

protected InputStream doRequest(byte[] data) throws IOException {
    URLConnection connection = new URL(url).openConnection();

    if (readTimeout != null) {
        connection.setReadTimeout(readTimeout.intValue());
    }//from   w ww. jav a  2 s. com

    addAuthHeader(connection);
    addSessionCookie(connection);
    connection.setDoOutput(true);

    connection.setRequestProperty("Content-Type", "application/octet-stream");

    if (data != null) {
        try (OutputStream output = connection.getOutputStream()) {
            output.write(data);
            output.flush();
        }
    }

    return connection.getInputStream();
}

From source file:org.wso2.es.integration.common.utils.AssetsRESTClient.java

/**
 * This methods make a call to ES-Publisher REST API and obtain a valid sessionID
 *
 * @return SessionId for the authenticated user
 *//*from   w w  w  .ja v a2s  . c o m*/
private String login() throws IOException {
    String sessionID = null;
    Reader input = null;
    BufferedWriter writer = null;
    String authenticationEndpoint = getBaseUrl() + PUBLISHER_APIS_AUTHENTICATE_ENDPOINT;
    //construct full authenticate endpoint
    try {
        //authenticate endpoint URL
        URL endpointUrl = new URL(authenticationEndpoint);
        URLConnection urlConn = endpointUrl.openConnection();
        urlConn.setDoInput(true);
        urlConn.setDoOutput(true);
        urlConn.setUseCaches(false);
        // Specify the content type.
        urlConn.setRequestProperty(CONTENT_TYPE_HEADER, CONTENT_TYPE);
        // Send POST output.
        writer = new BufferedWriter(new OutputStreamWriter(urlConn.getOutputStream()));
        String content = USERNAME + "=" + URLEncoder.encode(USERNAME_VAL, UTF_8) + "&" + PASSWORD + "="
                + URLEncoder.encode(PASSWORD_VAl, UTF_8);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Send Login Information : " + content);
        }
        writer.write(content);
        writer.flush();

        // Get response data.
        input = new InputStreamReader(urlConn.getInputStream());
        JsonElement elem = parser.parse(input);
        sessionID = elem.getAsJsonObject().getAsJsonObject(AUTH_RESPONSE_WRAP_KEY).get(SESSIONID).toString();
        if (LOG.isDebugEnabled()) {
            LOG.debug("Received SessionID : " + sessionID);
        }

    } catch (MalformedURLException e) {
        LOG.error(getLoginErrorMassage(authenticationEndpoint), e);
        throw e;
    } catch (IOException e) {
        LOG.error(getLoginErrorMassage(authenticationEndpoint), e);
        throw e;
    } finally {
        if (input != null) {
            try {
                input.close();// will close the URL connection as well
            } catch (IOException e) {
                LOG.error("Failed to close input stream ", e);
            }
        }
        if (writer != null) {
            try {
                writer.close();// will close the URL connection as well
            } catch (IOException e) {
                LOG.error("Failed to close output stream ", e);
            }
        }
    }
    return sessionID;
}

From source file:xtuaok.sharegyazo.HttpMultipartPostRequest.java

public String send() {
    URLConnection conn = null;
    String res = null;//from w w  w.  ja v  a  2s  .c om
    try {
        conn = new URL(mCgi).openConnection();
        conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
        ((HttpURLConnection) conn).setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.connect();

        OutputStream os = conn.getOutputStream();
        os.write(createBoundaryMessage("imagedata").getBytes());
        os.write(mByteData);
        String endBoundary = "\r\n--" + BOUNDARY + "--\r\n";
        os.write(endBoundary.getBytes());
        os.close();

        InputStream is = conn.getInputStream();
        res = convertToString(is);
    } catch (Exception e) {
        Log.d(LOG_TAG, e.getMessage() + "");
    } finally {
        if (conn != null) {
            ((HttpURLConnection) conn).disconnect();
        }
    }
    return res;
}

From source file:jp.go.nict.langrid.serviceexecutor.google.GoogleTranslation.java

@SuppressWarnings("unchecked")
private String invokeTranslation(Language sourceLang, Language targetLang, String source)
        throws InvalidParameterException, ProcessFailedException {
    InputStream is = null;//from   w  w  w .j  av  a 2  s . c  o m
    try {
        URLConnection con = new URL(TRANSLATE_URL).openConnection();
        con.setDoOutput(true);
        con.setReadTimeout(timeoutMillis);
        con.addRequestProperty("Referer", referer);
        writeParameters(con, sourceLang, targetLang, source);

        is = con.getInputStream();
        String json = StreamUtil.readAsString(is, CharsetUtil.newUTF8Decoder());
        try {
            TranslationResult result = JSON.decode(json, TranslationResult.class);
            ResponseData responseData = result.responseData;
            int status = result.responseStatus;
            String key = sourceLang.getCode() + ":" + targetLang.getCode();
            if (status == 200) {
                langPairCache.putInCache(key, true);
                return StringEscapeUtils.unescapeHtml(responseData.translatedText.replaceAll("&#39;", "'"));
            } else {
                String details = result.responseDetails;
                if (details.equals("invalid translation language pair")) {
                    langPairCache.putInCache(key, false);
                    languagePairValidator.get().getUniqueLanguagePair(Collections.EMPTY_LIST);
                }
                throw new ProcessFailedException(result.responseStatus + ": " + details);
            }
        } catch (JSONException e) {
            String message = "failed to read translated text: " + json;
            logger.log(Level.WARNING, message, e);
            throw new ProcessFailedException(message);
        }
    } catch (IOException e) {
        logger.log(Level.SEVERE, "failed to execute service.", e);
        throw new ProcessFailedException(e);
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:jp.go.nict.langrid.serviceexecutor.google.GoogleTranslation.java

@SuppressWarnings("unchecked")
private ArrayList<String> invokeBatchTranslation(Language sourceLang, Language targetLang, String[] sources)
        throws InvalidParameterException, ProcessFailedException {
    InputStream is = null;//w  w  w.  ja v a 2 s  .c o m
    try {
        URLConnection con = new URL(TRANSLATE_URL).openConnection();
        con.setDoOutput(true);
        con.setReadTimeout(timeoutMillis);
        con.addRequestProperty("Referer", referer);
        writeParameters(con, sourceLang, targetLang, sources);

        is = con.getInputStream();
        String json = StreamUtil.readAsString(is, CharsetUtil.newUTF8Decoder());
        try {
            BatchTranslationResult result = JSON.decode(json, BatchTranslationResult.class);
            int status = result.responseStatus;
            String key = sourceLang.getCode() + ":" + targetLang.getCode();

            if (status == 200) {
                langPairCache.putInCache(key, true);
                ArrayList<String> resultArray = new ArrayList<String>();
                for (TranslationResult r : result.responseData) {
                    resultArray.add(StringEscapeUtils
                            .unescapeHtml(r.responseData.translatedText.replaceAll("&#39;", "'")));
                }
                return resultArray;
            } else {
                String details = result.responseDetails;
                if (details.equals("invalid translation language pair")) {
                    langPairCache.putInCache(key, false);
                    languagePairValidator.get().getUniqueLanguagePair(Collections.EMPTY_LIST);
                }
                throw new ProcessFailedException(result.responseStatus + ": " + details);
            }
        } catch (JSONException e) {
            String message = "failed to read translated text: " + json;
            logger.log(Level.WARNING, message, e);
            throw new ProcessFailedException(message);
        }
    } catch (IOException e) {
        logger.log(Level.SEVERE, "failed to execute service.", e);
        throw new ProcessFailedException(e);
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:ubic.gemma.loader.protein.biomart.BiomartEnsemblNcbiFetcher.java

/**
 * Submit a xml query to biomart service return the returned data as a bufferedreader
 * //from   w ww . j  ava  2  s  .  com
 * @param urlToRead Biomart configured URL
 * @param data The query data for biomart
 * @return BufferedReader Stream to read data from
 */
private BufferedReader readFile(URL urlToRead, String data) {
    URLConnection conn = null;
    OutputStreamWriter writer = null;
    try {
        conn = urlToRead.openConnection();
        conn.setDoOutput(true);
        writer = new OutputStreamWriter(conn.getOutputStream());
        writer.write(data);
        writer.flush();
        writer.close();
        return new BufferedReader(new InputStreamReader(conn.getInputStream()));
    } catch (IOException e) {
        log.error(e);
        throw new RuntimeException(e);
    }
}

From source file:com.linkedin.pinot.perf.PerfBenchmarkDriver.java

public JSONObject postQuery(String query) throws Exception {
    final JSONObject json = new JSONObject();
    json.put("pql", query);

    final long start = System.currentTimeMillis();
    final URLConnection conn = new URL(brokerBaseApiUrl + "/query").openConnection();
    conn.setDoOutput(true);
    final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8"));
    final String reqStr = json.toString();

    writer.write(reqStr, 0, reqStr.length());
    writer.flush();/*from  w  ww .j a va 2  s  . com*/
    final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));

    final StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
        sb.append(line);
    }

    final long stop = System.currentTimeMillis();

    final String res = sb.toString();
    final JSONObject ret = new JSONObject(res);
    ret.put("totalTime", (stop - start));
    if ((ret.getLong("numDocsScanned") > 0) && verbose) {
        LOGGER.info("reqStr = " + reqStr);
        LOGGER.info(" Client side time in ms:" + (stop - start));
        LOGGER.info("numDocScanned : " + ret.getLong("numDocsScanned"));
        LOGGER.info("timeUsedMs : " + ret.getLong("timeUsedMs"));
        LOGGER.info("totalTime : " + ret.getLong("totalTime"));
        LOGGER.info("res = " + res);
    }
    return ret;
}

From source file:ubic.gemma.core.loader.protein.biomart.BiomartEnsemblNcbiFetcher.java

/**
 * Submit a xml query to biomart service return the returned data as a bufferedreader
 *
 * @param urlToRead Biomart configured URL
 * @return BufferedReader Stream to read data from
 *///from w  ww.  j  a  v  a 2 s . c o  m
private BufferedReader readBioMart(URL urlToRead) {
    URLConnection conn;
    try {
        conn = urlToRead.openConnection();
        conn.setReadTimeout(1000 * READ_TIMEOUT_SECONDS);
        conn.setDoOutput(true);
        // try (Writer writer = new OutputStreamWriter( conn.getOutputStream() );) {
        // writer.write( data );
        // writer.flush();
        return new BufferedReader(new InputStreamReader(conn.getInputStream()));
        // }
    } catch (IOException e) {
        log.error(e);
        throw new RuntimeException(e);
    }
}