コード例 #1
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();
    }
  }
コード例 #2
0
  @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();
  }
コード例 #3
0
  /**
   * The method makes a GetMethod object and an HttpClient object. The HttpClient then executes the
   * Getmethod and returns the pagesource to the caller.
   *
   * @param url Url to fetch the pagesource for
   * @param followRedirect Boolean variable to specify GetMethod followRedirect value
   * @param doAuthentication Boolean variable to specify GetMethod doAuthentication value
   * @return String
   */
  public String getPageSourceWithoutProxy(
      String url, boolean followRedirects, boolean doAuthentication) {

    GetMethod getMethod = null;
    String pageSouce = null;
    HttpClient httpClient = new HttpClient();
    try {
      getMethod = new GetMethod(url);
      getMethod.setFollowRedirects(followRedirects);
      getMethod.setDoAuthentication(doAuthentication);
      httpClient.executeMethod(getMethod);
      pageSouce = getMethod.getResponseBodyAsString();
    } catch (Exception e) {
      l.error(e + "  " + e.getMessage() + "exception occured for url" + url);
      try {
        getMethod = new GetMethod(url);
        getMethod.setFollowRedirects(followRedirects);
        getMethod.setDoAuthentication(doAuthentication);
        httpClient.executeMethod(getMethod);
        pageSouce = getMethod.getResponseBodyAsString();
        getMethod.releaseConnection();
      } catch (Exception ex) {
        l.error(ex + "  " + ex.getMessage() + "exception occured for url " + url);
        getMethod.releaseConnection();
      }
    } finally {
      getMethod.releaseConnection();
    }
    return pageSouce;
  }
コード例 #4
0
ファイル: WebsiteLogin.java プロジェクト: simster/ZE_OG41
  public static void login() throws Exception {

    // Dem Client den Benutzernamen und das Kennwort übergeben
    HttpClient client = new HttpClient();
    client.getParams().setParameter("vb_login_username", "Programmierklasse");
    client.getParams().setParameter("vb_login_password", "987654");

    // Text von der Forumseite abholen
    GetMethod method =
        new GetMethod(
            "http://forum.operationgamma41.de/showthread.php?1228-Erfassung-der-Moderationszeiten-!");
    try {
      client.executeMethod(method);
      Cookie[] cookies = client.getState().getCookies();
      for (int i = 0; i < cookies.length; i++) {
        Cookie cookie = cookies[i];
        System.err.println(
            "Cookie: "
                + cookie.getName()
                + ", Value: "
                + cookie.getValue()
                + ", IsPersistent?: "
                + cookie.isPersistent()
                + ", Expiry Date: "
                + cookie.getExpiryDate()
                + ", Comment: "
                + cookie.getComment());
      }
      client.executeMethod(method);
    } catch (Exception e) {
      System.err.println(e);
    } finally {
      method.releaseConnection();
    }
  }
コード例 #5
0
  @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);
  }
コード例 #6
0
ファイル: HttpClient.java プロジェクト: sponte/selenium-grid
  protected Response request(HttpMethod method) throws IOException {
    int statusCode;
    String body;

    try {
      statusCode = client.executeMethod(method);
      if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY
          || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
        method.releaseConnection();

        HttpMethod postMethod = redirectMethod((PostMethod) method);
        statusCode = client.executeMethod(postMethod);
        method = postMethod;
      }
      if (statusCode == HttpStatus.SC_NO_CONTENT) {
        body = "";
      } else {
        body = new String(method.getResponseBody(), "utf-8");
      }
      logger.debug("Remote Control replied with '" + statusCode + " / '" + body + "'");
      return new Response(statusCode, body, method.getResponseHeaders());
    } finally {
      method.releaseConnection();
    }
  }
