Example usage for java.net URLConnection getOutputStream

List of usage examples for java.net URLConnection getOutputStream

Introduction

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

Prototype

public OutputStream getOutputStream() throws IOException 

Source Link

Document

Returns an output stream that writes to this connection.

Usage

From source file:eu.europa.ec.markt.dss.validation.tsp.OnlineTSPSource.java

/**
 * Get timestamp token - communications layer
 * /*from ww  w.  j av  a2 s.  co  m*/
 * @return - byte[] - TSA response, raw bytes (RFC 3161 encoded)
 */
protected byte[] getTSAResponse(byte[] requestBytes) throws IOException {
    // Setup the TSA connection

    URL tspUrl = new URL(tspServer);
    URLConnection tsaConnection = tspUrl.openConnection();

    tsaConnection.setDoInput(true);
    tsaConnection.setDoOutput(true);
    tsaConnection.setUseCaches(false);
    tsaConnection.setRequestProperty("Content-Type", "application/timestamp-query");
    // tsaConnection.setRequestProperty("Content-Transfer-Encoding",
    // "base64");
    tsaConnection.setRequestProperty("Content-Transfer-Encoding", "binary");

    OutputStream out = tsaConnection.getOutputStream();
    out.write(requestBytes);
    out.close();

    // Get TSA response as a byte array
    InputStream inp = tsaConnection.getInputStream();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    int bytesRead = 0;
    while ((bytesRead = inp.read(buffer, 0, buffer.length)) >= 0) {
        baos.write(buffer, 0, bytesRead);
    }
    byte[] respBytes = baos.toByteArray();

    String encoding = tsaConnection.getContentEncoding();
    if (encoding != null && encoding.equalsIgnoreCase("base64")) {
        respBytes = new Base64().decode(respBytes);
    }
    return respBytes;
}

From source file:game.Clue.JerseyClient.java

public void sendPUT(String name) {
    System.out.println("SendPUT method called");
    try {//ww  w. j av  a  2 s  . co m
        JSONObject jsonObject = new JSONObject("{name:" + name + "}");

        URL url = new URL(
                "http://ec2-54-165-198-60.compute-1.amazonaws.com:8080/CluelessServer/webresources/service/game/player1");
        URLConnection connection = url.openConnection();
        connection.setDoOutput(true);
        //setDoOutput(true);
        connection.setRequestProperty("PUT", "application/json");

        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);

        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
        out.write(jsonObject.toString());

        System.out.println("Sent PUT message to server");
        out.close();

    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:game.Clue.JerseyClient.java

public void sendPOST() {
    System.out.println("POST method called");
    try {//  ww  w .  j  a v a2s  . c o  m

        JSONObject jsonObject = new JSONObject("{player:Brian}");
        URL url = new URL(
                "http://ec2-54-165-198-60.compute-1.amazonaws.com:8080/CluelessServer/webresources/service/game/");
        URLConnection connection = url.openConnection();
        connection.setDoOutput(true);
        //setDoOutput(true);
        connection.setRequestProperty("POST", "application/json");
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);

        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
        System.out.println(jsonObject.toString());
        out.write("{" + jsonObject.toString());

        System.out.println("Sent PUT message to server");
        out.close();

    } catch (Exception e) {
        System.out.println("\nError while calling REST POST Service");
        System.out.println(e);
    }

}

From source file:com.sabre.hack.travelachievementgame.DSCommHandler.java

