/**
   * Process connection response data.
   *
   * @param conn connection to read response data from.
   * @return assembled response as string.
   * @throws IOException on I/O error
   */
  private StringBuilder readResponse(URLConnection conn) throws IOException {
    StringBuilder retval = new StringBuilder();
    HttpURLConnection http = (HttpURLConnection) conn;
    int resp = 200;
    try {
      resp = http.getResponseCode();
    } catch (Throwable ex) {
    }

    if (resp >= 200 && resp < 300) {
      BufferedReader input = null;
      try {
        input = new BufferedReader(new InputStreamReader(conn.getInputStream()));
      } catch (Throwable ex) {
        retval.append(ex.toString());
        return retval;
      }

      String line = null;
      while ((line = input.readLine()) != null) {
        retval.append(line);
        retval.append("\n");
      }
      input.close();
    } else {
      retval.append(http.getResponseMessage());
    }

    LogContext.getLogger().finer(String.format("<-- HTTP Response: %d: %s", resp, retval));

    return retval;
  }
Ejemplo n.º 2
1
  private String getResult(String URL, HashMap optionalParameters) {
    StringBuilder sb = new StringBuilder();
    sb.append(URL);
    try {

      Iterator iterator = optionalParameters.keySet().iterator();

      int index = 0;
      while (iterator.hasNext()) {
        if (index == 0) {
          sb.append("?");
        } else {
          sb.append("&");
        }
        String key = (String) iterator.next();
        sb.append(key);
        sb.append("=");
        sb.append(URLEncoder.encode(optionalParameters.get(key).toString(), "UTF-8"));
        index++;
      }

      URI uri = new URI(String.format(sb.toString()));
      URL url = uri.toURL();

      HttpURLConnection conn = (HttpURLConnection) url.openConnection();

      conn.setRequestMethod("GET");
      conn.setRequestProperty("Accept", "application/json");
      conn.setRequestProperty("Authorization", "Bearer " + getAccessToken());
      if (conn.getResponseCode() != 200) {
        throw new RuntimeException(
            "Failed : HTTP error code : "
                + conn.getResponseCode()
                + " - "
                + conn.getResponseMessage());
      }

      BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

      String output;
      sb = new StringBuilder();
      while ((output = br.readLine()) != null) {
        sb.append(output);
      }

      conn.disconnect();

    } catch (IOException e) {

      e.printStackTrace();
      return null;
    } catch (URISyntaxException e) {
      e.printStackTrace();
      return null;
    }
    return sb.toString();
  }
Ejemplo n.º 3
0
  /**
   * Login with user name and password sent as String parameter to url using POST Interrogation
   *
   * @param username
   * @param userpass
   * @throws IOException
   */
  @And("^I make post message with user: \"([^\"]*)\" and password: \"([^\"]*)\"$")
  public void HttpPostForm(String username, String userpass) throws IOException {

    URL url = new URL("http://dippy.trei.ro");

    HttpURLConnection hConnection = (HttpURLConnection) url.openConnection();
    HttpURLConnection.setFollowRedirects(true);

    hConnection.setDoOutput(true);
    hConnection.setRequestMethod("POST");

    PrintStream ps = new PrintStream(hConnection.getOutputStream());
    ps.print("user="******"&amp;pass="******";do_login=Login");
    ps.close();

    hConnection.connect();

    if (HttpURLConnection.HTTP_OK == hConnection.getResponseCode()) {
      InputStream is = hConnection.getInputStream();

      System.out.println("!!! encoding: " + hConnection.getContentEncoding());
      System.out.println("!!! message: " + hConnection.getResponseMessage());

      is.close();
      hConnection.disconnect();
    }
  }
