private String doCall(String uri) throws IOException {
    System.out.println("We're calling the uri");
    HttpClient httpClient = new HttpClient();
    httpClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    HttpMethod getMethod = new GetMethod(uri);

    try {
      int response = httpClient.executeMethod(getMethod);

      if (response != 200) {
        throw new IOException("HTTP problem, httpcode: " + response);
      }

      InputStream stream = getMethod.getResponseBodyAsStream();
      String responseText = responseToString(stream);
      return responseText;

    } catch (HttpException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }

    return null;
  }
  @Test
  public void testUnsatisfiableRangeRequest() throws IOException, URISyntaxException {
    final URL testResourceUrl =
        new URL(VAULT_BASE_URI.toURL(), "unsatisfiableRangeRequestTestFile.txt");
    final HttpClient client = new HttpClient();

    // prepare file content:
    final byte[] fileContent = "This is some test file content.".getBytes();

    // put request:
    final EntityEnclosingMethod putMethod = new PutMethod(testResourceUrl.toString());
    putMethod.setRequestEntity(new ByteArrayRequestEntity(fileContent));
    final int putResponse = client.executeMethod(putMethod);
    putMethod.releaseConnection();
    Assert.assertEquals(201, putResponse);

    // get request:
    final HttpMethod getMethod = new GetMethod(testResourceUrl.toString());
    getMethod.addRequestHeader("Range", "chunks=1-2");
    final int getResponse = client.executeMethod(getMethod);
    final byte[] response = new byte[fileContent.length];
    IOUtils.read(getMethod.getResponseBodyAsStream(), response);
    getMethod.releaseConnection();
    Assert.assertEquals(416, getResponse);
    Assert.assertArrayEquals(fileContent, response);
  }
  @Test
  public void testFullFileDecryption() throws IOException, URISyntaxException {
    final URL testResourceUrl = new URL(VAULT_BASE_URI.toURL(), "fullFileDecryptionTestFile.txt");
    final HttpClient client = new HttpClient();

    // prepare 64MiB test data:
    final byte[] plaintextData = new byte[16777216 * Integer.BYTES];
    final ByteBuffer bbIn = ByteBuffer.wrap(plaintextData);
    for (int i = 0; i < 16777216; i++) {
      bbIn.putInt(i);
    }
    final InputStream plaintextDataInputStream = new ByteArrayInputStream(plaintextData);

    // put request:
    final EntityEnclosingMethod putMethod = new PutMethod(testResourceUrl.toString());
    putMethod.setRequestEntity(new ByteArrayRequestEntity(plaintextData));
    final int putResponse = client.executeMethod(putMethod);
    putMethod.releaseConnection();
    Assert.assertEquals(201, putResponse);

    // get request:
    final HttpMethod getMethod = new GetMethod(testResourceUrl.toString());
    final int statusCode = client.executeMethod(getMethod);
    Assert.assertEquals(200, statusCode);
    // final byte[] received = new byte[plaintextData.length];
    // IOUtils.read(getMethod.getResponseBodyAsStream(), received);
    // Assert.assertArrayEquals(plaintextData, received);
    Assert.assertTrue(
        IOUtils.contentEquals(plaintextDataInputStream, getMethod.getResponseBodyAsStream()));
    getMethod.releaseConnection();
  }
 @Nullable
 public Task findTask(String id) throws Exception {
   HttpMethod method = doREST("/rest/issue/byid/" + id, false);
   InputStream stream = method.getResponseBodyAsStream();
   Element element = new SAXBuilder(false).build(stream).getRootElement();
   return element.getName().equals("issue") ? createIssue(element) : null;
 }
  /**
   * Submits an HTTP result with the provided HTTPMethod and returns a dom4j document of the
   * response
   *
   * @param callMethod
   * @return
   * @throws ConnectionServiceException
   */
  public static org.dom4j.Document getResultDom4jDocument(HttpClient client, HttpMethod callMethod)
      throws ServiceException {

    try {
      // execute the HTTP call
      int status = client.executeMethod(callMethod);
      if (status != HttpStatus.SC_OK) {
        throw new ServiceException("Web service call failed with code " + status); // $NON-NLS-1$
      }
      // get the result as a string
      InputStream in = callMethod.getResponseBodyAsStream();
      byte buffer[] = new byte[2048];
      int n = in.read(buffer);
      StringBuilder sb = new StringBuilder();
      while (n != -1) {
        sb.append(new String(buffer, 0, n));
        n = in.read(buffer);
      }
      String result = sb.toString();
      // convert to XML
      return DocumentHelper.parseText(result);
    } catch (IOException e) {
      throw new ServiceException(e);
    } catch (DocumentException e) {
      throw new ServiceException(e);
    }
  }
