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:com.xeiam.xchange.streaming.socketio.IOConnection.java

/**
 * Handshake.//ww  w.j a va2 s .  co  m
 */
private void handshake() {

    URL url;
    String response;
    URLConnection connection;
    try {
        setState(STATE_HANDSHAKE);
        url = new URL(this.url.getProtocol() + "://" + this.url.getAuthority() + SOCKET_IO_1
                + (this.url.getQuery() == null ? "" : "?" + this.url.getQuery()));
        connection = url.openConnection();
        if (connection instanceof HttpsURLConnection) {
            ((HttpsURLConnection) connection).setSSLSocketFactory(sslSocketFactory);
        }
        connection.setConnectTimeout(connectTimeout);
        connection.setReadTimeout(connectTimeout);

        /* Setting the request headers */
        for (Entry<Object, Object> entry : headers.entrySet()) {
            connection.setRequestProperty((String) entry.getKey(), (String) entry.getValue());
        }
        log.debug("> " + connection.toString());
        InputStream stream = connection.getInputStream();
        Scanner in = new Scanner(stream);
        response = in.nextLine();
        log.debug("< " + response);
        String[] data = response.split(":");
        sessionId = data[0];
        heartbeatTimeout = Long.parseLong(data[1]) * 1000;
        closingTimeout = Long.parseLong(data[2]) * 1000;
        protocols = Arrays.asList(data[3].split(","));
    } catch (Exception e) {
        error(new SocketIOException("Error while handshaking", e));
    }
}

From source file:de.mmbbs.io.socket.IOConnection.java

/**
 * Handshake./*  w ww  .j av a  2 s  .  c om*/
 * 
 */
private void handshake() {
    URL url;
    String response = "";
    URLConnection connection;
    try {
        setState(STATE_HANDSHAKE);
        url = new URL(IOConnection.this.url.toString() + SOCKET_IO_1 + "?EIO=2&transport=polling");
        logger.info("URL: " + url.toString());
        connection = url.openConnection();
        if (connection instanceof HttpsURLConnection) {
            ((HttpsURLConnection) connection).setSSLSocketFactory(sslContext.getSocketFactory());
        }
        connection.setConnectTimeout(connectTimeout);
        connection.setReadTimeout(connectTimeout);

        /* Setting the request headers */
        for (Entry<Object, Object> entry : headers.entrySet()) {
            connection.setRequestProperty((String) entry.getKey(), (String) entry.getValue());
        }

        BufferedReader inB = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String inputLine;
        while ((inputLine = inB.readLine()) != null) {
            response += inputLine;
        }
        inB.close();

        //         InputStream stream = connection.getInputStream();
        //         Scanner in = new Scanner(stream);
        //         while (in.hasNext()) 
        //         {
        //            response += in.next();
        //           }
        //         in.close();

        Pattern pattern = Pattern.compile("\\w+:\\w+:\\w+:\\w+");
        Matcher matcher = pattern.matcher(response);
        if (matcher.find()) {
            logger.info("Response: " + response);
            this.version = VersionSocketIO.V09x;
            logger.info("Version: V09x");
            String[] data = response.split(":");
            sessionId = data[0];
            heartbeatTimeout = Long.parseLong(data[1]) * 1000;
            closingTimeout = Long.parseLong(data[2]) * 1000;
            protocols = Arrays.asList(data[3].split(","));
        } else {
            response = response.substring(response.indexOf('{'));
            response = response.substring(0, response.lastIndexOf('}') + 1);
            logger.info("Response: " + response);
            this.version = VersionSocketIO.V10x;
            logger.info("Version: V10x");
            try {
                JSONObject data = null;
                data = new JSONObject(response);
                sessionId = data.getString("sid");
                heartbeatTimeout = data.getLong("pingInterval");
                closingTimeout = data.getLong("pingTimeout");

                //               JSONArray arr = data.getJSONArray("upgrades");
                //               for (int i = 0; i < arr.length(); i++) {
                //                  protocols.add(arr.getString(i));
                //               }
                protocols = new ArrayList<String>();
                protocols.add("websocket");

            } catch (JSONException e) {
                logger.warning("Malformated JSON received");
            }
        }

    } catch (Exception e) {
        error(new SocketIOException("Error while handshaking", e));
    }
}