コード例 #7
0
  private String getEditorResponse(String urlpath, String encProcessSrc) {
    HttpClient httpclient = new HttpClient();

    PostMethod authMethod = new PostMethod(urlpath);
    NameValuePair[] data = {
      new NameValuePair("j_username", "admin"), new NameValuePair("j_password", "admin")
    };
    authMethod.setRequestBody(data);
    try {
      httpclient.executeMethod(authMethod);
    } catch (IOException e) {
      e.printStackTrace();
      return null;
    } finally {
      authMethod.releaseConnection();
    }

    PostMethod theMethod = new PostMethod(urlpath);
    theMethod.setParameter("processsource", encProcessSrc);
    StringBuffer sb = new StringBuffer();
    try {
      httpclient.executeMethod(theMethod);
      sb.append(theMethod.getResponseBodyAsString());
      return sb.toString();

    } catch (Exception e) {
      e.printStackTrace();
      return null;
    } finally {
      theMethod.releaseConnection();
    }
  }
コード例 #8
0
  /**
   * Send the command to Solr using a GET
   *
   * @param queryString
   * @param url
   * @return
   * @throws IOException
   */
  private static String sendGetCommand(String queryString, String url) throws IOException {
    String results = null;
    HttpClient client = new HttpClient();
    GetMethod get = new GetMethod(url);
    get.setQueryString(queryString.trim());

    client.executeMethod(get);
    try {
      // Execute the method.
      int statusCode = client.executeMethod(get);

      if (statusCode != HttpStatus.SC_OK) {
        System.err.println("Method failed: " + get.getStatusLine());
        results = "Method failed: " + get.getStatusLine();
      }

      results = getStringFromStream(get.getResponseBodyAsStream());
    } catch (HttpException e) {
      System.err.println("Fatal protocol violation: " + e.getMessage());
      e.printStackTrace();
    } catch (IOException e) {
      System.err.println("Fatal transport error: " + e.getMessage());
      e.printStackTrace();
    } finally {
      // Release the connection.
      get.releaseConnection();
    }
    return results;
  }
コード例 #9
0
  public void runSimpleLoginLoadTest() {
    HttpClient httpClient = getHttpClient();

    // RequestEntity re = new StringRequestEntity(raw_body, "text/xml",
    // "UTF-16");

    try {

      PostMethod postMethod = new PostMethod(getAsvip() + "mas/login");
      postMethod.addParameters(getReqParams());
      int statuscode = httpClient.executeMethod(postMethod);
      byte[] responseBody = postMethod.getResponseBody();
      postMethod.releaseConnection();
      // System.out.println(statuscode + " LOGIN   RESPONSE  ---- "+ new String(responseBody));

      postMethod = new PostMethod(getAsvip() + "mas/logout");
      statuscode = httpClient.executeMethod(postMethod);
      responseBody = postMethod.getResponseBody();
      //	System.out.println(statuscode + "  LOGOUT  RESPONSE  ---- "+ new String(responseBody));
      postMethod.releaseConnection();

    } catch (HttpException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
コード例 #10
0
  @Test
  public void createInstanceEveryTime() throws Exception {
    final HttpServer server = new HttpServer(new GetMethodHandler());
    try {
      Runnable runnable = getRunnable(server);
      new Thread(runnable).start();
      Thread.sleep(300L);

      String URL = "http://localhost:8888/";
      int timesToCall = 300;

      {
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < timesToCall; i++) {
          Request request = new Request(URL);
          HTTP.get(request);
          Thread.sleep(10L);
        }
        long endTime = System.currentTimeMillis();
        long millis = endTime - startTime - 10 * timesToCall;
        System.out.println("com.m3.curly 300 GET req : " + millis + " milliseconds");
        Thread.sleep(300L);
      }

      {
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < timesToCall; i++) {
          HttpClient client = new HttpClient();
          HttpMethod method = new GetMethod(URL);
          client.executeMethod(method);
          Thread.sleep(10L);
        }
        long endTime = System.currentTimeMillis();
        long millis = endTime - startTime - 10 * timesToCall;
        System.out.println("Commons HttpClient 300 GET req : " + millis + " milliseconds");
        Thread.sleep(300L);
      }

      {
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < timesToCall; i++) {
          HttpClient client = new HttpClient(new MultiThreadedHttpConnectionManager());
          HttpMethod method = new GetMethod(URL);
          client.executeMethod(method);
          Thread.sleep(10L);
        }
        long endTime = System.currentTimeMillis();
        long millis = endTime - startTime - 10 * timesToCall;
        System.out.println(
            "Commons HttpClient(MultiThreaded) 300 GET req : " + millis + " milliseconds");
        Thread.sleep(300L);
      }

    } finally {
      server.stop();
      Thread.sleep(300L);
    }
  }