Ejemplo n.º 4
0
  private String getResult(String URL) {
    StringBuilder sb = new StringBuilder();

    try {
      URL url = new URL(URL);
      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      conn.setRequestMethod("GET");
      conn.setRequestProperty("Accept", "application/json");
      conn.setRequestProperty("Authorization", "Bearer " + getAccessToken());

      if (conn.getResponseCode() != 200) {
        throw new RuntimeException(
            "Failed : HTTP error code : "
                + conn.getResponseCode()
                + " - "
                + conn.getResponseMessage());
      }

      BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

      String output;
      while ((output = br.readLine()) != null) {
        sb.append(output);
      }

      conn.disconnect();

    } catch (IOException e) {

      e.printStackTrace();
      return null;
    }

    return sb.toString();
  }
Ejemplo n.º 5
0
  public BoardList() {
    URL url = null;
    HttpURLConnection http_url_connection = null;
    int response_code;
    String response_message;
    InputStreamReader in = null;
    BufferedReader reader = null;
    ParserDelegator pd = null;
    try {
      // httpでhtmlファイルを取得する一連の処理
      url = new URL("http://menu.2ch.net/bbsmenu.html");
      http_url_connection = (HttpURLConnection) url.openConnection();
      http_url_connection.setRequestMethod("GET");
      http_url_connection.setInstanceFollowRedirects(false);
      http_url_connection.setRequestProperty("User-Agent", "Monazilla/1.00");
      response_code = http_url_connection.getResponseCode();
      response_message = http_url_connection.getResponseMessage();
      in = new InputStreamReader(http_url_connection.getInputStream(), "SJIS");
      reader = new BufferedReader(in);

      pd = new ParserDelegator();
      pd.parse(reader, cb, true);
      in.close();
      reader.close();
      http_url_connection.disconnect();
    } catch (IOException e1) {
      e1.printStackTrace();
    }
  }