Beispiel #6
0
  @Override
  public void loadResultFile(int fileId, FilePath file) {
    InputStream responseBodyAsStream = null;
    try {
      URL url = new URL(String.format(this.serviceExchangeURL, this.sessionId, fileId));

      HttpClient client = new HttpClient();
      HttpMethod get = new GetMethod(url.toExternalForm());
      client.executeMethod(get);
      responseBodyAsStream = get.getResponseBodyAsStream();

      file.copyFrom(responseBodyAsStream);
    } catch (MalformedURLException e) {
      LOGGER.log(
          Level.SEVERE,
          "Cannot access to exchange service on SCTM. Check the service URL and if SCTM up and running.!",
          e);
    } catch (HttpException e) {
      // handle lost session here
    } catch (IOException e) {
      LOGGER.log(Level.SEVERE, "Cannot load result file from SCTM.", e);
    } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } finally {
      try {
        if (responseBodyAsStream != null) responseBodyAsStream.close();
      } catch (IOException e) {
        LOGGER.log(Level.SEVERE, "Cannot close file stream.", e);
      }
    }
  }
 @Override
 public void run() {
   byte[] buffer = new byte[4096];
   while (!this.stats.isComplete()) {
     HttpMethod httpmethod;
     if (this.content == null) {
       GetMethod httpget = new GetMethod(target.toASCIIString());
       httpmethod = httpget;
     } else {
       PostMethod httppost = new PostMethod(target.toASCIIString());
       httppost.setRequestEntity(new ByteArrayRequestEntity(content));
       httpmethod = httppost;
     }
     long contentLen = 0;
     try {
       httpclient.executeMethod(httpmethod);
       InputStream instream = httpmethod.getResponseBodyAsStream();
       if (instream != null) {
         int l = 0;
         while ((l = instream.read(buffer)) != -1) {
           contentLen += l;
         }
       }
       this.stats.success(contentLen);
     } catch (IOException ex) {
       this.stats.failure(contentLen);
     } finally {
       httpmethod.releaseConnection();
     }
   }
 }
  /**
   * Extracts the response from the method as a InputStream.
   *
   * @param method the method that was executed
   * @return the response either as a stream, or as a deserialized java object
   * @throws IOException can be thrown
   */
  protected static Object extractResponseBody(HttpMethod method, Exchange exchange)
      throws IOException, ClassNotFoundException {
    InputStream is = method.getResponseBodyAsStream();
    if (is == null) {
      return null;
    }

    Header header = method.getResponseHeader(Exchange.CONTENT_ENCODING);
    String contentEncoding = header != null ? header.getValue() : null;

    if (!exchange.getProperty(Exchange.SKIP_GZIP_ENCODING, Boolean.FALSE, Boolean.class)) {
      is = GZIPHelper.uncompressGzip(contentEncoding, is);
    }

    // Honor the character encoding
    String contentType = null;
    header = method.getResponseHeader("content-type");
    if (header != null) {
      contentType = header.getValue();
      // find the charset and set it to the Exchange
      HttpHelper.setCharsetFromContentType(contentType, exchange);
    }
    InputStream response = doExtractResponseBodyAsStream(is, exchange);
    // if content type is a serialized java object then de-serialize it back to a Java object
    if (contentType != null
        && contentType.equals(HttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT)) {
      return HttpHelper.deserializeJavaObjectFromStream(response);
    } else {
      return response;
    }
  }
 public String getHtmlByCode(String code) {
   StringBuffer content = new StringBuffer();
   HttpMethod getMethod = null;
   init();
   try {
     getMethod = new GetMethod(this.getUrl());
     client.executeMethod(getMethod);
     InputStream in = getMethod.getResponseBodyAsStream();
     BufferedReader br = new BufferedReader(new InputStreamReader(in, code), 1024);
     String line = "";
     while ((line = br.readLine()) != null) {
       content.append(line);
     }
     if (br != null) {
       br.close();
       br = null;
     }
     if (in != null) {
       in.close();
       in = null;
     }
   } catch (Exception e) {
     e.printStackTrace();
     release();
   } finally {
     getMethod.releaseConnection();
   }
   return content.toString();
 }
 String getContent(HttpMethod httpMethod) {
   StringBuilder contentBuilder = new StringBuilder();
   if (isZipContent(httpMethod)) {
     InputStream is = null;
     GZIPInputStream gzin = null;
     InputStreamReader isr = null;
     BufferedReader br = null;
     try {
       is = httpMethod.getResponseBodyAsStream();
       gzin = new GZIPInputStream(is);
       isr =
           new InputStreamReader(
               gzin,
               ((HttpMethodBase) httpMethod).getResponseCharSet()); // ���ö�ȡ���ı����ʽ���Զ������
       br = new BufferedReader(isr);
       char[] buffer = new char[4096];
       int readlen = -1;
       while ((readlen = br.read(buffer, 0, 4096)) != -1) {
         contentBuilder.append(buffer, 0, readlen);
       }
     } catch (Exception e) {
       log.error("Unzip fail", e);
     } finally {
       try {
         br.close();
       } catch (Exception e1) {
         // ignore
       }
       try {
         isr.close();
       } catch (Exception e1) {
         // ignore
       }
       try {
         gzin.close();
       } catch (Exception e1) {
         // ignore
       }
       try {
         is.close();
       } catch (Exception e1) {
         // ignore
       }
     }
   } else {
     String content = null;
     try {
       content = httpMethod.getResponseBodyAsString();
     } catch (Exception e) {
       log.error("Fetch config error:", e);
     }
     if (null == content) {
       return null;
     }
     contentBuilder.append(content);
   }
   return contentBuilder.toString();
 }
 void copyProxyReponse(HttpMethod proxyResponse, HttpServletResponse response) throws IOException {
   copyProxyHeaders(proxyResponse.getResponseHeaders(), response);
   response.setContentLength(getResponseContentLength(proxyResponse));
   copy(proxyResponse.getResponseBodyAsStream(), response.getOutputStream());
   if (proxyResponse.getStatusLine() != null) {
     int statCode = proxyResponse.getStatusCode();
     response.setStatus(statCode);
   }
 }
 private void checkVersion() throws Exception {
   HttpMethod method = doREST("/rest/workflow/version", false);
   InputStream stream = method.getResponseBodyAsStream();
   Element element = new SAXBuilder(false).build(stream).getRootElement();
   final boolean timeTrackingAvailable =
       element.getName().equals("version")
           && VersionComparatorUtil.compare(element.getChildText("version"), "4.1") >= 0;
   if (!timeTrackingAvailable) {
     throw new Exception("This version of Youtrack the time tracking is not supported");
   }
 }
  private String post(final HttpMethod method) throws IOException, ForbiddenException {
    method.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
    method.setRequestHeader("Accept-Encoding", "gzip");
    InputStream is = null;
    try {
      this.m_clientManager.executeMethod(method);
      final int statusCode = method.getStatusCode();
      final StatusLine statusLine = method.getStatusLine();
      final Header encoding = method.getResponseHeader("Content-Encoding");
      if (encoding != null && encoding.getValue().equals("gzip")) {
        m_log.debug("Unzipping body...");
        is = new GZIPInputStream(method.getResponseBodyAsStream());
      } else {
        is = method.getResponseBodyAsStream();
      }
      final String body = IOUtils.toString(is);
      if (StringUtils.isBlank(body)) {
        // Could easily be a post request, which would not have a body.
        m_log.debug("No response body.  Post request?");
      }
      if (statusCode == HttpStatus.SC_FORBIDDEN) {
        final String msg = "NO 200 OK: " + method.getURI() + "\n" + statusLine + "\n" + body;
        m_log.warn(msg);
        throw new ForbiddenException(msg);
      }

      if (statusCode != HttpStatus.SC_OK) {

        final String msg = "NO 200 OK: " + method.getURI() + "\n" + statusLine + "\n" + body;
        m_log.warn(msg);
        throw new IOException(msg);
      } else {
        m_log.debug("Got 200 response...");
      }

      return body;
    } finally {
      IOUtils.closeQuietly(is);
      method.releaseConnection();
    }
  }
 private String read(HttpMethod method, int responseCode) {
   try {
     StringWriter stringWriter = new StringWriter();
     IOUtils.copy(method.getResponseBodyAsStream(), stringWriter, "UTF-8");
     if (responseCode != HttpStatus.SC_OK) {
       throw new RuntimeException(method.getResponseBodyAsString());
     }
     return stringWriter.toString();
   } catch (Exception e) {
     throw new RuntimeException(e);
   }
 }
  public Task[] getIssues(@Nullable String request, int max, long since) throws Exception {

    String query = getDefaultSearch();
    if (request != null) {
      query += " " + request;
    }
    String requestUrl =
        "/rest/project/issues/?filter="
            + encodeUrl(query)
            + "&max="
            + max
            + "&updatedAfter"
            + since;
    HttpMethod method = doREST(requestUrl, false);
    InputStream stream = method.getResponseBodyAsStream();

    // todo workaround for http://youtrack.jetbrains.net/issue/JT-7984
    String s = StreamUtil.readText(stream, "UTF-8");
    for (int i = 0; i < s.length(); i++) {
      if (!XMLChar.isValid(s.charAt(i))) {
        s = s.replace(s.charAt(i), ' ');
      }
    }

    Element element;
    try {
      // InputSource source = new InputSource(stream);
      // source.setEncoding("UTF-8");
      // element = new SAXBuilder(false).build(source).getRootElement();
      element = new SAXBuilder(false).build(new StringReader(s)).getRootElement();
    } catch (JDOMException e) {
      LOG.error("Can't parse YouTrack response for " + requestUrl, e);
      throw e;
    }
    if ("error".equals(element.getName())) {
      throw new Exception(
          "Error from YouTrack for " + requestUrl + ": '" + element.getText() + "'");
    }

    List<Element> children = element.getChildren("issue");

    final List<Task> tasks =
        ContainerUtil.mapNotNull(
            children,
            new NullableFunction<Element, Task>() {
              public Task fun(Element o) {
                return createIssue(o);
              }
            });
    return tasks.toArray(new Task[tasks.size()]);
  }
  /**
   * Get file from URL, directories are created and files overwritten.
   *
   * @deprecated use org.apache.commons.io.FileUtils.copyURLToFile(URL, File)
   * @param requestUrl
   * @param outputPathAndFileName
   * @return int request status code OR -1 if an exception occurred
   */
  public static int getToFile(String requestUrl, String outputPathAndFileName) {
    int resultStatus = -1;

    File outputFile = new File(outputPathAndFileName);
    String outputPath = outputFile.getAbsolutePath().replace(outputFile.getName(), "");
    File outputDir = new File(outputPath);
    if (!outputDir.exists()) {
      outputDir.mkdir();
    }

    HttpClient client = new HttpClient();

    //	client.getState().setCredentials(
    //			new AuthScope("localhost", 7080, null ),
    //			new UsernamePasswordCredentials("nation", "nationPW")
    //     );
    //	client.getParams().setAuthenticationPreemptive(true);

    HttpMethod method = new GetMethod(requestUrl);

    //	method.setDoAuthentication( true );
    //  client.getParams().setAuthenticationPreemptive(true);

    // Execute and print response
    try {

      OutputStream os = new FileOutputStream(outputFile);

      client.executeMethod(method);
      InputStream is = method.getResponseBodyAsStream();
      BufferedInputStream bis = new BufferedInputStream(is);

      byte[] bytes = new byte[8192]; // reading as chunk of 8192 bytes
      int count = bis.read(bytes);
      while (count != -1 && count <= 8192) {
        os.write(bytes, 0, count);
        count = bis.read(bytes);
      }
      bis.close();
      os.close();
      resultStatus = method.getStatusCode();

    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      method.releaseConnection();
    }

    return resultStatus;
  }
