Example #1
0
  @Test
  public void testGetXmlAndValidateXmlSchema()
      throws IOException, ParserConfigurationException, SAXException {
    HttpClient httpClient = new HttpClient();
    GetMethod get = new GetMethod("http://localhost/ch13personal/personal.xml");
    Document document;
    try {
      httpClient.executeMethod(get);
      InputStream input = get.getResponseBodyAsStream();
      // Parse the XML document into a DOM tree
      DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
      document = parser.parse(input);
    } finally {
      get.releaseConnection();
    }

    // Create a SchemaFactory capable of understanding WXS schemas
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

    // load a WXS schema, represented by a Schema instance
    Source schemaFile = new StreamSource(new File("src/main/webapp/personal.xsd"));
    Schema schema = factory.newSchema(schemaFile);

    // create a Validator instance, which can be used to validate an
    // instance document
    Validator validator = schema.newValidator();

    // validate the DOM tree
    validator.validate(new DOMSource(document));
  }
Example #2
0
  /**
   * 单次上传图片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("服务器状态异常");
    }
  }
Example #3
0
  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();
    }
  }
Example #4
0
  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;
  }
Example #5
0
  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;
  }
  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;
  }
Example #7
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();
   }
 }
  private HttpClient getClient() {
    HttpClient httpClient = new HttpClient();
    httpClient.getParams().setParameter("http.protocol.content-charset", "gbk");
    httpClient.getParams().setSoTimeout(timeout);

    if (useSSL) {
      if (sslPort > 0) {
        Protocol myhttps =
            new Protocol(
                "https", (ProtocolSocketFactory) new EasySSLProtocolSocketFactory(), sslPort);
        Protocol.registerProtocol("https", myhttps);
      }
    }

    if (useProxy) {
      HostConfiguration hc = new HostConfiguration();
      hc.setProxy(proxyUrl, proxyPort);
      httpClient.setHostConfiguration(hc);
      if (proxyUser != null) {
        httpClient
            .getState()
            .setProxyCredentials(
                AuthScope.ANY, new UsernamePasswordCredentials(proxyUser, proxyPassword));
      }
    }

    return httpClient;
  }
Example #9
0
  public void httpOnline() throws HttpException, IOException {
    /* 1 生成 HttpClinet 对象并设置参数*/
    HttpClient httpClient = new HttpClient();
    // 设置 Http 连接超时为5秒
    httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
    /*2 生成 GetMethod 对象并设置参数*/
    GetMethod getMethod = new GetMethod(m_ipAddr);
    // 设置 get 请求超时为 5 秒
    getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
    // 设置请求重试处理,用的是默认的重试处理:请求三次
    getMethod
        .getParams()
        .setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
    /*3 执行 HTTP GET 请求*/

    long startTime = System.currentTimeMillis();
    if (HttpStatus.SC_OK == httpClient.executeMethod(getMethod)) {
      statusCode = "Up";
      responseTime = System.currentTimeMillis() - startTime;
    } else {
      statusCode = "Down";
      responseTime = -1;
    }

    /*6 .释放连接*/
    getMethod.releaseConnection();
  }
  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;
  }
  private static String login() throws Exception {
    HttpClient httpClient = new HttpClient();
    PostMethod loginMethod = new PostMethod("http://*****:*****@gmail.com");
    loginRequest.setPassword("testpass");

    JAXBContext context = JAXBContext.newInstance("com.fb.platform.auth._1_0");
    Marshaller marshaller = context.createMarshaller();
    StringWriter sw = new StringWriter();
    marshaller.marshal(loginRequest, sw);

    StringRequestEntity requestEntity = new StringRequestEntity(sw.toString());
    loginMethod.setRequestEntity(requestEntity);

    int statusCode = httpClient.executeMethod(loginMethod);
    if (statusCode != HttpStatus.SC_OK) {
      System.out.println("unable to execute the login method : " + statusCode);
      return null;
    }
    String loginResponseStr = loginMethod.getResponseBodyAsString();
    System.out.println("Got the login Response : \n" + loginResponseStr);
    Unmarshaller unmarshaller = context.createUnmarshaller();
    LoginResponse loginResponse =
        (LoginResponse)
            unmarshaller.unmarshal(new StreamSource(new StringReader(loginResponseStr)));

    return loginResponse.getSessionToken();
  }
Example #12
0
 public static boolean downloadFile(String url, String filePath) {
   HttpClient client = new HttpClient();
   GetMethod method = new GetMethod(url);
   method
       .getParams()
       .setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
   try {
     int statusCode = client.executeMethod(method);
     if (statusCode != HttpStatus.SC_OK) {
       logger.error("downloadFile fail.url={},status={}", url, statusCode);
       return false;
     }
     BufferedInputStream bis = new BufferedInputStream(method.getResponseBodyAsStream());
     FileOutputStream fos = new FileOutputStream(new File(filePath));
     BufferedOutputStream bos = new BufferedOutputStream(fos);
     int len;
     while ((len = bis.read()) != -1) {
       bos.write(len);
     }
     bos.flush();
     bos.close();
     fos.close();
     bis.close();
     return true;
   } catch (Exception e) {
     logger.error("url=" + url, e);
     return false;
   } finally {
     method.releaseConnection();
   }
 }
