Example usage for java.net URLConnection setRequestProperty

List of usage examples for java.net URLConnection setRequestProperty

Introduction

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

Prototype

public void setRequestProperty(String key, String value) 

Source Link

Document

Sets the general request property.

Usage

From source file:org.openehealth.coms.cc.consent_applet.applet.ConsentApplet.java

/**
 * Requests all TreeNodes containing the given String in their Name-attribute
 *  //from w ww  . ja  v a 2 s.  c o  m
 * @param searchString
 */
private void requestSearchTree(String searchString) {

    if (searchString.trim().equalsIgnoreCase("")) {
        requestTreeRoot();
    } else {

        try {
            String toBeURL = strRelURL + "/" + privilegedServlet
                    + "CreateConsentServiceServlet?type=searchtree&searchstring=" + searchString;

            URL url = new URL(encodeString(toBeURL));
            URLConnection conn = url.openConnection();
            conn.setRequestProperty("cookie", strCookie);
            conn.setDoInput(true);

            InputStream is = conn.getInputStream();
            StringWriter writer = new StringWriter();
            IOUtils.copy(new InputStreamReader(is, "UTF8"), writer);
            String s = writer.toString();

            is.close();

            JSONObject jso = new JSONObject(s);

            OIDObject root = new OIDObject(jso.getString("identifier"), jso.getString("name"),
                    jso.getBoolean("isActive"));

            root.setHasChildren(jso.getBoolean("hasChildren"));

            DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode(root);

            reconstructTree(rootNode, jso);

            oidTreeModel = new DefaultTreeModel(rootNode);
            cap.setOIDTree(oidTreeModel, null, new OIDTreeSelectionListener());

            int row = 0;
            while (row < cap.mainPanel.mp.cp.tp.orgaTree.getRowCount()) {
                cap.mainPanel.mp.cp.tp.orgaTree.expandRow(row);
                row++;
            }

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

From source file:org.openehealth.coms.cc.consent_applet.applet.ConsentApplet.java

/**
 * Requests that a electronically signed CDA Document object be stored
 * //from   w ww  .j a v a  2 s. c  om
 * @param storeUrl
 */
private void requestStoreSignedConsent(String storeUrl) {
    try {

        URL url = new URL(strRelURL + storeUrl);
        URLConnection conn = url.openConnection();
        conn.setRequestProperty("cookie", strCookie);
        conn.setRequestProperty("Content-Type", "text/xml");
        conn.setRequestProperty("Character-Encoding", "UTF-8");

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

        DOMSource domSource = new DOMSource(cda);
        StringWriter owriter = new StringWriter();
        StreamResult result = new StreamResult(owriter);
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.transform(domSource, result);

        ByteArrayOutputStream bStream = new ByteArrayOutputStream();
        ObjectOutputStream oStream = new ObjectOutputStream(bStream);
        oStream.writeObject(cda);
        byte[] byteVal = bStream.toByteArray();

        OutputStream ops = conn.getOutputStream();
        ops.write(byteVal);

        InputStream is = conn.getInputStream();
        StringWriter writer = new StringWriter();
        IOUtils.copy(new InputStreamReader(is, "UTF8"), writer);
        String s = writer.toString();

        is.close();

        JSONObject jso = new JSONObject(s);

        boolean success = jso.getBoolean("success");
        String message = jso.getString("message");

        if (success) {

            JOptionPane.showMessageDialog(this, message, "Erfolg", JOptionPane.INFORMATION_MESSAGE);

        } else {

            JOptionPane.showMessageDialog(this, message, "Fehler", JOptionPane.ERROR_MESSAGE);

        }

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

From source file:org.eclipse.wst.ws.internal.parser.wsil.WebServicesParser.java

private byte[] getInputStreamAsByteArray(String uriString)
        throws MalformedURLException, IOException, WWWAuthenticationException {
    // Try to get a cached copy of the byte[]
    WebServiceEntity wsEntity = getWebServiceEntityByURI(uriString);
    if (wsEntity != null) {
        byte[] bytes = wsEntity.getBytes();
        if (bytes != null)
            return bytes;
    }/*w w w  .j a  v a 2  s . c o m*/
    // Get the byte[] by opening a stream to the URI
    URL url = createURL(uriString);
    URLConnection conn = url.openConnection();
    // proxy server setting
    String proxyUserName = System.getProperty("http.proxyUserName");
    String proxyPassword = System.getProperty("http.proxyPassword");
    if (proxyUserName != null && proxyPassword != null) {
        StringBuffer userNamePassword = new StringBuffer(proxyUserName);
        userNamePassword.append(':').append(proxyPassword);
        Base64 encoder = new Base64();
        String encoding = new String(encoder.encode(userNamePassword.toString().getBytes()));
        userNamePassword.setLength(0);
        userNamePassword.append("Basic ").append(encoding);
        conn.setRequestProperty("Proxy-authorization", userNamePassword.toString());
    }
    // HTTP basic authentication setting
    if (httpBasicAuthUsername_ != null && httpBasicAuthPassword_ != null) {
        StringBuffer sb = new StringBuffer(httpBasicAuthUsername_);
        sb.append(':').append(httpBasicAuthPassword_);
        Base64 encoder = new Base64();
        String encoding = new String(encoder.encode(sb.toString().getBytes()));
        sb.setLength(0);
        sb.append("Basic ").append(encoding);
        conn.setRequestProperty("Authorization", sb.toString());
    }
    InputStream is = null;
    try {
        is = conn.getInputStream();
        String wwwAuthMsg = conn.getHeaderField("WWW-Authenticate");
        if (wwwAuthMsg != null)
            throw new WWWAuthenticationException(new IOException(), wwwAuthMsg, uriString);
    } catch (IOException ioe) {
        String wwwAuthMsg = conn.getHeaderField("WWW-Authenticate");
        if (wwwAuthMsg != null)
            throw new WWWAuthenticationException(ioe, wwwAuthMsg, uriString);
        else
            throw ioe;
    }
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] b = new byte[1024];
    int byteRead = is.read(b);
    while (byteRead != -1) {
        baos.write(b, 0, byteRead);
        byteRead = is.read(b);
    }
    is.close();
    return baos.toByteArray();
}

From source file:it.cicolella.phwswethv2.ProgettiHwSwEthv2.java

private void changeRelayStatus(Board board, Command c) {
    try {/*from www .  j  a v a2 s.c o  m*/
        URL url = null;
        URLConnection urlConnection;
        String delimiter = configuration.getProperty("address-delimiter");
        String[] address = c.getProperty("address").split(delimiter);
        String relayNumber = HexIntConverter.convert(Integer.parseInt(address[1]) - 1);

        // if required set the authentication
        if (board.getAuthentication().equalsIgnoreCase("true")) {
            String authString = board.getUsername() + ":" + board.getPassword();
            byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
            String authStringEnc = new String(authEncBytes);
            //Create a URL for the desired  page   
            url = new URL("http://" + board.getIpAddress() + ":" + board.getPort() + "/protect/"
                    + CHANGE_STATE_RELAY_URL + relayNumber + "=" + c.getProperty("behavior"));
            urlConnection = url.openConnection();
            urlConnection.setRequestProperty("Authorization", "Basic " + authStringEnc);
        } else {
            //Create a URL for the desired  page   
            url = new URL("http://" + board.getIpAddress() + ":" + board.getPort() + "/"
                    + CHANGE_STATE_RELAY_URL + relayNumber + "=" + c.getProperty("behavior"));
            urlConnection = url.openConnection();
        }
        LOG.info("Freedomotic sends the command " + url);
        InputStream is = urlConnection.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        int numCharsRead;
        char[] charArray = new char[1024];
        StringBuffer sb = new StringBuffer();
        while ((numCharsRead = isr.read(charArray)) > 0) {
            sb.append(charArray, 0, numCharsRead);
        }
        String result = sb.toString();
    } catch (MalformedURLException e) {
        LOG.severe("Change relay status malformed URL " + e.toString());
    } catch (IOException e) {
        LOG.severe("Change relay status IOexception" + e.toString());
    }
}

From source file:junk.gui.HazardDataSetCalcCondorApp.java

/**
 * this connects to the servlet on web server to check if dataset name already exists
 * or computation have already been for these parameter settings.
 * @return/*from   ww w  .j a va  2  s  .c o  m*/
 */
private Object checkForHazardMapComputation() {

    try {
        if (D)
            System.out.println("starting to make connection with servlet");
        URL hazardMapServlet = new URL(DATASET_CHECK_SERVLET_URL);

        URLConnection servletConnection = hazardMapServlet.openConnection();
        if (D)
            System.out.println("connection established");

        // inform the connection that we will send output and accept input
        servletConnection.setDoInput(true);
        servletConnection.setDoOutput(true);

        // Don't use a cached version of URL connection.
        servletConnection.setUseCaches(false);
        servletConnection.setDefaultUseCaches(false);
        // Specify the content type that we will send binary data
        servletConnection.setRequestProperty("Content-Type", "application/octet-stream");

        ObjectOutputStream toServlet = new ObjectOutputStream(servletConnection.getOutputStream());

        //sending the parameters info. to the servlet
        toServlet.writeObject(getParametersInfo());

        //sending the dataset id to the servlet
        toServlet.writeObject(datasetIdText.getText());

        toServlet.flush();
        toServlet.close();

        // Receive the datasetnumber from the servlet after it has received all the data
        ObjectInputStream fromServlet = new ObjectInputStream(servletConnection.getInputStream());
        Object obj = fromServlet.readObject();
        //if(D) System.out.println("Receiving the Input from the Servlet:"+success);
        fromServlet.close();
        return obj;

    } catch (Exception e) {
        ExceptionWindow bugWindow = new ExceptionWindow(this, e, getParametersInfo());
        bugWindow.setVisible(true);
        bugWindow.pack();

    }
    return null;
}

From source file:edu.hackathon.perseus.core.httpSpeedTest.java

private double doUpload(String phpFile, InputStream uploadFileIs, String fileName) {
    URLConnection conn = null;
    OutputStream os = null;//w  w  w.jav  a2s  .co m
    InputStream is = null;
    double bw = 0.0;

    try {
        String response = "";
        Date oldTime = new Date();
        URL url = new URL(amazonDomain + "/" + phpFile);
        String boundary = "---------------------------4664151417711";
        conn = url.openConnection();
        conn.setDoOutput(true);
        conn.setConnectTimeout(5000);
        conn.setReadTimeout(5000);

        byte[] fileData = new byte[uploadFileIs.available()];
        uploadFileIs.read(fileData);
        uploadFileIs.close();

        String message1 = "--" + boundary + CrLf;
        message1 += "Content-Disposition: form-data;";
        message1 += "name=\"uploadedfile\"; filename=\"" + fileName + "\"" + CrLf;
        message1 += "Content-Type: text/plain; charset=UTF-8" + CrLf + CrLf;

        // the file is sent between the messages in the multipart message.
        String message2 = CrLf + "--" + boundary + "--" + CrLf;

        conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

        int contentLenght = message1.length() + message2.length() + fileData.length;

        // might not need to specify the content-length when sending chunked data.
        conn.setRequestProperty("Content-Length", String.valueOf(contentLenght));

        os = conn.getOutputStream();

        os.write(message1.getBytes());

        // SEND THE IMAGE
        int index = 0;
        int size = 1024;
        do {
            if ((index + size) > fileData.length) {
                size = fileData.length - index;
            }
            os.write(fileData, index, size);
            index += size;
        } while (index < fileData.length);

        os.write(message2.getBytes());
        os.flush();

        is = conn.getInputStream();

        char buff = 512;
        int len;
        byte[] data = new byte[buff];
        do {
            len = is.read(data);

            if (len > 0) {
                response += new String(data, 0, len);
            }
        } while (len > 0);

        if (response.equals("200")) {
            Date newTime = new Date();
            double milliseconds = newTime.getTime() - oldTime.getTime();
            bw = ((double) contentLenght * 8) / (milliseconds * (double) 1000);
        }
    } catch (Exception e) {
        System.out.println("Exception is fired in upload test. error:" + e.getMessage());
    } finally {
        try {
            os.close();
        } catch (Exception e) {
            //System.out.println("Exception is fired in os.close. error:" + e.getMessage());
        }
        try {
            is.close();
        } catch (Exception e) {
            //System.out.println("Exception is fired in is.close. error:" + e.getMessage());
        }
    }
    return bw;
}

From source file:com.freedomotic.plugins.devices.phwswethv2.ProgettiHwSwEthv2.java

private void changeRelayStatus(Board board, Command c) {
    try {//  w w  w.j a va2  s  .c o m
        URL url = null;
        URLConnection urlConnection;
        String delimiter = configuration.getProperty("address-delimiter");
        String[] address = c.getProperty("address").split(delimiter);
        String relayNumber = HexIntConverter.convert(Integer.parseInt(address[1]) - 1);

        // if required set the authentication
        if (board.getAuthentication().equalsIgnoreCase("true")) {
            String authString = board.getUsername() + ":" + board.getPassword();
            byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
            String authStringEnc = new String(authEncBytes);
            //Create a URL for the desired  page   
            url = new URL("http://" + board.getIpAddress() + ":" + board.getPort() + "/protect/"
                    + CHANGE_STATE_RELAY_URL + relayNumber + "=" + c.getProperty("status"));
            urlConnection = url.openConnection();
            urlConnection.setRequestProperty("Authorization", "Basic " + authStringEnc);
        } else {
            //Create a URL for the desired  page   
            url = new URL("http://" + board.getIpAddress() + ":" + board.getPort() + "/"
                    + CHANGE_STATE_RELAY_URL + relayNumber + "=" + c.getProperty("status"));
            urlConnection = url.openConnection();
        }
        LOG.info("Freedomotic sends the command " + url);
        InputStream is = urlConnection.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        int numCharsRead;
        char[] charArray = new char[1024];
        StringBuffer sb = new StringBuffer();
        while ((numCharsRead = isr.read(charArray)) > 0) {
            sb.append(charArray, 0, numCharsRead);
        }
        String result = sb.toString();
    } catch (MalformedURLException e) {
        LOG.severe("Change relay status malformed URL " + e.toString());
    } catch (IOException e) {
        LOG.severe("Change relay status IOexception" + e.toString());
    }
}

From source file:junk.gui.HazardDataSetCalcCondorApp.java

/**
 * sets up the connection with the servlet on the server (gravity.usc.edu)
 *//*from   ww  w.j av a  2s .  c  om*/
private void sendParametersToServlet(SitesInGriddedRegion regionSites,
        ScalarIntensityMeasureRelationshipAPI imr, String eqkRupForecastLocation) {

    try {
        if (D)
            System.out.println("starting to make connection with servlet");
        URL hazardMapServlet = new URL(SERVLET_URL);

        URLConnection servletConnection = hazardMapServlet.openConnection();
        if (D)
            System.out.println("connection established");

        // inform the connection that we will send output and accept input
        servletConnection.setDoInput(true);
        servletConnection.setDoOutput(true);

        // Don't use a cached version of URL connection.
        servletConnection.setUseCaches(false);
        servletConnection.setDefaultUseCaches(false);
        // Specify the content type that we will send binary data
        servletConnection.setRequestProperty("Content-Type", "application/octet-stream");

        ObjectOutputStream toServlet = new ObjectOutputStream(servletConnection.getOutputStream());

        //sending the object of the gridded region sites to the servlet
        toServlet.writeObject(regionSites);
        //sending the IMR object to the servlet
        toServlet.writeObject(imr);
        //sending the EQK forecast object to the servlet
        toServlet.writeObject(eqkRupForecastLocation);
        //send the X values in a arraylist
        ArrayList list = new ArrayList();
        for (int i = 0; i < function.getNum(); ++i)
            list.add(new String("" + function.getX(i)));
        toServlet.writeObject(list);
        // send the MAX DISTANCE
        toServlet.writeObject(maxDistance);

        //sending email address to the servlet
        toServlet.writeObject(emailText.getText());
        //sending the parameters info. to the servlet
        toServlet.writeObject(getParametersInfo());

        //sending the dataset id to the servlet
        toServlet.writeObject(datasetIdText.getText());

        toServlet.flush();
        toServlet.close();

        // Receive the datasetnumber from the servlet after it has received all the data
        ObjectInputStream fromServlet = new ObjectInputStream(servletConnection.getInputStream());
        String dataset = fromServlet.readObject().toString();
        JOptionPane.showMessageDialog(this, dataset);
        if (D)
            System.out.println("Receiving the Input from the Servlet:" + dataset);
        fromServlet.close();

    } catch (Exception e) {
        ExceptionWindow bugWindow = new ExceptionWindow(this, e, getParametersInfo());
        bugWindow.setVisible(true);
        bugWindow.pack();
    }
}

From source file:savant.view.swing.Savant.java

private static void logUsageStats() {
    try {//from w  ww  .ja  v  a2  s.  co  m
        URLConnection urlConn;
        DataOutputStream printout;
        // URL of CGI-Bin script.
        // URL connection channel.
        urlConn = BrowserSettings.LOG_USAGE_STATS_URL.openConnection();
        // Let the run-time system (RTS) know that we want input.
        urlConn.setDoInput(true);
        // Let the RTS know that we want to do output.
        urlConn.setDoOutput(true);
        // No caching, we want the real thing.
        urlConn.setUseCaches(false);
        // Specify the content type.
        urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        // Send POST output.
        printout = new DataOutputStream(urlConn.getOutputStream());

        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        Date date = new Date();
        Locale locale = Locale.getDefault();

        String content = post("time", dateFormat.format(date)) + "&"
                + post("language", locale.getDisplayLanguage()) + "&"
                + post("user.timezone", System.getProperty("user.timezone")) + "&"
                + post("savant.version", BrowserSettings.VERSION) + "&"
                + post("savant.build", BrowserSettings.BUILD)
                //+ "&" + post("address", InetAddress.getLocalHost().getHostAddress())
                + "&" + post("java.version", System.getProperty("java.version")) + "&"
                + post("java.vendor", System.getProperty("java.vendor")) + "&"
                + post("os.name", System.getProperty("os.name")) + "&"
                + post("os.arch", System.getProperty("os.arch")) + "&"
                + post("os.version", System.getProperty("os.version")) + "&"
                + post("user.region", System.getProperty("user.region"));

        printout.writeBytes(content);
        printout.flush();
        printout.close();
        urlConn.getInputStream();
    } catch (Exception ex) {
        //LOG.error("Error logging usage stats.", ex);
    }
}