コード例 #11
0
 /** Create the given directory via WebDAV, if needed, under given URL */
 public void mkdir(String url) throws IOException {
   int status = 0;
   status = httpClient.executeMethod(new GetMethod(url));
   if (status != 200) {
     status = httpClient.executeMethod(new HttpAnyMethod("MKCOL", url));
     if (status != 201) {
       throw new IOException("mkdir(" + url + ") failed, status code=" + status);
     }
   }
 }
コード例 #12
0
ファイル: RESTWorkItemHandler.java プロジェクト: sazonov/jbpm
 protected void doAuthorization(
     HttpClient httpclient, HttpMethod method, Map<String, Object> params) {
   if (type == null) {
     return;
   }
   String u = (String) params.get("Username");
   String p = (String) params.get("Password");
   if (u == null || p == null) {
     u = this.username;
     p = this.password;
   }
   if (u == null) {
     throw new IllegalArgumentException("Could not find username");
   }
   if (p == null) {
     throw new IllegalArgumentException("Could not find password");
   }
   if (type == AuthenticationType.BASIC) {
     httpclient
         .getState()
         .setCredentials(
             new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM),
             new UsernamePasswordCredentials(u, p));
     method.setDoAuthentication(true);
   } else if (type == AuthenticationType.FORM_BASED) {
     String authUrlStr = (String) params.get("AuthUrl");
     if (authUrlStr == null) {
       authUrlStr = authUrl;
     }
     if (authUrlStr == null) {
       throw new IllegalArgumentException("Could not find authentication url");
     }
     try {
       httpclient.executeMethod(method);
     } catch (IOException e) {
       throw new RuntimeException("Could not execute request for form-based authentication", e);
     } finally {
       method.releaseConnection();
     }
     PostMethod authMethod = new PostMethod(authUrlStr);
     NameValuePair[] data = {
       new NameValuePair("j_username", u), new NameValuePair("j_password", p)
     };
     authMethod.setRequestBody(data);
     try {
       httpclient.executeMethod(authMethod);
     } catch (IOException e) {
       throw new RuntimeException("Could not initialize form-based authentication", e);
     } finally {
       authMethod.releaseConnection();
     }
   } else {
     throw new RuntimeException("Unknown AuthenticationType " + type);
   }
 }