From source file:org.ramadda.util.Utils.java

/**
 * _more_/*www .  j  av a  2 s.  co m*/
 *
 * @param url _more_
 *
 * @return _more_
 *
 * @throws Exception _more_
 */
public static String readUrl(String url) throws Exception {
    URL u = new URL(url);
    URLConnection connection = new URL(url).openConnection();
    connection.setRequestProperty("User-Agent", "ramadda");
    connection.setRequestProperty("Host", u.getHost());
    InputStream is = connection.getInputStream();
    String s = IOUtil.readContents(is);
    IOUtil.close(is);

    return s;
}

From source file:com.ikanow.infinit.e.data_model.driver.InfiniteDriver.java

public String sendGetRequest(String urlAddress, int redirects) throws Exception {
    if (urlAddress.startsWith("https:")) {
        TrustManagerManipulator.allowAllSSL();
    }//from  w ww .java 2  s  . co  m

    URL url = new URL(urlAddress);
    URLConnection urlConnection = url.openConnection();
    if (cookie != null)
        urlConnection.setRequestProperty("Cookie", cookie);
    if (apiKey != null)
        urlConnection.setRequestProperty("Cookie", apiKey);

    ((HttpURLConnection) urlConnection).setRequestMethod("GET");

    int status = ((HttpURLConnection) urlConnection).getResponseCode();
    // normally, 3xx is redirect
    if (status != HttpURLConnection.HTTP_OK) {
        if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM
                || status == HttpURLConnection.HTTP_SEE_OTHER) {
            if (redirects <= 5) {
                String newUrlAddress = ((HttpURLConnection) urlConnection).getHeaderField("Location");
                if (null != newUrlAddress) {
                    return sendGetRequest(newUrlAddress, redirects + 1);
                }
            }
            //(else carry on, will exception out or something below)
        }
    } //TESTED

    //read back result
    BufferedReader inStream = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
    StringBuilder strBuilder = new StringBuilder();
    String buffer;
    while ((buffer = inStream.readLine()) != null) {
        strBuilder.append(buffer);
    }
    inStream.close();

    //save cookie if cookie is null
    if (cookie == null) {
        String headername;
        for (int i = 1; (headername = urlConnection.getHeaderFieldKey(i)) != null; i++) {
            if (headername.equals("Set-Cookie")) {
                cookie = urlConnection.getHeaderField(i);
                break;
            }
        }
    }
    return strBuilder.toString();
}

From source file:org.apache.synapse.config.SynapseConfigUtils.java

/**
 * Returns a URLCOnnection for given URL. If the URL is https one , then URLConnectin is a
 * HttpsURLCOnnection and it is configured with KeyStores given in the synapse.properties file
 *
 * @param url URL//from  w w  w.j ava 2 s .c o m
 * @return URLConnection for given URL
 */
