コード例 #1
0
ファイル: RESTWorkItemHandler.java プロジェクト: sazonov/jbpm
  public void executeWorkItem(WorkItem workItem, WorkItemManager manager) {
    // extract required parameters
    String urlStr = (String) workItem.getParameter("Url");
    String method = (String) workItem.getParameter("Method");
    if (urlStr == null) {
      throw new IllegalArgumentException("Url is a required parameter");
    }
    if (method == null || method.trim().length() == 0) {
      method = "GET";
    }
    Map<String, Object> params = workItem.getParameters();

    // optional timeout config parameters, defaulted to 60 seconds
    Integer connectTimeout = (Integer) params.get("ConnectTimeout");
    if (connectTimeout == null) connectTimeout = 60000;
    Integer readTimeout = (Integer) params.get("ReadTimeout");
    if (readTimeout == null) readTimeout = 60000;

    HttpClient httpclient = new HttpClient();
    httpclient.setConnectionTimeout(connectTimeout);
    httpclient.setTimeout(readTimeout);

    HttpMethod theMethod = null;
    if ("GET".equals(method)) {
      theMethod = new GetMethod(urlStr);
    } else if ("POST".equals(method)) {
      theMethod = new PostMethod(urlStr);
    }
    doAuthorization(httpclient, theMethod, params);
    try {
      int responseCode = httpclient.executeMethod(theMethod);
      Map<String, Object> results = new HashMap<String, Object>();
      if (responseCode >= 200 && responseCode < 300) {
        theMethod.getResponseBody();
        postProcessResult(theMethod.getResponseBodyAsString(), results);
      } else {
        results.put("Status", responseCode);
        results.put(
            "StatusMsg",
            "endpoint " + urlStr + " could not be reached: " + theMethod.getResponseBodyAsString());
      }
      // notify manager that work item has been completed
      manager.completeWorkItem(workItem.getId(), results);
    } catch (Exception e) {
      e.printStackTrace();
      manager.abortWorkItem(workItem.getId());
    } finally {
      theMethod.releaseConnection();
    }
  }
コード例 #2
0
ファイル: HttpUtil.java プロジェクト: yangjinbo47/flux
  /**
   * 发送http请求,并返回响应的xml报文 <功能详细描述>
   *
   * @param url http请求url
   * @param xml 请求xml报文
   * @return
   */
  private String send(HttpMethod httpMethod) {
    // 获取响应报文
    String response = null;
    int resultCode = HttpStatus.SC_OK;
    try {
      // 设置header信息,传输XML格式的
      httpMethod.setRequestHeader(CONTENT_TYPE_NAME, CONTENT_TYPE_VALUE_XML_UTF_8);

      // 处理响应结果码
      resultCode = httpClient.executeMethod(httpMethod);
      if (HttpStatus.SC_OK == resultCode) {
        byte[] resBody = httpMethod.getResponseBody();
        if (null != resBody && resBody.length > 0) {
          response = new String(resBody, UTF_8);
        }
      } else {
        response = resultCode + "";
        LogUtil.error("Http response: " + httpMethod.getResponseBodyAsString());
      }
    } catch (Exception ex) {
      response = ex.toString();
      LogUtil.error("send http request error!", ex);
    } finally {
      if (null != httpMethod) {
        httpMethod.releaseConnection();
      }
    }
    return response;
  }
コード例 #3
0
ファイル: Pownce.java プロジェクト: pstallworth/javapownce
  public void execute() {

    client = new HttpClient();
    //		if (requestType.equals("GET")) {
    // Instantiate a GET HTTP method
    //	        HttpMethod method = new GetMethod(apiUrl);

    //	        if (!authentication.equals("")) {
    //	        	method.setRequestHeader("Authorization", "basic " + authentication);
    //	        }
    try {

      int statusCode = client.executeMethod(method);

      System.out.println("QueryString>>> " + apiUrl);
      System.out.println("Status Text>>>" + HttpStatus.getStatusText(statusCode));

      // Get data as a String
      System.out.println(method.getResponseBodyAsString());

      // OR as a byte array
      byte[] res = method.getResponseBody();

      // write to file
      FileOutputStream fos = new FileOutputStream("donepage.html");
      fos.write(res);

      // release connection
      method.releaseConnection();
    } catch (IOException e) {
      e.printStackTrace();
    }
    // }
  }
コード例 #4
0
  @Test
  public void testServletAsAnonymous() throws Exception {

    HttpClient httpClient = new HttpClient();

    HttpMethod getMethod = null;
    try {
      // ------------ Test anonymous user not allowed ----------------
      getMethod =
          new GetMethod(
              "http://localhost:18080/authentication/token?applicationName=myFavoriteApp&deviceId=dead-beaf-cafe-babe&permission=rw");
      int status = httpClient.executeMethod(getMethod);
      assertEquals(401, status);

      // ------------ Test anonymous user allowed ----------------
      harness.deployContrib(
          "org.nuxeo.ecm.platform.login.token.test",
          "OSGI-INF/test-token-authentication-allow-anonymous-token-contrib.xml");

      status = httpClient.executeMethod(getMethod);
      assertEquals(201, status);
      String token = getMethod.getResponseBodyAsString();
      assertNotNull(token);
      assertNotNull(tokenAuthenticationService.getUserName(token));
      assertEquals(1, tokenAuthenticationService.getTokenBindings("Guest").size());

      harness.undeployContrib(
          "org.nuxeo.ecm.platform.login.token.test",
          "OSGI-INF/test-token-authentication-allow-anonymous-token-contrib.xml");
    } finally {
      getMethod.releaseConnection();
    }
  }