コード例 #13
0
  private String sendRequest(TicketsRequest request) throws HttpException, IOException {

    String html = "";
    GetMethod get = new GetMethod(url2);
    client.executeMethod(get);

    int statusCodeInit = client.executeMethod(get);
    if (statusCodeInit != HttpStatus.SC_OK) {
      logger.error("sendRequest method failed. Get method failed: " + get.getStatusLine());
      return null;
    } else {
      html = IOUtils.toString(get.getResponseBodyAsStream(), "UTF-8");
    }
    parseToken(html);

    client.getHttpConnectionManager().getParams().setSoTimeout(10000);
    PostMethod post = new PostMethod(URL);

    post.addRequestHeader("Accept", "*/*");
    post.addRequestHeader("Accept-Encoding", "gzip, deflate");
    post.addRequestHeader("Accept-Language", "uk,ru;q=0.8,en-US;q=0.5,en;q=0.3");
    //		post.addRequestHeader("Cache-Control", "no-cache");
    post.addRequestHeader("Connection", "keep-alive");
    //		post.addRequestHeader("Content-Length", "288"); //202. 196
    post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
    post.addRequestHeader("GV-Ajax", "1");
    post.addRequestHeader("GV-Referer", "http://booking.uz.gov.ua/");
    post.addRequestHeader("GV-Screen", "1920x1080");
    post.addRequestHeader("GV-Token", token);
    post.addRequestHeader("GV-Unique-Host", "1");
    post.addRequestHeader("Host", "booking.uz.gov.ua");
    //		post.addRequestHeader("Pragma", "no-cache");
    post.addRequestHeader("Origin", "http://booking.uz.gov.ua");
    post.addRequestHeader("Referer", "http://booking.uz.gov.ua/");
    post.addRequestHeader(
        "User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:43.0) Gecko/20100101 Firefox/39.0");

    post.addParameter("another_ec", "0");
    post.addParameter("date_dep", new SimpleDateFormat("dd.MM.yyyy").format(request.date));
    post.addParameter("search", "");
    post.addParameter("station_from", request.from.getName());
    post.addParameter("station_id_from", request.from.getStationId());
    post.addParameter("station_id_till", request.till.getStationId());
    post.addParameter("station_till", request.till.getName());
    post.addParameter("time_dep", "00:00");
    post.addParameter("time_dep_till", "");

    int statusCode = client.executeMethod(post);
    if (statusCode != HttpStatus.SC_OK) {
      logger.error("sendRequest method failed. Post method failed: " + post.getStatusLine());
      return null;
    }

    return post.getResponseBodyAsString();
  }
コード例 #14
0
 @Test
 public void testRunning() throws Exception {
   HttpClient client = new HttpClient();
   setupClientSsl();
   // test get
   HttpMethod get = new GetMethod("https://127.0.0.1:8443/etomcat_x509");
   client.executeMethod(get);
   byte[] responseBody = get.getResponseBody();
   String content = new String(responseBody, "UTF-8");
   Assert.assertEquals("Servlet get fail", SecuredService.GREETING, content);
   // test assess denied
   HttpMethod post = new PostMethod("https://127.0.0.1:8443/etomcat_x509");
   client.executeMethod(post);
   assertEquals("Method security fail get fail", 403, post.getStatusCode());
 }
コード例 #15
0
ファイル: XMLRestWorker.java プロジェクト: jormaral/SLdirect
  private Sector buscarSector(int sectorCode) {
    HttpClient httpclient = getHttpClient();
    GetMethod get = new GetMethod(restUrl.getSectorUrl());
    get.addRequestHeader("Accept", "application/xml");
    Sector ret = null;
    try {
      int result = httpclient.executeMethod(get);
      logger.info("Response status code: " + result);
      String xmlString = get.getResponseBodyAsString();
      logger.info("Response body: " + xmlString);

      ret = importSector(xmlString, sectorCode);
    } catch (HttpException e) {
      logger.error(e.getMessage());
    } catch (IOException e) {
      logger.error(e.getMessage());
    } catch (ParserConfigurationException e) {
      logger.error(e.getMessage());
    } catch (SAXException e) {
      logger.error(e.getMessage());
    } finally {
      get.releaseConnection();
    }
    return ret;
  }
コード例 #16
0
ファイル: XMLRestWorker.java プロジェクト: jormaral/SLdirect
  private ClasificacionOrganizacion findRestClasificacionOrganizacion(Integer id) {
    HttpClient httpclient = getHttpClient();
    GetMethod get = new GetMethod(restUrl.getClassOrganizacionUrl());
    get.addRequestHeader("Accept", "application/xml");
    ClasificacionOrganizacion ret = null;
    try {
      int result = httpclient.executeMethod(get);
      logger.info("Response status code: " + result);
      String xmlString = get.getResponseBodyAsString();
      logger.info("Response body: " + xmlString);

      ret = importClasificacionOrganizacion(xmlString, id);
    } catch (HttpException e) {
      logger.error(e.getMessage());
    } catch (IOException e) {
      logger.error(e.getMessage());
    } catch (ParserConfigurationException e) {
      logger.error(e.getMessage());
    } catch (SAXException e) {
      logger.error(e.getMessage());
    } finally {
      get.releaseConnection();
    }
    return ret;
  }