Ejemplo n.º 6
0
  private String putResult(String URL) {
    StringBuilder sb = new StringBuilder();

    try {
      String finalUrl = "";
      if (URL.contains("?")) {
        String[] parsedUrl = URL.split("\\?");
        String params = URLEncoder.encode(parsedUrl[1], "UTF-8");
        finalUrl = parsedUrl[0] + "?" + params;
      } else {
        finalUrl = URL;
      }

      URL url = new URL(finalUrl);
      HttpURLConnection conn = (HttpURLConnection) url.openConnection();

      conn.setRequestMethod("PUT");
      conn.setRequestProperty("Accept", "application/json");
      conn.setRequestProperty("Authorization", "Bearer " + getAccessToken());
      if (conn.getResponseCode() != 200 | conn.getResponseCode() != 201) {
        throw new RuntimeException(
            "Failed : HTTP error code : "
                + conn.getResponseCode()
                + " - "
                + conn.getResponseMessage());
      }

      BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

      String output;
      sb = new StringBuilder();
      while ((output = br.readLine()) != null) {
        sb.append(output);
      }

      conn.disconnect();

    } catch (IOException e) {

      e.printStackTrace();
      return null;
    }

    return sb.toString();
  }
  public InputStream upload() throws ResourceUploaderException {

    try {

      try {
        URL url = new URL(target.toString().replaceAll(" ", "%20"));

        // some authentications screw up without an explicit port number here

        String protocol = url.getProtocol().toLowerCase();

        if (url.getPort() == -1) {

          int target_port;

          if (protocol.equals("http")) {

            target_port = 80;

          } else {

            target_port = 443;
          }

          try {
            String str = target.toString().replaceAll(" ", "%20");

            int pos = str.indexOf("://");

            pos = str.indexOf("/", pos + 4);

            // might not have a trailing "/"

            if (pos == -1) {

              url = new URL(str + ":" + target_port + "/");

            } else {

              url = new URL(str.substring(0, pos) + ":" + target_port + str.substring(pos));
            }

          } catch (Throwable e) {

            Debug.printStackTrace(e);
          }
        }

        url = AddressUtils.adjustURL(url);

        try {
          if (user_name != null) {

            SESecurityManager.setPasswordHandler(url, this);
          }

          for (int i = 0; i < 2; i++) {

            try {
              HttpURLConnection con;

              if (url.getProtocol().equalsIgnoreCase("https")) {

                // see ConfigurationChecker for SSL client defaults

                HttpsURLConnection ssl_con = (HttpsURLConnection) url.openConnection();

                // allow for certs that contain IP addresses rather than dns names

                ssl_con.setHostnameVerifier(
                    new HostnameVerifier() {
                      public boolean verify(String host, SSLSession session) {
                        return (true);
                      }
                    });

                con = ssl_con;

              } else {

                con = (HttpURLConnection) url.openConnection();
              }

              con.setRequestMethod("POST");

              con.setRequestProperty(
                  "User-Agent", Constants.AZUREUS_NAME + " " + Constants.AZUREUS_VERSION);

              con.setDoOutput(true);
              con.setDoInput(true);

              OutputStream os = con.getOutputStream();

              byte[] buffer = new byte[65536];

              while (true) {

                int len = data.read(buffer);

                if (len <= 0) {

                  break;
                }

                os.write(buffer, 0, len);
              }

              con.connect();

              int response = con.getResponseCode();

              if ((response != HttpURLConnection.HTTP_ACCEPTED)
                  && (response != HttpURLConnection.HTTP_OK)) {

                throw (new ResourceUploaderException(
                    "Error on connect for '"
                        + url.toString()
                        + "': "
                        + Integer.toString(response)
                        + " "
                        + con.getResponseMessage()));
              }

              return (con.getInputStream());

            } catch (SSLException e) {

              if (i == 0) {

                if (SESecurityManager.installServerCertificates(url) != null) {

                  // certificate has been installed

                  continue; // retry with new certificate
                }
              }

              throw (e);
            }
          }

          throw (new ResourceUploaderException("Should never get here"));

        } finally {

          if (user_name != null) {

            SESecurityManager.setPasswordHandler(url, null);
          }
        }
      } catch (java.net.MalformedURLException e) {

        throw (new ResourceUploaderException(
            "Exception while parsing URL '" + target + "':" + e.getMessage(), e));

      } catch (java.net.UnknownHostException e) {

        throw (new ResourceUploaderException(
            "Exception while initializing download of '"
                + target
                + "': Unknown Host '"
                + e.getMessage()
                + "'",
            e));

      } catch (java.io.IOException e) {

        throw (new ResourceUploaderException(
            "I/O Exception while downloading '" + target + "':" + e.toString(), e));
      }
    } catch (Throwable e) {

      ResourceUploaderException rde;

      if (e instanceof ResourceUploaderException) {

        rde = (ResourceUploaderException) e;

      } else {

        rde = new ResourceUploaderException("Unexpected error", e);
      }

      throw (rde);

    } finally {

      try {
        data.close();

      } catch (Throwable e) {

        e.printStackTrace();
      }
    }
  }