コード例 #5
0
  public Object doTransform(Object src, String encoding) throws TransformerException {
    Object msg;
    HttpMethod httpMethod = (HttpMethod) src;
    Header contentType = httpMethod.getResponseHeader(HttpConstants.HEADER_CONTENT_TYPE);
    try {
      if (contentType != null && !contentType.getValue().startsWith("text/")) {
        msg = httpMethod.getResponseBody();
      } else {
        msg = httpMethod.getResponseBodyAsString();
      }
    } catch (IOException e) {
      throw new TransformerException(this, e);
    }
    // Standard headers
    Map headerProps = new HashMap();
    Header[] headers = httpMethod.getRequestHeaders();
    String name;
    for (int i = 0; i < headers.length; i++) {
      name = headers[i].getName();
      if (name.startsWith("X-" + MuleProperties.PROPERTY_PREFIX)) {
        name = name.substring(2);
      }
      headerProps.put(headers[i].getName(), headers[i].getValue());
    }
    // Set Mule Properties

    return new MuleMessage(msg, headerProps);
  }
コード例 #6
0
  public void test_getContentsFolder() {

    try {
      Thread.sleep(2000);
    } catch (InterruptedException e1) {

      e1.printStackTrace();
    }

    // Get the content
    HttpMethod get_col_contents =
        new GetMethod(
            SLING_URL + COLLECTION_URL + slug + "/" + CONTENTS_FOLDER + "/" + "sling:resourceType");
    try {
      client.executeMethod(get_col_contents);
    } catch (HttpException e) {

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

      e.printStackTrace();
    }
    // handle response.
    String response_body = "";
    try {
      response_body = get_col_contents.getResponseBodyAsString();
    } catch (IOException e) {

      e.printStackTrace();
    }

    assertEquals(response_body, CONTENTS_RESOURCE_TYPE);
  }
コード例 #7
0
  public void test_getTagsFolder() {

    try {
      Thread.sleep(2000);
    } catch (InterruptedException e1) {

      e1.printStackTrace();
    }

    String response_body = "";
    HttpMethod get_col_tags =
        new GetMethod(
            SLING_URL + COLLECTION_URL + slug + "/" + TAGS_FOLDER + "/" + "sling:resourceType");
    try {
      client.executeMethod(get_col_tags);
    } catch (HttpException e) {

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

      e.printStackTrace();
    }

    try {
      response_body = get_col_tags.getResponseBodyAsString();
    } catch (IOException e) {

      e.printStackTrace();
    }

    assertEquals(response_body, TAGS_RESOURCE_TYPE);
    get_col_tags.releaseConnection();
  }
コード例 #8
0
  public static String getTinyUrl(String fullUrl) {
    HttpClient httpclient = new HttpClient();
    httpclient.setConnectionTimeout(TIMEOUT);
    httpclient.setTimeout(TIMEOUT);
    HttpMethod method = new GetMethod("http://tinyurl.com/api-create.php");
    method.setQueryString(new NameValuePair[] {new NameValuePair("url", fullUrl)});
    String tinyUrl = fullUrl;

    try {
      httpclient.executeMethod(method);
      tinyUrl = method.getResponseBodyAsString();
      method.releaseConnection();
    } catch (HttpException e) {
      method.releaseConnection();
      // implement Liferay logging service
    } catch (IOException e) {
      method.releaseConnection();
      // implement Liferay logging service
    } catch (Exception e) {
      method.releaseConnection();
      // implement Liferay logging service
    }

    return tinyUrl;
  }
コード例 #9
0
 @Nullable
 private static JsonElement request(
     @NotNull String host,
     @Nullable String login,
     @Nullable String password,
     @NotNull String path,
     @Nullable String requestBody,
     boolean post) {
   HttpMethod method = null;
   try {
     method = doREST(host, login, password, path, requestBody, post);
     String resp = method.getResponseBodyAsString();
     if (method.getStatusCode() != 200) {
       String message =
           String.format(
               "Request not successful. Status-Code: %s, Message: %s.",
               method.getStatusCode(), method.getStatusText());
       LOG.warn(message);
       throw new HttpStatusException(method.getStatusCode(), method.getStatusText(), message);
     }
     if (resp == null) {
       String message = String.format("Unexpectedly empty response: %s.", resp);
       LOG.warn(message);
       throw new RuntimeException(message);
     }
     return parseResponse(resp);
   } catch (IOException e) {
     LOG.warn(String.format("Request failed: %s", e.getMessage()), e);
     throw Throwables.propagate(e);
   } finally {
     if (method != null) {
       method.releaseConnection();
     }
   }
 }