Example #13
0
  public static String postRequest(String url, Map<String, String> parameters) {
    HttpClient client = new HttpClient();
    PostMethod method = new PostMethod(url);
    method
        .getParams()
        .setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
    if (MapUtils.isNotEmpty(parameters)) {
      NameValuePair[] pairs = new NameValuePair[parameters.size()];
      Iterator<Entry<String, String>> iterator = parameters.entrySet().iterator();
      int index = 0;
      while (iterator.hasNext()) {
        Map.Entry<String, String> entry = (Map.Entry<String, String>) iterator.next();
        pairs[index++] = new NameValuePair(entry.getKey(), entry.getValue());
      }
      method.setRequestBody(pairs);
    }

    try {
      int statusCode = client.executeMethod(method);
      if (statusCode != HttpStatus.SC_OK) {
        logger.error("post method fail.url={},status={}", url, statusCode);
        return "";
      }
      byte[] responseBody = method.getResponseBody();
      return new String(responseBody, "UTF-8");
    } catch (Exception e) {
      logger.error("url=" + url, e);
      return "";
    } finally {
      method.releaseConnection();
    }
  }
Example #14
0
 @Override
 public void download(String url, OutputStream output) {
   Cookie cookie = new Cookie(".dmm.co.jp", SESSION_ID_KEY, sessionId, "/", null, false);
   HttpClient client = new HttpClient();
   client.getState().addCookie(cookie);
   GetMethod method = new GetMethod(url);
   try {
     downloding.set(true);
     client.executeMethod(method);
     InputStream input = method.getResponseBodyAsStream();
     try {
       IOUtils.copyLarge(input, output);
       byte[] buffer = new byte[4096];
       int n = 0;
       while (downloding.get() && -1 != (n = input.read(buffer))) {
         output.write(buffer, 0, n);
       }
       if (!downloding.get()) {
         LOGGER.warn("interrupted to download " + url);
       }
     } finally {
       IOUtils.closeQuietly(input);
     }
   } catch (IOException e) {
     throw new EgetException("failed to download " + url, e);
   } finally {
     downloding.set(false);
     method.releaseConnection();
   }
 }
Example #15
0
  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();
    }
  }
Example #16
0
  protected void loadNetImage() {
    String url = "http://ww2.sinaimg.cn/thumbnail/675e5a2bjw1e0pydwgwgnj.jpg";
    HttpClient httpClient = null;
    GetMethod httpGet = null;
    Bitmap bitmap = null;

    try {
      httpClient = getHttpClient();
      httpGet = getHttpGet(url, null, null);
      if (httpClient.executeMethod(httpGet) == HttpStatus.SC_OK) {
        InputStream inStream = httpGet.getResponseBodyAsStream();
        bitmap = BitmapFactory.decodeStream(inStream);
        inStream.close();

        mImageView03.setImageBitmap(bitmap);
      }
    } catch (HttpException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      httpGet.releaseConnection();
      httpClient = null;
    }
  }
Example #17
0
 public WebClient(String encoding) {
   this.encoding = encoding;
   httpClient = new HttpClient();
   httpClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
   httpClient.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, encoding);
   httpClient.getParams().setParameter(HttpMethodParams.SINGLE_COOKIE_HEADER, true);
 }
  @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();
    }
  }
Example #19
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();
    }
  }
  public static int GetCountByCkan3(String url) {
    int count = 0;
    HttpClient client = new HttpClient();
    LOG.info("**** INPUT SPLIT COUNT *** " + url);
    GetMethod method = new GetMethod(url);
    method
        .getParams()
        .setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));

    method.setRequestHeader("User-Agent", "Hammer Project - SantaMaria crawler");
    method
        .getParams()
        .setParameter(HttpMethodParams.USER_AGENT, "Hammer Project - SantaMaria crawler");

    try {
      client.executeMethod(method);
      byte[] responseBody = method.getResponseBody();
      Document doc = Document.parse(new String(responseBody));
      if (doc.containsKey("result")) {
        count = ((Document) doc.get("result")).getInteger("count");
        LOG.info("Find --> " + count);
      }
    } catch (Exception e) {
      e.printStackTrace();
      LOG.error(e);
    } finally {
      method.releaseConnection();
    }
    return count;
  }
Example #21
0
  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;
  }