public static URLConnection getURLConnection(URL url) {

    try {
        if (url == null) {
            if (log.isDebugEnabled()) {
                log.debug("Provided URL is null");
            }
            return null;
        }

        URLConnection connection;
        if (url.getProtocol().equalsIgnoreCase("http") || url.getProtocol().equalsIgnoreCase("https")) {

            Properties synapseProperties = SynapsePropertiesLoader.loadSynapseProperties();

            String proxyHost = synapseProperties.getProperty(SynapseConstants.SYNPASE_HTTP_PROXY_HOST);
            String proxyPort = synapseProperties.getProperty(SynapseConstants.SYNPASE_HTTP_PROXY_PORT);

            // get the list of excluded hosts for proxy
            List<String> excludedHosts = getExcludedHostsForProxy(synapseProperties);

            if (proxyHost != null && proxyPort != null && !excludedHosts.contains(proxyHost)) {
                SocketAddress sockaddr = new InetSocketAddress(proxyHost, Integer.parseInt(proxyPort));
                Proxy proxy = new Proxy(Proxy.Type.HTTP, sockaddr);

                if (url.getProtocol().equalsIgnoreCase("https")) {
                    connection = getHttpsURLConnection(url, synapseProperties, proxy);
                } else {
                    connection = url.openConnection(proxy);
                }
            } else {
                if (url.getProtocol().equalsIgnoreCase("https")) {
                    connection = getHttpsURLConnection(url, synapseProperties, null);
                } else {
                    connection = url.openConnection();
                }
            }

            // try to see weather authentication is required
            String userName = synapseProperties.getProperty(SynapseConstants.SYNPASE_HTTP_PROXY_USER);
            String password = synapseProperties.getProperty(SynapseConstants.SYNPASE_HTTP_PROXY_PASSWORD);
            if (userName != null && password != null) {
                String header = userName + ":" + password;
                byte[] encodedHeaderBytes = new Base64().encode(header.getBytes());
                String encodedHeader = new String(encodedHeaderBytes);

                connection.setRequestProperty("Proxy-Authorization", "Basic " + encodedHeader);
            }
        } else {
            connection = url.openConnection();
        }

        connection.setReadTimeout(getReadTimeout());
        connection.setConnectTimeout(getConnectTimeout());
        connection.setRequestProperty("Connection", "close"); // if http is being used
        return connection;
    } catch (IOException e) {
        handleException("Error reading at URI ' " + url + " ' ", e);
    }
    return null;
}

From source file:com.ikanow.infinit.e.data_model.driver.InfiniteDriver.java

private String sendPostRequest(String urlAddress, String data, int redirects)
        throws MalformedURLException, IOException {
    String result = "";

    if (urlAddress.startsWith("https:")) {
        TrustManagerManipulator.allowAllSSL();
    }/*from ww w.jav  a 2 s .c  o m*/
    URLConnection urlConnection = new URL(urlAddress).openConnection();

    if (cookie != null)
        urlConnection.setRequestProperty("Cookie", cookie);
    if (apiKey != null)
        urlConnection.setRequestProperty("Cookie", apiKey);

    urlConnection.setDoOutput(true);
    urlConnection.setRequestProperty("Accept-Charset", "UTF-8");
    ((HttpURLConnection) urlConnection).setRequestMethod("POST");

    // Post JSON string to URL

    OutputStream os = urlConnection.getOutputStream();

    byte[] b = data.getBytes("UTF-8");

    os.write(b);

    int status = ((HttpURLConnection) urlConnection).getResponseCode();
    // normally, 3xx is redirect
    if (status != HttpURLConnection.HTTP_OK) {
        if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM
                || status == HttpURLConnection.HTTP_SEE_OTHER) {
            if (redirects <= 5) {
                String newUrlAddress = ((HttpURLConnection) urlConnection).getHeaderField("Location");
                if (null != newUrlAddress) {
                    return sendPostRequest(newUrlAddress, data, redirects + 1);
                }
            }
            //(else carry on, will exception out or something below)
        }
    } //TESTED

    // Receive results back from API

    InputStream inStream = urlConnection.getInputStream();

    result = IOUtils.toString(inStream, "UTF-8");

    inStream.close();

    //save cookie if cookie is null
    if (cookie == null) {
        String headername;
        for (int i = 1; (headername = urlConnection.getHeaderFieldKey(i)) != null; i++) {
            if (headername.equals("Set-Cookie")) {
                cookie = urlConnection.getHeaderField(i);
                break;
            }
        }
    }

    return result;
}

From source file:org.apache.jsp.communities_jsp.java