コード例 #10
0
  public Object deserializeUrl(String url) {

    HttpMethod httpMethod = new GetMethod(url);
    HttpClient httpClient = new HttpClient();
    int code = 0;
    int tries = 0;
    String stringResponse = null;
    try {
      code = httpClient.executeMethod(httpMethod);
      if (code < 200 || code >= 300) throw new IOException("a cow");

      stringResponse = httpMethod.getResponseBodyAsString();
    } catch (IOException ioEx) {
      Log.v(_tag, ioEx.toString());
      tries++;
    }
    httpMethod.releaseConnection();

    if (stringResponse == null) return null;
    int start = stringResponse.indexOf("File1=") + 6;
    if (start == -1) return null;
    stringResponse = stringResponse.substring(start, stringResponse.indexOf("\n", start));

    return stringResponse;
  }
コード例 #11
0
 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();
 }
コード例 #12
0
ファイル: CallUrl.java プロジェクト: jinhang/KeeWebFrame
 public static Msg<List<LatLng>> call(String staffid) {
   Msg<List<LatLng>> rmsg = new Msg<List<LatLng>>();
   List<LatLng> lls = new ArrayList();
   AroundLocation mrj = new AroundLocation();
   try {
     HttpClient hc = new HttpClient();
     //			String urlPath=Constants.HF_url;
     String urlPath = "http://yuntuapi.amap.com/datamanage/data/list?";
     urlPath += "tableid=558d1470e4b0b297165d1168";
     urlPath += "&filter=user_id:" + staffid;
     urlPath += "&sortrule=sequence:1";
     urlPath += "&key=" + Constants.EWP_SERVER_AK;
     //			urlPath +="&key=25284b478f1da94d318d0f7d8bd8af87";
     System.out.println(urlPath);
     HttpMethod method = new GetMethod(urlPath);
     hc.executeMethod(method);
     // 打印服务器返回的状态
     System.out.println(method.getStatusLine());
     // 打印返回的信息
     System.out.println(method.getResponseBodyAsString().replaceAll("_", "map"));
     // 释放连接
     method.releaseConnection();
     // 解析JSON
     mrj =
         JSON.parseObject(
             method.getResponseBodyAsString().replaceAll("_", "map"), AroundLocation.class);
     List<Datas> pjs = mrj.getDatas();
     if (pjs != null) {
       for (int i = 0; i < pjs.size(); i++) {
         String[] location = pjs.get(i).getMaplocation().split(",");
         lls.add(new LatLng(Double.valueOf(location[1]), Double.valueOf(location[0])));
       }
       rmsg.setResult(true);
       rmsg.setValue(lls);
     } else {
       rmsg.setResult(false);
     }
   } catch (Exception e) {
     e.printStackTrace();
     rmsg.setResult(false);
     return rmsg;
   }
   return rmsg;
 }
コード例 #13
0
  /**
   * Gets the result of the execution of a get request. the attempt will be repeated until obtain
   * the exepected result
   *
   * @param path the path on which the request should be executed
   * @param expression the result that should be returned by the GET request, which allows to know
   *     if that request is completely processed or not
   * @throws Exception if something's going wrong...
   */
  public void retryGetRequestUntilObtainExpectedResponse(
      @NonNull String path, @NonNull String expression) throws Exception {
    String fullpath = path;
    if (path.startsWith("/")) fullpath = baseUrl + path;
    log.debug("Sending GET request to " + fullpath + " with several attemps");

    final int maxAttempts = Integer.parseInt(ExecutionContext.get(RestConstants.MAX_ATTEMPTS_KEY));
    final int timeToWait = Integer.parseInt(ExecutionContext.get(RestConstants.TIME_TO_WAIT_KEY));

    final HttpMethod method = new GetMethod(fullpath);
    try {
      for (final Map.Entry<String, String> header : requestHeaders.entrySet())
        method.setRequestHeader(header.getKey(), header.getValue());

      String responseAsString = null;
      String toCheck = null;
      String expected = expression;
      String prop = null;
      final int idx = expression.indexOf("=");
      if (idx > 0) {
        prop = expression.substring(0, idx);
        expected = expression.substring(idx + 1);
      }
      int statusCode;
      int attempts = 0;
      boolean success = false;
      do {
        // waiting timeToWait seconds
        Thread.sleep(timeToWait * 1000);
        statusCode = httpClient.executeMethod(method);
        attempts++;
        if (statusCode == HttpStatus.SC_OK) {
          responseAsString = method.getResponseBodyAsString();
          toCheck = responseAsString;
          if (prop != null) toCheck = JSONHelper.getPropertyValue(responseAsString, prop);
          if (toCheck.contains(expected)) {
            success = true;
            log.debug("The result is available! ");
          } else
            log.warn("The result is not yet available! | Waiting " + timeToWait + " seconds ...");
        } else
          log.warn(
              "unsuccessful GET request : "
                  + method.getStatusLine()
                  + " | Waiting "
                  + timeToWait
                  + " seconds ...");
      } while (!success && maxAttempts > attempts);
      response = new ResponseWrapper(responseAsString, statusCode);
    } catch (final Exception e) {
      log.error(e.getMessage(), e);
      throw e;
    } finally {
      method.releaseConnection();
    }
  }