Example #22
0
 private static boolean autoVerify(
     Message msg,
     Connection connection,
     String verify,
     String msgId,
     String key,
     String userId,
     String subject,
     String body)
     throws SQLException, HttpException, IOException, MessagingException {
   String select = "select prefs from users where uid=" + userId;
   log("Auto verification select: " + select);
   Statement stmt = connection.createStatement();
   try {
     stmt.execute(select);
     ResultSet result = stmt.getResultSet();
     if (result.next()) {
       String prefs = result.getString(1);
       String phrase = getPref(prefs, "secret_phrase");
       log("Auto verification of message: " + verify + "=?=" + phrase);
       if (verify.equals(phrase)) {
         log("Automatic verification of message " + msgId + " successful.");
         HttpClient client = new HttpClient();
         HttpMethod method = new GetMethod(getUrl(msgId, key));
         client.executeMethod(method);
         return true;
       }
     }
     return false;
   } finally {
     stmt.close();
   }
 }
Example #23
0
  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;
  }
Example #24
0
 /**
  * 抓取网页静态内容: 下载 void
  *
  * @author wx
  */
 private void fetchStaticResources() {
   HttpClient client = new HttpClient();
   Set<String> urlSet = staticModels.keySet();
   Iterator<String> ite = urlSet.iterator();
   while (ite.hasNext()) {
     String key = ite.next();
     StaticResourceModel model = staticModels.get(key);
     // 执行下载
     GetMethod get = new GetMethod(model.getUrl());
     try {
       client.executeMethod(get);
       File path = new File(siteSaveFolder + model.savePath());
       if (!path.exists()) {
         path.mkdirs();
       }
       File storeFile = new File(siteSaveFolder + model.getFilePath());
       FileOutputStream output = new FileOutputStream(storeFile);
       // 得到网络资源的字节数组,并写入文件
       output.write(get.getResponseBody());
       output.close();
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
 }
Example #25
0
  /**
   * 批量上传图片
   *
   * @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;
    }
  }
Example #26
0
  public static void send(String content, String mobile) throws Exception {

    HttpClient client = new HttpClient();
    PostMethod method = new PostMethod(Url);

    client.getParams().setContentCharset("UTF-8");
    method.setRequestHeader("ContentType", "application/x-www-form-urlencoded;charset=UTF-8");

    NameValuePair[] data = { // 提交短信
      new NameValuePair("account", "cf_ddz"),
      new NameValuePair("password", "zaq12wsx"), // 密码可以使用明文密码或使用32位MD5加密
      new NameValuePair("mobile", mobile),
      new NameValuePair("content", content),
    };

    method.setRequestBody(data);

    client.executeMethod(method);

    String SubmitResult = method.getResponseBodyAsString();

    Document doc = DocumentHelper.parseText(SubmitResult);
    Element root = doc.getRootElement();

    String code = root.elementText("code");
    String msg = root.elementText("msg");
    String smsid = root.elementText("smsid");

    logger.info(code + "|" + msg + "|" + smsid);
  }
Example #27
0
 /** Make sure we can get a valid http client. */
 @Test
 public void canGetHttpClient() {
   final HttpClient client = this.config.httpClient();
   Assert.assertNotNull(client);
   Assert.assertTrue(
       client.getHttpConnectionManager() instanceof MultiThreadedHttpConnectionManager);
 }
Example #28
0
 /** Create a new Client. The client will not use authentication by default. */
 public Client() {
   client = new HttpClient();
   client.getParams().setParameter("http.socket.timeout", Integer.valueOf(DEFAULT_TIMEOUT));
   log.debug("proxy host: " + client.getHostConfiguration().getProxyHost());
   log.debug("proxy port: " + client.getHostConfiguration().getProxyPort());
   doAuthentication = false;
 }
Example #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.");
    }
  }
Example #30
0
  /**
   * Method responsible for querying and parsing to correios cep locator
   *
   * @author pulu - 09/09/2013
   */
  private Webservicecep findAddressByCepAtCorreios(String url) throws IOException {
    HttpClient httpClient = new HttpClient();
    PostMethod postMethod = new PostMethod(url);
    log.log(Level.INFO, "Querying to correios WS...");
    try {
      httpClient.executeMethod(postMethod);

      if (postMethod.getStatusCode() == HttpStatus.SC_OK) {
        Document doc = Jsoup.parse(new URL(url).openStream(), "ISO-8859-1", url);
        Elements elements = doc.select("td:not([colspan]):not(:has(*))");

        return new Webservicecep(
            Webservicecep.SUCCESS_CODE,
            elements.get(3).ownText(),
            elements.get(2).ownText(),
            elements.get(1).ownText(),
            "",
            elements.get(0).ownText());

      } else return new Webservicecep(Webservicecep.ERROR_CODE);
    } catch (Exception e) {
      log.log(Level.WARNING, "Failed to parse html data. Possible reason: invalid cep.");
      return new Webservicecep(Webservicecep.ERROR_CODE);
    }
  }