Beispiel #17
0
  protected <T> void processOnResponses(HttpMethod httpMethod, HttpInvocation<T> httpInvocation)
      throws Exception {
    int statusCode = httpMethod.getStatusCode();
    httpInvocation.onResponseStatus(statusCode);

    Header[] responseHeaders = httpMethod.getResponseHeaders();
    if (ArrayUtils.isNotEmpty(responseHeaders)) {
      for (Header header : responseHeaders) {
        httpInvocation.onResponseHeader(header.getName(), header.getValue());
      }
    }

    httpInvocation.onResponseBody(httpMethod.getResponseBodyAsStream());
  }
  /**
   * @throws RuleOracleUnavailableException
   * @see RuleDao#getRuleTree(String)
   */
  public RuleSet getRuleTree(String surt) throws RuleOracleUnavailableException {
    HttpMethod method = new GetMethod(oracleUrl + "/rules/tree/" + surt);
    RuleSet rules;

    try {
      http.executeMethod(method);
      String response = method.getResponseBodyAsString();
      System.out.println(response);
      rules = (RuleSet) xstream.fromXML(method.getResponseBodyAsStream());
    } catch (IOException e) {
      throw new RuleOracleUnavailableException(e);
    }
    method.releaseConnection();
    return rules;
  }
 public HttpInputStream(HttpClient client, HttpMethod method, String url) throws IOException {
   m_client = client;
   m_method = method;
   m_url = url;
   try {
     m_code = m_client.executeMethod(m_method);
     m_in = m_method.getResponseBodyAsStream();
     if (m_in == null) {
       m_in = new ByteArrayInputStream(new byte[0]);
     }
   } catch (IOException e) {
     m_method.releaseConnection();
     throw e;
   }
 }
 HttpMethod doREST(String request, boolean post) throws Exception {
   HttpClient client = login(new PostMethod(getUrl() + "/rest/user/login"));
   String uri = getUrl() + request;
   HttpMethod method = post ? new PostMethod(uri) : new GetMethod(uri);
   configureHttpMethod(method);
   int status = client.executeMethod(method);
   if (status == 400) {
     InputStream string = method.getResponseBodyAsStream();
     Element element = new SAXBuilder(false).build(string).getRootElement();
     if ("error".equals(element.getName())) {
       throw new Exception(element.getText());
     }
   }
   return method;
 }
  public String getTinyUrl(String fullUrl) throws HttpException, IOException {
    HttpClient httpclient = new HttpClient();
    HttpMethod method = new GetMethod("http://tinyurl.com/api-create.php");
    method.setQueryString(new NameValuePair[] {new NameValuePair("url", fullUrl)});
    httpclient.executeMethod(method);

    InputStream is = method.getResponseBodyAsStream();
    StringBuilder sb = new StringBuilder();
    for (int i = is.read(); i != -1; i = is.read()) {
      sb.append((char) i);
    }
    String tinyUrl = sb.toString();
    method.releaseConnection();

    log.info("Successfully shortened URL " + fullUrl + " via tinyurl to " + tinyUrl + ".");
    return tinyUrl;
  }
 @NotNull
 public String executeMethod(@NotNull HttpMethod method) throws Exception {
   LOG.debug("URI: " + method.getURI());
   int statusCode;
   String entityContent;
   try {
     statusCode = getHttpClient().executeMethod(method);
     LOG.debug("Status code: " + statusCode);
     // may be null if 204 No Content received
     final InputStream stream = method.getResponseBodyAsStream();
     entityContent = stream == null ? "" : StreamUtil.readText(stream, CharsetToolkit.UTF8);
     LOG.debug(entityContent);
   } finally {
     method.releaseConnection();
   }
   // besides SC_OK, can also be SC_NO_CONTENT in issue transition requests
   // see: JiraRestApi#setTaskStatus
   // if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_NO_CONTENT) {
   if (statusCode >= 200 && statusCode < 300) {
     return entityContent;
   } else if (method.getResponseHeader("Content-Type") != null) {
     Header header = method.getResponseHeader("Content-Type");
     if (header.getValue().startsWith("application/json")) {
       JsonObject object = GSON.fromJson(entityContent, JsonObject.class);
       if (object.has("errorMessages")) {
         String reason = StringUtil.join(object.getAsJsonArray("errorMessages"), " ");
         // something meaningful to user, e.g. invalid field name in JQL query
         LOG.warn(reason);
         throw new Exception("Request failed. Reason: " + reason);
       }
     }
   }
   if (method.getResponseHeader("X-Authentication-Denied-Reason") != null) {
     Header header = method.getResponseHeader("X-Authentication-Denied-Reason");
     // only in JIRA >= 5.x.x
     if (header.getValue().startsWith("CAPTCHA_CHALLENGE")) {
       throw new Exception("Login failed. Enter captcha in web-interface.");
     }
   }
   if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
     throw new Exception(LOGIN_FAILED_CHECK_YOUR_PERMISSIONS);
   }
   String statusText = HttpStatus.getStatusText(method.getStatusCode());
   throw new Exception(
       String.format("Request failed with HTTP error: %d %s", statusCode, statusText));
 }
 private HttpResponse getHttpResult(HttpMethod method, int retry)
     throws ConnectException, HttpHelperException {
   HttpResponse httpResponse = new HttpResponse();
   this.initMethod(method, retry);
   InputStream is = null;
   BufferedReader reader = null;
   HttpClient client = createHttpClient();
   try {
     client.executeMethod(method);
   } catch (HttpException e1) {
     throw new ConnectException(e1);
   } catch (IOException e1) {
     throw new HttpHelperException(e1);
   }
   try {
     is = method.getResponseBodyAsStream();
     reader = new BufferedReader(new InputStreamReader(is, "utf-8"));
     StringBuilder sb = new StringBuilder();
     char[] ch = new char[3096];
     while (reader.read(ch) != -1) {
       sb.append(ch);
     }
     httpResponse.setStatusCode(method.getStatusCode());
     httpResponse.setStatusText(method.getStatusText());
     httpResponse.setResponseText(sb.toString());
     return httpResponse;
   } catch (Exception e) {
     throw new HttpHelperException(e);
   } finally {
     method.releaseConnection();
     try {
       if (reader != null) {
         reader.close();
       }
     } catch (IOException e) {
       throw new HttpHelperException(e);
     }
     try {
       if (is != null) {
         is.close();
       }
     } catch (IOException e) {
       throw new HttpHelperException(e);
     }
   }
 }
  /*
   * (non-Javadoc)
   * @see org.jasig.portlet.weather.dao.IWeatherDao#find(java.lang.String)
   */
  public Collection<Location> find(String location) {
    final String url =
        FIND_URL
            .replace("@KEY@", key)
            .replace("@QUERY@", QuietUrlCodec.encode(location, Constants.URL_ENCODING));

    HttpMethod getMethod = new GetMethod(url);
    InputStream inputStream = null;
    try {
      // Execute the method.
      int statusCode = httpClient.executeMethod(getMethod);
      if (statusCode != HttpStatus.SC_OK) {
        final String statusText = getMethod.getStatusText();
        throw new DataRetrievalFailureException(
            "get of '"
                + url
                + "' failed with status '"
                + statusCode
                + "' due to '"
                + statusText
                + "'");
      }

      // Read the response body
      inputStream = getMethod.getResponseBodyAsStream();

      List<Location> locations = deserializeSearchResults(inputStream);

      return locations;

    } catch (HttpException e) {
      throw new RuntimeException(
          "http protocol exception while getting data from weather service from: " + url, e);
    } catch (IOException e) {
      throw new RuntimeException(
          "IO exception while getting data from weather service from: " + url, e);
    } catch (JAXBException e) {
      throw new RuntimeException(
          "Parsing exception while getting data from weather service from: " + url, e);
    } finally {
      // try to close the inputstream
      IOUtils.closeQuietly(inputStream);
      // release the connection
      getMethod.releaseConnection();
    }
  }
  protected Object getAndDeserialize(String url, TemperatureUnit unit) {
    HttpMethod getMethod = new GetMethod(url);
    InputStream inputStream = null;
    try {
      // Execute the method.
      int statusCode = httpClient.executeMethod(getMethod);
      if (statusCode != HttpStatus.SC_OK) {
        final String statusText = getMethod.getStatusText();
        throw new DataRetrievalFailureException(
            "get of '"
                + url
                + "' failed with status '"
                + statusCode
                + "' due to '"
                + statusText
                + "'");
      }

      // Read the response body
      inputStream = getMethod.getResponseBodyAsStream();

      Weather weather = deserializeWeatherResult(inputStream, unit);

      return weather;

    } catch (HttpException e) {
      throw new RuntimeException(
          "http protocol exception while getting data from weather service from: " + url, e);
    } catch (IOException e) {
      throw new RuntimeException(
          "IO exception while getting data from weather service from: " + url, e);
    } catch (JAXBException e) {
      throw new RuntimeException(
          "Parsing exception while getting data from weather service from: " + url, e);
    } catch (ParseException e) {
      throw new RuntimeException(
          "Parsing exception while getting data from weather service from: " + url, e);
    } finally {
      // try to close the inputstream
      IOUtils.closeQuietly(inputStream);
      // release the connection
      getMethod.releaseConnection();
    }
  }