コード例 #17
0
ファイル: XMLRestWorker.java プロジェクト: jormaral/SLdirect
  private String getXmlToken() {
    String token = null;
    HttpClient httpclient = getHttpClient();
    GetMethod get = new GetMethod(restUrl.getTokenUrl());
    get.addRequestHeader("Accept", "application/xml");

    NameValuePair userParam = new NameValuePair(USERNAME_PARAM, satelite.getUser());
    NameValuePair passwordParam = new NameValuePair(PASSWORD_PARAM, satelite.getPassword());
    NameValuePair[] params = new NameValuePair[] {userParam, passwordParam};

    get.setQueryString(params);
    try {
      int statusCode = httpclient.executeMethod(get);
      if (statusCode != HttpStatus.SC_OK) {
        logger.error("Method failed: " + get.getStatusLine());
      }
      token = parseToken(get.getResponseBodyAsString());
    } catch (HttpException e) {
      logger.error(e.getMessage());
    } catch (IOException e) {
      logger.error(e.getMessage());
    } catch (ParserConfigurationException e) {
      logger.error(e.getMessage());
    } catch (SAXException e) {
      logger.error(e.getMessage());
    } finally {
      get.releaseConnection();
    }

    return token;
  }
コード例 #18
0
ファイル: XMLRestWorker.java プロジェクト: jormaral/SLdirect
  private Capacidad buscarCapacidad(int capacityCode) {
    HttpClient httpclient = getHttpClient();
    GetMethod get = new GetMethod(restUrl.getCapacidadUrl());
    get.addRequestHeader("Accept", "application/xml");
    Capacidad ret = null;
    try {
      int result = httpclient.executeMethod(get);
      if (logger.isTraceEnabled()) logger.trace("Response status code: " + result);
      String xmlString = get.getResponseBodyAsString();
      if (logger.isTraceEnabled()) logger.trace("Response body: " + xmlString);

      ret = importCapacidad(xmlString, capacityCode);
    } catch (HttpException e) {
      logger.error(e.getMessage());
    } catch (IOException e) {
      logger.error(e.getMessage());
    } catch (ParserConfigurationException e) {
      logger.error(e.getMessage());
    } catch (SAXException e) {
      logger.error(e.getMessage());
    } finally {
      get.releaseConnection();
    }
    return ret;
  }
コード例 #19
0
 private void doPost(
     String realm,
     String host,
     String user,
     String pass,
     String url,
     boolean handshake,
     boolean preemtive,
     int result)
     throws Exception {
   HttpClient client = new HttpClient();
   client.getParams().setAuthenticationPreemptive(preemtive);
   client
       .getState()
       .setCredentials(
           new AuthScope(host, -1, realm), new UsernamePasswordCredentials(user, pass));
   PostMethod post = new PostMethod(url);
   post.setDoAuthentication(handshake);
   StringRequestEntity requestEntity = new StringRequestEntity(soapRequest, "text/xml", "UTF-8");
   post.setRequestEntity(requestEntity);
   try {
     int status = client.executeMethod(post);
     assertEquals(result, status);
     assertNotNull(post.getResponseBodyAsString());
   } finally {
     post.releaseConnection();
   }
 }
コード例 #20
0
  private void doGet(
      String realm,
      String host,
      String user,
      String pass,
      String url,
      boolean handshake,
      boolean preemtive,
      int result)
      throws Exception {
    HttpClient client = new HttpClient();
    client.getParams().setAuthenticationPreemptive(preemtive);
    client
        .getState()
        .setCredentials(
            new AuthScope(host, -1, realm), new UsernamePasswordCredentials(user, pass));
    GetMethod get = new GetMethod(url);
    get.setDoAuthentication(handshake);

    try {
      int status = client.executeMethod(get);
      assertEquals(result, status);
    } finally {
      get.releaseConnection();
    }
  }