public String callRestfulApi(String addr, HttpServletRequest request, HttpServletResponse response) {
      if (localCookie)
          CookieHandler.setDefault(cm);

      try {/*from  w  ww  . ja va  2s. c  o  m*/
          ByteArrayOutputStream output = new ByteArrayOutputStream();
          URL url = new URL(API_ROOT + addr);
          URLConnection urlConnection = url.openConnection();
          String cookieVal = getBrowserInfiniteCookie(request);
          if (cookieVal != null) {
              urlConnection.addRequestProperty("Cookie", "infinitecookie=" + cookieVal);
              urlConnection.setDoInput(true);
              urlConnection.setDoOutput(true);
              urlConnection.setRequestProperty("Accept-Charset", "UTF-8");
          }
          IOUtils.copy(urlConnection.getInputStream(), output);
          String newCookie = getConnectionInfiniteCookie(urlConnection);
          if (newCookie != null && response != null) {
              setBrowserInfiniteCookie(response, newCookie, request.getServerPort());
          }
          return output.toString();
      } catch (IOException e) {
          System.out.println(e.getMessage());
          return null;
      }
  }

From source file:org.apache.jsp.communities_jsp.java

private String postToRestfulApi(String addr, String data, HttpServletRequest request,
          HttpServletResponse response) {
      if (localCookie)
          CookieHandler.setDefault(cm);
      String result = "";
      try {/* www .j av a  2 s  .com*/
          URLConnection connection = new URL(API_ROOT + addr).openConnection();
          String cookieVal = getBrowserInfiniteCookie(request);
          if (cookieVal != null) {
              connection.addRequestProperty("Cookie", "infinitecookie=" + cookieVal);
              connection.setDoInput(true);
          }
          connection.setDoOutput(true);
          connection.setRequestProperty("Accept-Charset", "UTF-8");

          // Post JSON string to URL
          OutputStream os = connection.getOutputStream();
          byte[] b = data.getBytes("UTF-8");
          os.write(b);

          // Receive results back from API
          InputStream is = connection.getInputStream();
          result = IOUtils.toString(is, "UTF-8");

          String newCookie = getConnectionInfiniteCookie(connection);
          if (newCookie != null && response != null) {
              setBrowserInfiniteCookie(response, newCookie, request.getServerPort());
          }
      } catch (Exception e) {
          //System.out.println("Exception: " + e.getMessage());
      }
      return result;
  }

From source file:com.adobe.aem.demo.communities.Loader.java

private static void doAnalytics(String analytics, String event, String pageURL, String resourcePath,
        String resourceType) {/*from w w  w.j a  v a2  s . c  om*/

    if (analytics != null && pageURL != null && resourcePath != null && resourceType != null && event != null) {

        URLConnection urlConn = null;
        DataOutputStream printout = null;
        BufferedReader input = null;
        String tmp = null;
        try {

            URL pageurl = new URL(pageURL);
            StringBuffer sb = new StringBuffer(
                    "<?xml version=1.0 encoding=UTF-8?><request><sc_xml_ver>1.0</sc_xml_ver>");
            sb.append("<events>" + event + "</events>");
            sb.append("<pageURL>" + pageURL + "</pageURL>");
            sb.append("<pageName>"
                    + pageurl.getPath().substring(1, pageurl.getPath().indexOf(".")).replaceAll("/", ":")
                    + "</pageName>");
            sb.append("<evar1>" + resourcePath + "</evar1>");
            sb.append("<evar2>" + resourceType + "</evar2>");
            sb.append("<visitorID>demomachine</visitorID>");
            sb.append("<reportSuiteID>" + analytics.substring(0, analytics.indexOf(".")) + "</reportSuiteID>");
            sb.append("</request>");

            logger.debug("New Analytics Event: " + sb.toString());

            URL sitecaturl = new URL("http://" + analytics);

            urlConn = sitecaturl.openConnection();
            urlConn.setDoInput(true);
            urlConn.setDoOutput(true);
            urlConn.setUseCaches(false);
            urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            printout = new DataOutputStream(urlConn.getOutputStream());

            printout.writeBytes(sb.toString());
            printout.flush();
            printout.close();

            input = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));

            while (null != ((tmp = input.readLine()))) {
                logger.debug(tmp);
            }
            printout.close();
            input.close();

        } catch (Exception ex) {

            logger.error(ex.getMessage());

        }

    }

}