Beispiel #26
0
  private Result excuteMethod(HttpMethod method, String cookie, Map<String, String> headers) {
    Result result = new Result();
    result.setSuccess(true);
    int responseCode = -1;
    try {
      // String cookie =
      // "240=240; CurLoginUserGUID=a44e6f49751b4d8b9659636ae20540d6;
      // strCertificate=410df02a24354be8bb194aeec0829589;";
      if (cookie != null) {
        method.addRequestHeader("Cookie", cookie);
      }
      if (headers != null) {
        for (Entry<String, String> entry : headers.entrySet()) {
          method.addRequestHeader(entry.getKey(), entry.getValue());
        }
      }
      method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, httpRequestRetryHandler);
      org.apache.commons.httpclient.HttpClient client = this.createHttpClient();
      client.executeMethod(method);
      responseCode = method.getStatusCode();
      if (responseCode != HttpStatus.SC_OK) {
        result.setSuccess(false);
        result.setErrorCode(ErrorCodeEnum.NOT_FOUND_ERROR);
        result.setMessage("responseCode:" + responseCode);
        result.setResponseCode(responseCode);
      }
      InputStream is = method.getResponseBodyAsStream();
      try {
        result.setResultBytes(IOUtils.toByteArray(is));
      } finally {
        IOUtils.closeQuietly(is);
      }

    } catch (Exception e) {
      result.setSuccess(false);
      result.setErrorCode(ErrorCodeEnum.SYSTEM_ERROR);
      result.setMessage(e.getMessage());
      result.setCause(e);
    } finally {
      result.setMethodStatusCode(method.getStatusCode());
      method.releaseConnection();
    }
    return result;
  }
 @Override
 public void updateTimeSpent(final LocalTask task, final String timeSpent, final String comment)
     throws Exception {
   checkVersion();
   final HttpMethod method =
       doREST(
           "/rest/issue/execute/"
               + task.getId()
               + "?command=work+Today+"
               + timeSpent.replaceAll(" ", "+")
               + "+"
               + comment,
           true);
   if (method.getStatusCode() != 200) {
     InputStream stream = method.getResponseBodyAsStream();
     String message = new SAXBuilder(false).build(stream).getRootElement().getText();
     throw new Exception(message);
   }
 }
  /**
   * Extract JSON-object from the method's response.
   *
   * @param method the method containing the response
   * @return the json object. Returns null if response is not JSON or no data-object is present.
   */
  public static JSONObject getObjectFromResponse(HttpMethod method) {
    JSONObject result = null;

    try {
      InputStream response = method.getResponseBodyAsStream();
      if (response != null) {
        Object object =
            new JSONParser().parse(new InputStreamReader(response, Charset.forName("UTF-8")));
        if (object instanceof JSONObject) {
          return (JSONObject) object;
        }
      }
    } catch (IOException error) {
      // Ignore errors, returning null
    } catch (ParseException error) {
      // Ignore errors, returning null
    }

    return result;
  }