コード例 #21
0
  protected ResponseStatus simpleHttpGet(
      final BiServerConnection connection, final String restUrl, boolean authenticate) {

    ResponseStatus responseStatus = new ResponseStatus();

    HttpClient client = getSimpleHttpClient(connection, authenticate);

    final String url =
        connection.getUrl().endsWith("/")
            ? (connection.getUrl() + restUrl)
            : (connection.getUrl() + "/" + restUrl);

    GetMethod get = createGetMethod(url, authenticate);

    try {
      // execute the GET
      client.executeMethod(get);

      responseStatus.setStatus(get.getStatusCode());
      responseStatus.setMessage(get.getResponseBodyAsString());

    } catch (Exception e) {

      responseStatus.setStatus(-1);
      responseStatus.setMessage(e.getMessage());

    } finally {
      // release any connection resources used by the method
      get.releaseConnection();
    }

    return responseStatus;
  }
コード例 #22
0
ファイル: DataService.java プロジェクト: luinnx/box_android
  /**
   * 批量上传图片
   *
   * @param path 服务器地址
   * @param name 用户名
   * @param filePath sd卡图片路径
   * @param onSuccessListner
   * @return
   * @throws Exception
   */
  public static String sendDataByHttpClientPost(
      String path, List<File> files, List<Part> mparameters, OnSuccessListner listner)
      throws Exception {

    for (int i = 0; i < files.size(); i++) {
      mparameters.add(new FilePart("file", files.get(i)));
    }
    Part[] parts = mparameters.toArray(new Part[0]);

    PostMethod filePost = new PostMethod(path);
    filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
    HttpClient client = new HttpClient();
    client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);

    int status = client.executeMethod(filePost);
    if (status == 200) {
      Log.e("DataService", "" + filePost.getResponseCharSet());
      String result = new String(filePost.getResponseBodyAsString());
      Log.e("DataService", "--" + result);
      // JSONArray array = (JSONArray) JSON.parse(result);
      Log.e("JSONArray", "--" + result);
      listner.onSuccess(result);
      return result;
    } else {
      listner.onFailed();
      return null;
    }
  }
コード例 #23
0
ファイル: AppHelper.java プロジェクト: XyzalZhang/WeX5
  public static String getHttp(String url, Boolean all) throws HttpException, Exception {
    HttpClient client = new HttpClient();
    PostMethod method = new PostMethod(url);
    method
        .getParams()
        .setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0, false));
    try {
      int statusCode = client.executeMethod(method);
      if (statusCode != HttpStatus.SC_OK) {
        throw new HttpException("访问失败,错误原因:" + method.getStatusLine());
      }

      InputStream response = method.getResponseBodyAsStream();
      BufferedReader br = new BufferedReader(new InputStreamReader(response, "UTF-8"));
      if (all) {
        StringBuffer sb = new StringBuffer();
        String str = null;
        while ((str = br.readLine()) != null) {
          sb.append(str);
          sb.append("\r\n");
        }

        return sb.toString();
      } else {
        return br.readLine();
      }
    } finally {
      method.releaseConnection();
    }
  }
コード例 #24
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);
  }
コード例 #25
0
ファイル: DataService.java プロジェクト: luinnx/box_android
  /**
   * 单次上传图片or文件
   *
   * @param path
   * @param name
   * @param filePath
   * @return
   * @throws Exception
   */
  public static String sendDataByHttpClientPost(String path, String name, String filePath)
      throws Exception {

    /*
     * List<Part> partList = new ArrayList<Part>(); partList.add(new
     * StringPart("user", name));
     *
     * for (int i = 0; i < 4; i++) { partList.add(new FilePart(name,
     * FilePart())); }
     */

    // 实例化上传数据的数组
    Part[] parts = {new StringPart("user", name), new FilePart("file", new File(filePath))};

    PostMethod filePost = new PostMethod(path);

    filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));

    org.apache.commons.httpclient.HttpClient client =
        new org.apache.commons.httpclient.HttpClient();
    client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);

    int status = client.executeMethod(filePost);
    Log.e("Other", "返回结果:" + status);
    if (status == 200) {

      System.out.println(filePost.getResponseCharSet());
      String result = new String(filePost.getResponseBodyAsString());

      System.out.println("--" + result);
      return result;
    } else {
      throw new IllegalStateException("服务器状态异常");
    }
  }