Ejemplo n.º 8
0
  SOAPMessage doGet(URL endPoint) throws SOAPException {
    boolean isFailure = false;

    URL url = null;
    HttpURLConnection httpConnection = null;

    int responseCode = 0;
    try {
      /// Is https GET allowed??
      if (endPoint.getProtocol().equals("https")) initHttps();
      // Process the URL
      JaxmURI uri = new JaxmURI(endPoint.toString());
      String userInfo = uri.getUserinfo();

      url = endPoint;

      if (dL > 0) d("uri: " + userInfo + " " + url + " " + uri);

      // TBD
      //    Will deal with https later.
      if (!url.getProtocol().equalsIgnoreCase("http")
          && !url.getProtocol().equalsIgnoreCase("https")) {
        log.severe("SAAJ0052.p2p.protocol.mustbe.http.or.https");
        throw new IllegalArgumentException(
            "Protocol " + url.getProtocol() + " not supported in URL " + url);
      }
      httpConnection = (HttpURLConnection) createConnection(url);

      httpConnection.setRequestMethod("GET");

      httpConnection.setDoOutput(true);
      httpConnection.setDoInput(true);
      httpConnection.setUseCaches(false);
      httpConnection.setFollowRedirects(true);

      httpConnection.connect();

      try {

        responseCode = httpConnection.getResponseCode();

        // let HTTP_INTERNAL_ERROR (500) through because it is used for SOAP faults
        if (responseCode == HttpURLConnection.HTTP_INTERNAL_ERROR) {
          isFailure = true;
        } else if ((responseCode / 100) != 2) {
          log.log(
              Level.SEVERE,
              "SAAJ0008.p2p.bad.response",
              new String[] {httpConnection.getResponseMessage()});
          throw new SOAPExceptionImpl(
              "Bad response: (" + responseCode + httpConnection.getResponseMessage());
        }
      } catch (IOException e) {
        // on JDK1.3.1_01, we end up here, but then getResponseCode() succeeds!
        responseCode = httpConnection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_INTERNAL_ERROR) {
          isFailure = true;
        } else {
          throw e;
        }
      }

    } catch (SOAPException ex) {
      throw ex;
    } catch (Exception ex) {
      log.severe("SAAJ0012.p2p.get.failed");
      throw new SOAPExceptionImpl("Get failed", ex);
    }

    SOAPMessage response = null;
    if (responseCode == HttpURLConnection.HTTP_OK || isFailure) {
      try {
        MimeHeaders headers = new MimeHeaders();

        String key, value;

        // Header field 0 is the status line so we skip it.

        int i = 1;

        while (true) {
          key = httpConnection.getHeaderFieldKey(i);
          value = httpConnection.getHeaderField(i);

          if (key == null && value == null) break;

          if (key != null) {
            StringTokenizer values = new StringTokenizer(value, ",");
            while (values.hasMoreTokens()) headers.addHeader(key, values.nextToken().trim());
          }
          i++;
        }

        InputStream httpIn =
            (isFailure ? httpConnection.getErrorStream() : httpConnection.getInputStream());
        // If no reply message is returned,
        // content-Length header field value is expected to be zero.
        // java SE 6 documentation says :
        // available() : an estimate of the number of bytes that can be read
        // (or skipped over) from this input stream without blocking
        // or 0 when it reaches the end of the input stream.
        if ((httpIn == null)
            || (httpConnection.getContentLength() == 0)
            || (httpIn.available() == 0)) {
          response = null;
          log.warning("SAAJ0014.p2p.content.zero");
        } else {
          response = messageFactory.createMessage(headers, httpIn);
        }

        httpIn.close();
        httpConnection.disconnect();

      } catch (SOAPException ex) {
        throw ex;
      } catch (Exception ex) {
        log.log(Level.SEVERE, "SAAJ0010.p2p.cannot.read.resp", ex);
        throw new SOAPExceptionImpl("Unable to read response: " + ex.getMessage());
      }
    }
    return response;
  }