Beispiel #29
0
  /**
   * 주어진 url의 응답 결과를 얻는다.
   *
   * @param url
   * @param params
   * @return HttpResult
   */
  protected HttpResult getHttp(String url, Map<String, String> params) {

    HttpResult result = new HttpResult();

    HttpClient client = getHttpClient();
    HttpMethod method = new GetMethod(url);

    if (params != null) {
      HttpMethodParams param = new HttpMethodParams();

      for (String key : params.keySet()) {
        param.setParameter(key, params.get(key));
      }

      method.setParams(param);
    }

    try {
      int statusCode = client.executeMethod(method);
      result.setStatusCode(statusCode);

      if (statusCode == HttpStatus.SC_OK) {
        // 동적페이지의 경우 last-modified 는 없음.
        InputStream bodyAsStream = method.getResponseBodyAsStream();
        StringBuilder sb = new StringBuilder();
        byte[] b = new byte[1024];
        for (int n; (n = bodyAsStream.read(b)) != -1; ) {
          sb.append(new String(b, 0, n, this.getEnconding()));
        }
        result.setContent(sb.toString());
      }

    } catch (Exception e) {

      logger.error(e.getMessage(), e);
    }

    return result;
  }
  /**
   * Appends response form URL to a StringBuffer
   *
   * @param requestUrl
   * @param resultStringBuffer
   * @return int request status code OR -1 if an exception occurred
   */
  public static int getAsString(String requestUrl, StringBuffer resultStringBuffer) {
    HttpClient client = new HttpClient();

    //	client.getState().setCredentials(
    //			new AuthScope("localhost", 7080, null ),
    //			new UsernamePasswordCredentials("nation", "nationPW")
    //     );
    //	client.getParams().setAuthenticationPreemptive(true);

    HttpMethod method = new GetMethod(requestUrl);

    // method.setDoAuthentication( true );
    // client.getParams().setAuthenticationPreemptive(true);

    // Execute and print response
    try {
      client.executeMethod(method);
      InputStream is = method.getResponseBodyAsStream();
      BufferedInputStream bis = new BufferedInputStream(is);

      String datastr = null;
      byte[] bytes = new byte[8192]; // reading as chunk of 8192 bytes
      int count = bis.read(bytes);
      while (count != -1 && count <= 8192) {
        datastr = new String(bytes, 0, count);
        resultStringBuffer.append(datastr);
        count = bis.read(bytes);
      }
      bis.close();

    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      method.releaseConnection();
    }

    return method.getStatusCode();
  }