コード例 #26
0
  public String jasperAuthen(String username, String password) throws HttpException, IOException {
    logger.info("Authenticate : Jasper Report Server");

    Header[] headers = null;
    String sessionCookie = "";

    this.httpClient = new HttpClient();
    PostMethod mPost = new PostMethod(restLoginUrl);

    Header mtHeader = new Header();
    mtHeader.setName("content-type");
    mtHeader.setValue("application/x-www-form-urlencoded");
    mtHeader.setName("accept");

    mPost.addParameter("j_username", username);
    mPost.addParameter("j_password", password);
    mPost.addRequestHeader(mtHeader);

    httpClient.executeMethod(mPost);

    headers = mPost.getResponseHeaders();
    mPost.releaseConnection();

    sessionCookie = headers[2].getValue();
    logger.debug("SessionCookie is {}", sessionCookie);

    return sessionCookie;
  }
コード例 #27
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();
  }
コード例 #28
0
  @Override
  public String getReportTextContent(String rqAppId, String urlReport) throws Exception {
    logger.info("Get report contents as String");

    JRSConfig jrsConfig = configurationRepository.findJasperUser(rqAppId);
    JRSAuthen jrsAuthen = jrsConfig.getJrsAuthen();
    String passwordEncrypted = AES128Cipher.decrypt(jrsAuthen.getPassword());

    this.jasperAuthen(jrsAuthen.getUsername(), passwordEncrypted);

    Header mtHeader = new Header();
    mtHeader.setName("content-type");
    mtHeader.setValue("application/x-www-form-urlencoded");
    mtHeader.setName("accept");

    GetMethod mGet = new GetMethod(urlReport);
    mGet.addRequestHeader(mtHeader);
    httpClient.executeMethod(mGet);

    String value = mGet.getResponseBodyAsString().trim();
    logger.debug("Response Body is {}", value);

    if (isHTML(value)) {
      logger.error("The contents are HTML");
      throw new CustomGenericException("Cannot get the report contents as String");
    }

    return value;
  }
コード例 #29
0
  public synchronized void updateHtmlEntry(String key, String html) throws HttpException {
    HttpClient httpClient = new HttpClient();
    PostMethod postMethod = new PostMethod(catalogDbURL + "update");
    System.err.println(key);
    postMethod.addParameter("key", key);
    postMethod.addParameter("columns", html);
    try {
      httpClient.executeMethod(postMethod);
    } catch (HttpException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }

    if (postMethod.getStatusCode() == HttpStatus.SC_OK) {
      try {
        String resp = postMethod.getResponseBodyAsString();
        System.err.println(resp);
      } catch (IOException e) {
        e.printStackTrace();
      }
    } else {
      throw new HttpException("failed to post form.");
    }
  }
コード例 #30
0
  /** Checks all the servers marked as being online if they still are online. */
  private synchronized void checkOnlineServers() {
    Iterator itr;
    itr = online.listIterator();
    while (itr.hasNext()) {
      Server server = (Server) itr.next();
      String url = getServerURL(server);
      GetMethod get = new GetMethod(url);
      get.setFollowRedirects(false);

      try {
        httpClient.executeMethod(get);
        if (!okServerResponse(get.getStatusCode())) {
          offline.add(server);
          itr.remove();
          log.debug("Server going OFFLINE! " + getServerURL(server));
          listener.serverOffline(server);
        }
      } catch (Exception e) {
        offline.add(server);
        itr.remove();
        log.debug("Server going OFFLINE! " + getServerURL(server));
        listener.serverOffline(server);
      } finally {
        get.releaseConnection();
      }
    }
  }