Ejemplo n.º 9
0
  SOAPMessage post(SOAPMessage message, URL endPoint) throws SOAPException {
    boolean isFailure = false;

    URL url = null;
    HttpURLConnection httpConnection = null;

    int responseCode = 0;
    try {
      if (endPoint.getProtocol().equals("https"))
        // if(!setHttps)
        initHttps();
      // Process the URL
      JaxmURI uri = new JaxmURI(endPoint.toString());
      String userInfo = uri.getUserinfo();

      url = endPoint;

      if (dL > 0) d("uri: " + userInfo + " " + url + " " + uri);

      // TBD
      //    Will deal with https later.
      if (!url.getProtocol().equalsIgnoreCase("http")
          && !url.getProtocol().equalsIgnoreCase("https")) {
        log.severe("SAAJ0052.p2p.protocol.mustbe.http.or.https");
        throw new IllegalArgumentException(
            "Protocol " + url.getProtocol() + " not supported in URL " + url);
      }
      httpConnection = (HttpURLConnection) createConnection(url);

      httpConnection.setRequestMethod("POST");

      httpConnection.setDoOutput(true);
      httpConnection.setDoInput(true);
      httpConnection.setUseCaches(false);
      httpConnection.setInstanceFollowRedirects(true);

      if (message.saveRequired()) message.saveChanges();

      MimeHeaders headers = message.getMimeHeaders();

      Iterator it = headers.getAllHeaders();
      boolean hasAuth = false; // true if we find explicit Auth header
      while (it.hasNext()) {
        MimeHeader header = (MimeHeader) it.next();

        String[] values = headers.getHeader(header.getName());
        if (values.length == 1)
          httpConnection.setRequestProperty(header.getName(), header.getValue());
        else {
          StringBuffer concat = new StringBuffer();
          int i = 0;
          while (i < values.length) {
            if (i != 0) concat.append(',');
            concat.append(values[i]);
            i++;
          }

          httpConnection.setRequestProperty(header.getName(), concat.toString());
        }

        if ("Authorization".equals(header.getName())) {
          hasAuth = true;
          log.fine("SAAJ0091.p2p.https.auth.in.POST.true");
        }
      }

      if (!hasAuth && userInfo != null) {
        initAuthUserInfo(httpConnection, userInfo);
      }

      OutputStream out = httpConnection.getOutputStream();
      message.writeTo(out);

      out.flush();
      out.close();

      httpConnection.connect();

      try {

        responseCode = httpConnection.getResponseCode();

        // let HTTP_INTERNAL_ERROR (500) through because it is used for SOAP faults
        if (responseCode == HttpURLConnection.HTTP_INTERNAL_ERROR) {
          isFailure = true;
        }
        // else if (responseCode != HttpURLConnection.HTTP_OK)
        // else if (!(responseCode >= HttpURLConnection.HTTP_OK && responseCode < 207))
        else if ((responseCode / 100) != 2) {
          log.log(
              Level.SEVERE,
              "SAAJ0008.p2p.bad.response",
              new String[] {httpConnection.getResponseMessage()});
          throw new SOAPExceptionImpl(
              "Bad response: (" + responseCode + httpConnection.getResponseMessage());
        }
      } catch (IOException e) {
        // on JDK1.3.1_01, we end up here, but then getResponseCode() succeeds!
        responseCode = httpConnection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_INTERNAL_ERROR) {
          isFailure = true;
        } else {
          throw e;
        }
      }

    } catch (SOAPException ex) {
      throw ex;
    } catch (Exception ex) {
      log.severe("SAAJ0009.p2p.msg.send.failed");
      throw new SOAPExceptionImpl("Message send failed", ex);
    }

    SOAPMessage response = null;
    if (responseCode == HttpURLConnection.HTTP_OK || isFailure) {
      try {
        MimeHeaders headers = new MimeHeaders();

        String key, value;

        // Header field 0 is the status line so we skip it.

        int i = 1;

        while (true) {
          key = httpConnection.getHeaderFieldKey(i);
          value = httpConnection.getHeaderField(i);

          if (key == null && value == null) break;

          if (key != null) {
            StringTokenizer values = new StringTokenizer(value, ",");
            while (values.hasMoreTokens()) headers.addHeader(key, values.nextToken().trim());
          }
          i++;
        }

        InputStream httpIn =
            (isFailure ? httpConnection.getErrorStream() : httpConnection.getInputStream());

        byte[] bytes = readFully(httpIn);

        int length =
            httpConnection.getContentLength() == -1
                ? bytes.length
                : httpConnection.getContentLength();

        // If no reply message is returned,
        // content-Length header field value is expected to be zero.
        if (length == 0) {
          response = null;
          log.warning("SAAJ0014.p2p.content.zero");
        } else {
          ByteInputStream in = new ByteInputStream(bytes, length);
          response = messageFactory.createMessage(headers, in);
        }

        httpIn.close();
        httpConnection.disconnect();

      } catch (SOAPException ex) {
        throw ex;
      } catch (Exception ex) {
        log.log(Level.SEVERE, "SAAJ0010.p2p.cannot.read.resp", ex);
        throw new SOAPExceptionImpl("Unable to read response: " + ex.getMessage());
      }
    }
    return response;
  }