コード例 #14
0
  Set<String> getUpdateDataIdsInBody(HttpMethod httpMethod) {
    Set<String> modifiedDataIdSet = new HashSet<String>();
    try {
      String modifiedDataIdsString = httpMethod.getResponseBodyAsString();
      return convertStringToSet(modifiedDataIdsString);
    } catch (Exception e) {

    }
    return modifiedDataIdSet;
  }
コード例 #15
0
ファイル: CallUrl.java プロジェクト: jinhang/KeeWebFrame
 public static Msg<List<Datas>> callAround(String lat, String lng) {
   Msg<List<Datas>> rmsg = new Msg<List<Datas>>();
   List<LatLng> lls = new ArrayList();
   AroundLocation mrj = new AroundLocation();
   try {
     HttpClient hc = new HttpClient();
     //			String urlPath=Constants.HF_url;
     String urlPath = "http://yuntuapi.amap.com/datasearch/around?";
     urlPath += "tableid=558d1470e4b0b297165d1168";
     urlPath += "&sortrule=user_id:1";
     urlPath += "&center=" + lng + "," + lat;
     urlPath += "&radius=" + Constants.EWP_AROUND_RADIUS;
     //			urlPath +="&radius=5000";
     urlPath += "&key=" + Constants.EWP_SERVER_AK;
     //			urlPath +="&key=25284b478f1da94d318d0f7d8bd8af87";
     System.out.println(urlPath);
     HttpMethod method = new GetMethod(urlPath);
     hc.executeMethod(method);
     // 打印服务器返回的状态
     System.out.println(method.getStatusLine());
     // 打印返回的信息
     System.out.println(method.getResponseBodyAsString().replaceAll("_", "map"));
     // 释放连接
     method.releaseConnection();
     // 解析JSON
     mrj =
         JSON.parseObject(
             method.getResponseBodyAsString().replaceAll("_", "map"), AroundLocation.class);
     List<Datas> pjs = mrj.getDatas();
     if (pjs != null && pjs.size() > 0) {
       rmsg.setResult(true);
       rmsg.setValue(pjs);
     } else {
       rmsg.setResult(false);
     }
   } catch (Exception e) {
     e.printStackTrace();
     rmsg.setResult(false);
     return rmsg;
   }
   return rmsg;
 }
コード例 #16
0
ファイル: TextLink.java プロジェクト: gaddie-3/sn-kiosk
  private static String getTinyUrl(String fullUrl) throws HttpException, IOException {
    HttpClient httpclient = new HttpClient();

    // Prepare a request object
    HttpMethod method = new GetMethod("http://tinyurl.com/api-create.php");
    method.setQueryString(new NameValuePair[] {new NameValuePair("url", fullUrl)});
    httpclient.executeMethod(method);
    String tinyUrl = method.getResponseBodyAsString();
    method.releaseConnection();
    return tinyUrl;
  }
コード例 #17
0
 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);
   }
 }