public String getAuthToken(String apiEndPoint, String encodedCliAndSecret) {

    //receives : apiEndPoint (https://api.test.sabre.com)
    //encodedCliAndSecret : base64Encode(  base64Encode(V1:[user]:[group]:[domain]) + ":" + base64Encode([secret]) )
    String strRet = null;//from  ww w . j av a 2s  . co  m

    try {

        URL urlConn = new URL(apiEndPoint + "/v1/auth/token");
        URLConnection conn = urlConn.openConnection();

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

        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("Authorization", "Basic " + encodedCliAndSecret);
        conn.setRequestProperty("Accept", "application/json");

        //send request
        DataOutputStream dataOut = new DataOutputStream(conn.getOutputStream());
        dataOut.writeBytes("grant_type=client_credentials");
        dataOut.flush();
        dataOut.close();

        //get response
        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String strChunk = "";
        StringBuilder sb = new StringBuilder();
        while (null != ((strChunk = rd.readLine())))
            sb.append(strChunk);

        //parse the token
        JSONObject respParser = new JSONObject(sb.toString());
        strRet = respParser.getString("access_token");

    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return strRet;

}

From source file:org.wso2.carbon.automation.test.utils.generic.GenericJSONClient.java

public JSONObject doGet(String endpoint, String query, String contentType)
        throws AutomationFrameworkException, IOException {
    String charset = "UTF-8";
    OutputStream os = null;//from w  ww  .  j  a va  2  s  .  c  om
    InputStream is = null;
    try {
        if (contentType == null || "".equals(contentType)) {
            contentType = "application/json";
        }
        URLConnection conn = new URL(endpoint).openConnection();
        conn.setRequestProperty(GenericJSONClient.HEADER_CONTENT_TYPE, contentType);
        conn.setRequestProperty(GenericJSONClient.HEADER_ACCEPT_CHARSET, charset);
        conn.setRequestProperty("Content-Length", "1000");
        conn.setReadTimeout(30000);
        System.setProperty("java.net.preferIPv4Stack", "true");
        conn.setRequestProperty("Connection", "close");
        conn.setDoOutput(true);
        os = conn.getOutputStream();
        os.write(query.getBytes(charset));
        is = conn.getInputStream();
        String out = null;
        if (is != null) {
            StringBuilder source = new StringBuilder();
            byte[] data = new byte[1024];
            int len;
            while ((len = is.read(data)) != -1) {
                source.append(new String(data, 0, len, Charset.defaultCharset()));
            }
            out = source.toString();
        }
        return new JSONObject(out);
    } catch (IOException e) {
        throw new AutomationFrameworkException("Error occurred while executing the GET operation", e);
    } catch (JSONException e) {
        throw new AutomationFrameworkException("Error occurred while parsing the response to a JSONObject", e);
    } finally {
        assert os != null;
        os.flush();
        os.close();
        assert is != null;
        is.close();
    }
}

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

public String call(String params) {
    String uri = baseUrl + API_ENDPOINT;
    OutputStream os = null;/*from w w  w  .ja  va2  s.com*/
    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.kepler.util.AuthNamespace.java

/**
  * Return a unique namespace from the provided authority string.
  * /*w w  w  .  ja v  a  2  s .c  om*/
 * @param authority
 * @return boolean true if success
 * @throws Exception
 */
private boolean queryAuthorizedNamespace(String authority) throws Exception {
    if (isDebugging)
        log.debug("queryAuthorizedNamespace( " + authority + ")");

    // thwart malicious robots
    String data = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode("kepler", "UTF-8");
    data += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode("kepler", "UTF-8");

    try {
        // Send the request
        URL url = new URL(authority);
        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        OutputStream os = conn.getOutputStream();
        OutputStreamWriter wr = new OutputStreamWriter(os);
        wr.write(data);
        wr.flush();

        // Get the response as a set of Properties
        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;
        Properties props = new Properties();
        while ((line = rd.readLine()) != null) {
            if (isDebugging)
                log.debug(line);
            line = line.trim();
            if (line.equals(""))
                continue;
            int equalsIndex = line.indexOf("=");
            if (equalsIndex > 0) {
                String key = line.substring(0, equalsIndex).trim();
                String value = line.substring(equalsIndex + 1).trim();
                props.setProperty(key, value);
            }
        }
        wr.close();
        rd.close();

        // Check to see if there was an error
        String errorString = props.getProperty("error");
        if (errorString != null) {
            log.warn(errorString);
        } else {
            // Check and set the returned namespace
            String newNamespace = props.getProperty("namespace");
            if (newNamespace != null && !newNamespace.equals("")) {
                setAuthority(authority);
                setNamespace(newNamespace);

                try {
                    writeAuthorizedNamespace();
                    return true;
                } catch (Exception e) {
                    log.error("Unable to write " + _saveFileName + " file: " + _anFileName);
                    e.printStackTrace();
                }
            }
        }
    } catch (Exception e) {
        System.out.println(e.toString());
    }

    return false;
}

From source file:game.Clue.JerseyClient.java

public void requestLogintoServer(String name) {

    try {//from   w  w  w  .java 2  s .c o m
        for (int i = 0; i < 6; i++) {
            JSONObject jsonObject = new JSONObject(name);

            URL url = new URL(
                    "http://ec2-54-165-198-60.compute-1.amazonaws.com:8080/CluelessServer/webresources/service/player"
                            + i);
            URLConnection connection = url.openConnection();
            connection.setDoOutput(true);
            //setDoOutput(true);
            connection.setRequestProperty("PUT", "application/json");
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);

            OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
            out.write(jsonObject.toString());

            System.out.println("Sent PUT message for logging into server");
            out.close();
        }
    } catch (Exception e) {
        e.printStackTrace();

    }

}

From source file:org.phaidra.apihooks.APIRESTHooksImpl.java

/**
 * Runs the hook if enabled in fedora.fcfg.
 *
 * @param method The name of the method that calls the hook
 * @param pid The PID that is being accessed
 * @param params Method parameters, depend on the method called
 * @return String Hook verdict. Begins with "OK" if it's ok to proceed.
 * @throws APIHooksException If the remote call went wrong
 *///from  www .  j  av  a 2  s  . c om
public String runHook(String method, DOWriter w, Context context, String pid, Object[] params)
        throws APIHooksException {
    String rval = null;

    // Only do this if the method is enabled in fedora.fcfg
    if (getParameter(method) == null) {
        log.debug("runHook: method |" + method + "| not configured, not calling webservice");
        return "OK";
    }

    Iterator i = context.subjectAttributes();
    String attrs = "";
    while (i.hasNext()) {
        String name = "";
        try {
            name = (String) i.next();
            String[] value = context.getSubjectValues(name);
            for (int j = 0; j < value.length; j++) {
                attrs += "&attr=" + URLEncoder.encode(name + "=" + value[j], "UTF-8");
                log.debug("runHook: will send |" + name + "=" + value[j] + "| as subject attribute");
            }
        } catch (NullPointerException ex) {
            log.debug(
                    "runHook: caught NullPointerException while trying to retrieve subject attribute " + name);
        } catch (UnsupportedEncodingException ex) {
            log.debug("runHook: caught UnsupportedEncodingException while trying to encode subject attribute "
                    + name);
        }
    }
    String paramstr = "";
    try {
        for (int j = 0; j < params.length; j++) {
            paramstr += "&param" + Integer.toString(j) + "=";
            if (params[j] != null) {
                String p = params[j].toString();
                paramstr += URLEncoder.encode(p, "UTF-8");
            }
        }
    } catch (UnsupportedEncodingException ex) {
        log.debug("runHook: caught UnsupportedEncodingException while trying to encode a parameter");
    }

    String loginId = context.getSubjectValue(Constants.SUBJECT.LOGIN_ID.uri);

    log.debug("runHook: called for method=|" + method + "|, pid=|" + pid + "|");
    try {
        // TODO: timeout? retries?
        URL url;
        URLConnection urlConn;
        DataOutputStream printout;
        BufferedReader input;

        url = new URL(getParameter("restmethod"));
        urlConn = url.openConnection();
        urlConn.setDoInput(true);
        urlConn.setDoOutput(true);
        urlConn.setUseCaches(false);
        urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        printout = new DataOutputStream(urlConn.getOutputStream());
        String content = "method=" + URLEncoder.encode(method, "UTF-8") + "&username="
                + URLEncoder.encode(loginId, "UTF-8") + "&pid=" + URLEncoder.encode(pid, "UTF-8") + paramstr
                + attrs;
        printout.writeBytes(content);
        printout.flush();
        printout.close();

        // Get response data.
        input = new BufferedReader(new InputStreamReader(urlConn.getInputStream(), "UTF-8"));
        String str;
        rval = "";
        while (null != ((str = input.readLine()))) {
            rval += str + "\n";
        }
        input.close();

        String ct = urlConn.getContentType();
        if (ct.startsWith("text/xml")) {
            log.debug("runHook: successful REST invocation for method |" + method + "|, returning: " + rval);
        } else if (ct.startsWith("text/plain")) {
            log.debug("runHook: successful REST invocation for method |" + method
                    + "|, but hook returned an error: " + rval);
            throw new Exception(rval);
        } else {
            throw new Exception("Invalid content type " + ct);
        }
    } catch (Exception ex) {
        log.error("runHook: error calling REST hook: " + ex.toString());
        throw new APIHooksException("Error calling REST hook: " + ex.toString(), ex);
    }

    return processResults(rval, w, context);
}

From source file:CounterApp.java

public int getCount() throws Exception {
    java.net.URL url = new java.net.URL(servletURL);
    java.net.URLConnection con = url.openConnection();
    if (sessionCookie != null) {
        con.setRequestProperty("cookie", sessionCookie);
    }//w  ww  .  ja  va  2 s  .co m
    con.setUseCaches(false);
    con.setDoOutput(true);
    con.setDoInput(true);
    ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
    DataOutputStream out = new DataOutputStream(byteOut);
    out.flush();
    byte buf[] = byteOut.toByteArray();
    con.setRequestProperty("Content-type", "application/octet-stream");
    con.setRequestProperty("Content-length", "" + buf.length);
    DataOutputStream dataOut = new DataOutputStream(con.getOutputStream());
    dataOut.write(buf);
    dataOut.flush();
    dataOut.close();
    DataInputStream in = new DataInputStream(con.getInputStream());
    int count = in.readInt();
    in.close();
    if (sessionCookie == null) {
        String cookie = con.getHeaderField("set-cookie");
        if (cookie != null) {
            sessionCookie = parseCookie(cookie);
            System.out.println("Setting session ID=" + sessionCookie);
        }
    }

    return count;
}