コード例 #18
0
ファイル: HttpClient.java プロジェクト: Araell/prototype
  public Response httpRequest(HttpMethod method, Boolean WithTokenHeader, String token)
      throws WeiboException {
    InetAddress ipaddr;
    int responseCode = -1;
    try {
      ipaddr = InetAddress.getLocalHost();
      List<Header> headers = new ArrayList<Header>();
      if (WithTokenHeader) {
        if (token == null) {
          throw new IllegalStateException("Oauth2 token is not set!");
        }
        headers.add(new Header("Authorization", "OAuth2 " + token));
        headers.add(new Header("API-RemoteIP", ipaddr.getHostAddress()));
        client.getHostConfiguration().getParams().setParameter("http.default-headers", headers);
        for (Header hd : headers) {
          log(hd.getName() + ": " + hd.getValue());
        }
      }

      method
          .getParams()
          .setParameter(
              HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
      client.executeMethod(method);
      Header[] resHeader = method.getResponseHeaders();
      responseCode = method.getStatusCode();
      log("Response:");
      log("https StatusCode:" + String.valueOf(responseCode));

      for (Header header : resHeader) {
        log(header.getName() + ":" + header.getValue());
      }
      Response response = new Response();
      response.setResponseAsString(method.getResponseBodyAsString());
      log(response.toString() + "\n");

      if (responseCode != OK) {
        try {
          throw new WeiboException(
              getCause(responseCode), response.asJSONObject(), method.getStatusCode());
        } catch (JSONException e) {
          e.printStackTrace();
        }
      }
      return response;

    } catch (IOException ioe) {
      throw new WeiboException(ioe.getMessage(), ioe, responseCode);
    } finally {
      method.releaseConnection();
    }
  }
コード例 #19
0
  public static String get(String url) {
    HttpMethod method = new GetMethod(url);
    try {
      int returnCode = client.executeMethod(method);
      if ((returnCode >= 200) && (returnCode < 300)) {
        return method.getResponseBodyAsString();
      }
    } catch (HttpException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }

    return null;
  }
コード例 #20
0
  /**
   * @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;
  }
コード例 #21
0
  /**
   * Gets the result of the execution of a get request. the attempt will be repeated several times
   * in case of failures
   *
   * @param path the path on which the request should be sent
   * @throws Exception if something's going wrong...
   */
  public void retryGetRequestUntilSucceed(@NonNull String path) throws Exception {
    String fullpath = path;
    if (path.startsWith("/")) fullpath = baseUrl + path;

    log.debug("Sending GET request to " + fullpath + " with several attemps");

    final int maxAttempts = Integer.parseInt(ExecutionContext.get(RestConstants.MAX_ATTEMPTS_KEY));
    final int timeToWait = Integer.parseInt(ExecutionContext.get(RestConstants.TIME_TO_WAIT_KEY));

    final HttpMethod method = new GetMethod(fullpath);
    try {
      for (final Map.Entry<String, String> header : requestHeaders.entrySet())
        method.setRequestHeader(header.getKey(), header.getValue());

      String responseAsString = null;
      int statusCode;
      int attempts = 0;
      boolean success = false;
      do {
        // waiting timeToWait seconds
        Thread.sleep(timeToWait * 1000);
        statusCode = httpClient.executeMethod(method);
        attempts++;
        // check for status code 200
        if (statusCode == HttpStatus.SC_OK) {
          responseAsString = method.getResponseBodyAsString();
          success = true;
          log.info("The result is available! ");
        } else
          log.warn(
              "unsuccessful GET request : "
                  + method.getStatusLine()
                  + " | Waiting "
                  + timeToWait
                  + " seconds ...");
      } while (!success && maxAttempts > attempts);
      response = new ResponseWrapper(responseAsString, statusCode);
    } catch (final Exception e) {
      log.error(e.getMessage(), e);
      throw e;
    } finally {
      method.releaseConnection();
    }
  }
コード例 #22
0
ファイル: HttpUtils.java プロジェクト: tiansiyuan/misc
 /**
  * 提交
  *
  * @param method
  * @param token
  * @return
  * @throws ApiException
  */
 private static String httpRequest(HttpMethod method, String token) throws IOException {
   try {
     List<Header> headers = new ArrayList<Header>();
     if (token != null) {
       headers.add(new Header("Authorization", "Bearer " + token));
       client.getHostConfiguration().getParams().setParameter("http.default-headers", headers);
     }
     method
         .getParams()
         .setParameter(
             HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
     client.executeMethod(method);
     return method.getResponseBodyAsString();
   } catch (IOException ioe) {
     throw ioe;
   } finally {
     method.releaseConnection();
   }
 }
コード例 #23
0
  /**
   * Allows to send a GET request to the path passed using the http client
   *
   * @param path the path on which the request should be sent
   */
  public void sendGetRequest(final String path) throws Exception {
    String fullpath = path;
    if (path.startsWith("/")) fullpath = baseUrl + path;
    log.info("Sending GET request to " + fullpath);

    final HttpMethod method = new GetMethod(fullpath);
    try {
      for (final Map.Entry<String, String> header : requestHeaders.entrySet())
        method.setRequestHeader(header.getKey(), header.getValue());
      final int statusCode = httpClient.executeMethod(method);
      response =
          new ResponseWrapper(
              method.getResponseBodyAsString(), method.getResponseHeaders(), statusCode);
    } catch (final IOException e) {
      log.error(e.getMessage(), e);
      throw e;
    } finally {
      method.releaseConnection();
    }
  }
コード例 #24
0
ファイル: UserServiceImpl.java プロジェクト: demonshrimp/dawj
 @Override
 public User qqLogin(String accessToken) {
   User user = null;
   HttpClient httpClient = new HttpClient();
   HttpMethod method =
       new GetMethod("https://graph.qq.com/oauth2.0/me?access_token=" + accessToken);
   try {
     httpClient.executeMethod(method);
     String json = method.getResponseBodyAsString();
     json = json.replace("callback(", "").replace(");", "");
     JsonObject jsonObject = new Gson().fromJson(json, JsonObject.class);
     String openid = jsonObject.get("openid").getAsString();
     user = userDao.getByProperty("qqOpenId", openid);
     if (null != user) {
       user = loginHandle(user);
     }
   } catch (Exception e) {
     e.printStackTrace();
     throw new ServiceException(e.getMessage());
   }
   return user;
 }
コード例 #25
0
  /**
   * 执行Http请求
   *
   * @param request 请求数据
   * @param strParaFileName 文件类型的参数名
   * @param strFilePath 文件路径
   * @return
   * @throws HttpException, IOException
   */
  public HttpResponse execute(HttpRequest request, String strParaFileName, String strFilePath)
      throws HttpException, IOException {
    HttpClient httpclient = new HttpClient(connectionManager);

    // 设置连接超时
    int connectionTimeout = defaultConnectionTimeout;
    if (request.getConnectionTimeout() > 0) {
      connectionTimeout = request.getConnectionTimeout();
    }
    httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(connectionTimeout);

    // 设置回应超时
    int soTimeout = defaultSoTimeout;
    if (request.getTimeout() > 0) {
      soTimeout = request.getTimeout();
    }
    httpclient.getHttpConnectionManager().getParams().setSoTimeout(soTimeout);

    // 设置等待ConnectionManager释放connection的时间
    httpclient.getParams().setConnectionManagerTimeout(defaultHttpConnectionManagerTimeout);

    String charset = request.getCharset();
    charset = charset == null ? DEFAULT_CHARSET : charset;
    HttpMethod method = null;

    // get模式且不带上传文件
    if (request.getMethod().equals(HttpRequest.METHOD_GET)) {
      method = new GetMethod(request.getUrl());
      method.getParams().setCredentialCharset(charset);

      // parseNotifyConfig会保证使用GET方法时,request一定使用QueryString
      method.setQueryString(request.getQueryString());
    } else if (strParaFileName.equals("") && strFilePath.equals("")) {
      // post模式且不带上传文件
      method = new PostMethod(request.getUrl());
      ((PostMethod) method).addParameters(request.getParameters());
      method.addRequestHeader(
          "Content-Type", "application/x-www-form-urlencoded; text/html; charset=" + charset);
    } else {
      // post模式且带上传文件
      method = new PostMethod(request.getUrl());
      List<Part> parts = new ArrayList<Part>();
      for (int i = 0; i < request.getParameters().length; i++) {
        parts.add(
            new StringPart(
                request.getParameters()[i].getName(),
                request.getParameters()[i].getValue(),
                charset));
      }
      // 增加文件参数,strParaFileName是参数名,使用本地文件
      parts.add(new FilePart(strParaFileName, new FilePartSource(new File(strFilePath))));

      // 设置请求体
      ((PostMethod) method)
          .setRequestEntity(
              new MultipartRequestEntity(parts.toArray(new Part[0]), new HttpMethodParams()));
    }

    // 设置Http Header中的User-Agent属性
    method.addRequestHeader("User-Agent", "Mozilla/4.0");
    HttpResponse response = new HttpResponse();

    try {
      httpclient.executeMethod(method);
      if (request.getResultType().equals(HttpResultType.STRING)) {
        response.setStringResult(method.getResponseBodyAsString());
      } else if (request.getResultType().equals(HttpResultType.BYTES)) {
        response.setByteResult(method.getResponseBody());
      }
      response.setResponseHeaders(method.getResponseHeaders());
    } catch (UnknownHostException ex) {

      return null;
    } catch (IOException ex) {

      return null;
    } catch (Exception ex) {

      return null;
    } finally {
      method.releaseConnection();
    }
    return response;
  }
コード例 #26
0
  /**
   * 执行Http请求
   *
   * @param request
   * @return
   */
  public HttpResponse execute(HttpRequest request) {
    HttpClient httpclient = new HttpClient(connectionManager);

    // 设置连接超时
    int connectionTimeout = defaultConnectionTimeout;
    if (request.getConnectionTimeout() > 0) {
      connectionTimeout = request.getConnectionTimeout();
    }
    httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(connectionTimeout);

    // 设置回应超时
    int soTimeout = defaultSoTimeout;
    if (request.getTimeout() > 0) {
      soTimeout = request.getTimeout();
    }
    httpclient.getHttpConnectionManager().getParams().setSoTimeout(soTimeout);

    // 设置等待ConnectionManager释放connection的时间
    httpclient.getParams().setConnectionManagerTimeout(defaultHttpConnectionManagerTimeout);

    String charset = request.getCharset();
    charset = charset == null ? DEFAULT_CHARSET : charset;
    HttpMethod method = null;

    if (request.getMethod().equals(HttpRequest.METHOD_GET)) {
      method = new GetMethod(request.getUrl());
      method.getParams().setCredentialCharset(charset);

      // parseNotifyConfig会保证使用GET方法时,request一定使用QueryString
      method.setQueryString(request.getQueryString());
    } else {
      method = new PostMethod(request.getUrl());
      ((PostMethod) method).addParameters(request.getParameters());
      method.addRequestHeader(
          "Content-Type", "application/x-www-form-urlencoded; text/html; charset=" + charset);
    }

    // 设置Http Header中的User-Agent属性
    method.addRequestHeader("User-Agent", "Mozilla/4.0");
    HttpResponse response = new HttpResponse();

    try {
      httpclient.executeMethod(method);
      if (request.getResultType().equals(HttpResultType.STRING)) {
        response.setStringResult(method.getResponseBodyAsString());
      } else if (request.getResultType().equals(HttpResultType.BYTES)) {
        response.setByteResult(method.getResponseBody());
      }
      response.setResponseHeaders(method.getResponseHeaders());
    } catch (UnknownHostException ex) {

      return null;
    } catch (IOException ex) {

      return null;
    } catch (Exception ex) {

      return null;
    } finally {
      method.releaseConnection();
    }
    return response;
  }
コード例 #27
0
ファイル: HttpNetAgent.java プロジェクト: onevs108/dashbd
  private String send(HttpMethod method, boolean sslExceptionIgnore) throws HttpNetAgentException {
    String responseBody = null;
    HttpClient hc = null;

    try {
      this.hashCode();
      String reqLog =
          ">> " + (method instanceof PostMethod ? "POST" : "GET") + " [" + method.getURI() + "]";

      if (method instanceof PostMethod) {
        NameValuePair[] params = ((PostMethod) method).getParameters();
        for (int i = 0; i < params.length; i++) {
          NameValuePair param = params[i];
          reqLog += "\n" + (param.getName() + "=" + param.getValue());
        }
      }
      reqLog +=
          ", hscd["
              + this.hashCode()
              + "], sslExcIgnore["
              + sslExceptionIgnore
              + "], hs["
              + this.hashCode()
              + "]";

      logger.info(reqLog);
      logger.info(getHttpInfoDumy(method));

      HttpConnectionManager httpConnMgr = new SimpleHttpConnectionManager();
      HttpConnectionManagerParams httpConnMgrParams = new HttpConnectionManagerParams();

      // Connection Timeout 설정
      httpConnMgrParams.setConnectionTimeout(netTimeoutConn);

      // Socket Timeout 설정
      httpConnMgrParams.setSoTimeout(netTimeoutSock);
      httpConnMgr.setParams(httpConnMgrParams);

      hc = new HttpClient(httpConnMgr);
      /*
      if (sslExceptionIgnore){
      	try {
      		Protocol.registerProtocol("https", new Protocol("https", new EasySSLProtocolSocketFactory(), 443));
      	} catch (GeneralSecurityException e) {
      		e.printStackTrace();
      	}
      }
      */

      int status = hc.executeMethod(method);

      if (200 == status) {
        responseBody = method.getResponseBodyAsString();
        logger.info("<< responseBody [" + responseBody + "], hs[" + this.hashCode() + "]");
        if (responseBody == null) responseBody = "";

      } else {
        logger.error(
            "<< http status Not Success ["
                + status
                + "], hs["
                + this.hashCode()
                + "],"
                + getHttpInfoDumy(method));
        throw new HttpNetAgentException(
            HttpNetAgentException.HTTP_HAEDER_NOT_SUCCESS, "Http Status[" + status + "]");
      }

    } catch (HttpException e) {
      logger.error(
          "<< HttpException msg ["
              + e.getMessage()
              + "], hs["
              + this.hashCode()
              + "],"
              + getHttpInfoDumy(method),
          e);
      throw new HttpNetAgentException(HttpNetAgentException.HTTP_NET_ERROR, e.getMessage());
    } catch (IOException e) {
      logger.error(
          "<< IOException msg ["
              + e.getMessage()
              + "], hs["
              + this.hashCode()
              + "],"
              + getHttpInfoDumy(method),
          e);
      throw new HttpNetAgentException(HttpNetAgentException.HTTP_NET_ERROR, e.getMessage());
    }

    return responseBody;
  }
コード例 #28
0
  /** Polls the fileserver, checks if there are any new files, and if so, displays them */
  @SuppressWarnings("unchecked")
  private void poll() {
    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(MediaUploadCallable.FILESERVER_URL);
    String json = null;
    double timestamp = 0;
    try {
      int status = client.executeMethod(method);
      json = method.getResponseBodyAsString();
    } catch (IOException e) {
      return;
    }
    try {
      Double largestTimeStamp = 0.0;
      HashMap<String, Object> jsonMap = new ObjectMapper().readValue(json, HashMap.class);
      for (Object kv : ((ArrayList) jsonMap.get("files"))) {
        LinkedHashMap<String, Object> linkedHashMap = (LinkedHashMap<String, Object>) kv;
        if (linkedHashMap.get("meta") == null) {
          continue;
        }
        LinkedHashMap<String, Object> meta =
            ((LinkedHashMap<String, Object>) linkedHashMap.get("meta"));
        timestamp = Double.parseDouble((String) meta.get("timestamp"));
        /*
        if (timestamp < lastTimeStamp) {
            continue;
        }*/
        if (alreadyKnown.contains((String) linkedHashMap.get("displayname"))) {
          continue;
        }
        DataSourceData data = new DataSourceData();
        LatLng latLng =
            new LatLng(
                new BigDecimal(Double.parseDouble((String) meta.get("Latitude"))),
                new BigDecimal(Double.parseDouble((String) meta.get("Longtitude"))));
        data.setArea(new Area(latLng, 0));
        data.setTitle((String) linkedHashMap.get("displayname"));
        data.setDescription(getDesciptionForFilename((String) linkedHashMap.get("displayname")));
        Datatypes filetype = DataType.getDatatype((String) linkedHashMap.get("displayname"));
        if (filetype == Datatypes.AUDIO) {
          data.setIconName("audio.png");
        }
        if (filetype == Datatypes.VIDEO) {
          data.setIconName("video.png");
        }
        if (filetype == Datatypes.IMAGE) {
          data.setIconName("image.png");
        }
        onDataReceived(data);

        alreadyKnown.add((String) linkedHashMap.get("displayname"));
        if (largestTimeStamp < timestamp) {
          largestTimeStamp = timestamp;
        }
      }
      lastTimeStamp = largestTimeStamp + 1;
    } catch (IOException e) {
      e.printStackTrace();
      // Suff went wrong
      return;
    }
  }
コード例 #29
0
  /**
   * Makes a rest request of any type at the specified urlSuffix. The urlSuffix should be of the
   * form /userService/users. If CS throws an exception it handled and transalated to a Openfire
   * exception if possible. This is done using the check fault method that tries to throw the best
   * maching exception.
   *
   * @param type Must be GET or DELETE
   * @param urlSuffix The url suffix of the rest request
   * @param xmlParams The xml with the request params, must be null if type is GET or DELETE only
   * @return The response as a xml doc.
   * @throws ConnectionException Thrown if there are issues perfoming the request.
   * @throws Exception Thrown if the response from Clearspace contains an exception.
   */
  public Element executeRequest(HttpType type, String urlSuffix, String xmlParams)
      throws ConnectionException, Exception {
    if (Log.isDebugEnabled()) {
      Log.debug("Outgoing REST call [" + type + "] to " + urlSuffix + ": " + xmlParams);
    }

    String wsUrl = getConnectionURI() + WEBSERVICES_PATH + urlSuffix;

    String secret = getSharedSecret();

    HttpClient client = new HttpClient();
    HttpMethod method;

    // Configures the authentication
    client.getParams().setAuthenticationPreemptive(true);
    Credentials credentials = new UsernamePasswordCredentials(OPENFIRE_USERNAME, secret);
    AuthScope scope = new AuthScope(host, port, AuthScope.ANY_REALM);
    client.getState().setCredentials(scope, credentials);

    // Creates the method
    switch (type) {
      case GET:
        method = new GetMethod(wsUrl);
        break;
      case POST:
        PostMethod pm = new PostMethod(wsUrl);
        StringRequestEntity requestEntity = new StringRequestEntity(xmlParams);
        pm.setRequestEntity(requestEntity);
        method = pm;
        break;
      case PUT:
        PutMethod pm1 = new PutMethod(wsUrl);
        StringRequestEntity requestEntity1 = new StringRequestEntity(xmlParams);
        pm1.setRequestEntity(requestEntity1);
        method = pm1;
        break;
      case DELETE:
        method = new DeleteMethod(wsUrl);
        break;
      default:
        throw new IllegalArgumentException();
    }

    method.setRequestHeader("Accept", "text/xml");
    method.setDoAuthentication(true);

    try {
      // Executes the request
      client.executeMethod(method);

      // Parses the result
      String body = method.getResponseBodyAsString();
      if (Log.isDebugEnabled()) {
        Log.debug("Outgoing REST call results: " + body);
      }

      // Checks the http status
      if (method.getStatusCode() != 200) {
        if (method.getStatusCode() == 401) {
          throw new ConnectionException(
              "Invalid password to connect to Clearspace.",
              ConnectionException.ErrorType.AUTHENTICATION);
        } else if (method.getStatusCode() == 404) {
          throw new ConnectionException(
              "Web service not found in Clearspace.", ConnectionException.ErrorType.PAGE_NOT_FOUND);
        } else if (method.getStatusCode() == 503) {
          throw new ConnectionException(
              "Web service not avaible in Clearspace.",
              ConnectionException.ErrorType.SERVICE_NOT_AVAIBLE);
        } else {
          throw new ConnectionException(
              "Error connecting to Clearspace, http status code: " + method.getStatusCode(),
              new HTTPConnectionException(method.getStatusCode()),
              ConnectionException.ErrorType.OTHER);
        }
      } else if (body.contains("Clearspace Upgrade Console")) {
        // TODO Change CS to send a more standard error message
        throw new ConnectionException(
            "Clearspace is in an update state.", ConnectionException.ErrorType.UPDATE_STATE);
      }

      Element response = localParser.get().parseDocument(body).getRootElement();

      // Check for exceptions
      checkFault(response);

      // Since there is no exception, returns the response
      return response;
    } catch (DocumentException e) {
      throw new ConnectionException(
          "Error parsing the response of Clearspace.", e, ConnectionException.ErrorType.OTHER);
    } catch (HttpException e) {
      throw new ConnectionException(
          "Error performing http request to Clearspace", e, ConnectionException.ErrorType.OTHER);
    } catch (UnknownHostException e) {
      throw new ConnectionException(
          "Unknown Host " + getConnectionURI() + " trying to connect to Clearspace",
          e,
          ConnectionException.ErrorType.UNKNOWN_HOST);
    } catch (IOException e) {
      throw new ConnectionException(
          "Error peforming http request to Clearspace.", e, ConnectionException.ErrorType.OTHER);
    } finally {
      method.releaseConnection();
    }
  }