示例#1
0
  @Override
  public void run() {
    try {
      URL url = buildPingUrl();
      if (logger.isDebugEnabled()) {
        logger.debug("Sending UDC information to {}...", url);
      }
      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      conn.setConnectTimeout((int) HTTP_TIMEOUT.millis());
      conn.setReadTimeout((int) HTTP_TIMEOUT.millis());

      if (conn.getResponseCode() >= 300) {
        throw new Exception(
            String.format("%s Responded with Code %d", url.getHost(), conn.getResponseCode()));
      }
      if (logger.isDebugEnabled()) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line = reader.readLine();
        while (line != null) {
          logger.debug(line);
          line = reader.readLine();
        }
        reader.close();
      } else {
        conn.getInputStream().close();
      }
      successCounter.incrementAndGet();
    } catch (Exception e) {
      if (logger.isDebugEnabled()) {
        logger.debug("Error sending UDC information", e);
      }
      failCounter.incrementAndGet();
    }
  }
  public SetIfModifiedSince() throws Exception {

    serverSock = new ServerSocket(0);
    int port = serverSock.getLocalPort();

    Thread thr = new Thread(this);
    thr.start();

    Date date = new Date(new Date().getTime() - 1440000); // this time yesterday
    URL url;
    HttpURLConnection con;

    // url = new URL(args[0]);
    url = new URL("http://localhost:" + String.valueOf(port) + "/anything");
    con = (HttpURLConnection) url.openConnection();

    con.setIfModifiedSince(date.getTime());
    con.connect();
    int ret = con.getResponseCode();

    if (ret == 304) {
      System.out.println("Success!");
    } else {
      throw new RuntimeException(
          "Test failed! Http return code using setIfModified method is:"
              + ret
              + "\nNOTE:some web servers are not implemented according to RFC, thus a failed test does not necessarily indicate a bug in setIfModifiedSince method");
    }
  }
  private boolean handshake() throws Exception {
    URL homePage = new URL("http://mangaonweb.com/viewer.do?ctsn=" + ctsn);

    HttpURLConnection urlConn = (HttpURLConnection) homePage.openConnection();
    urlConn.connect();
    if (urlConn.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND) return (false);

    // save the cookie
    String headerName = null;
    for (int i = 1; (headerName = urlConn.getHeaderFieldKey(i)) != null; i++) {
      if (headerName.equals("Set-Cookie")) {
        cookies = urlConn.getHeaderField(i);
      }
    }

    // save cdn and crcod
    String page = "", line;
    BufferedReader stream =
        new BufferedReader(new InputStreamReader(urlConn.getInputStream(), "UTF-8"));
    while ((line = stream.readLine()) != null) page += line;

    cdn = param(page, "cdn");
    crcod = param(page, "crcod");

    return (true);
  }
  /**
   * 运行时,添加JVM参数“-Dsun.net.http.retryPost=false”,可阻止自动重连。
   *
   * @see 'http://www.coderanch.com/t/490463/sockets/java/Timeout-retry-URLHTTPRequest'
   */
  @Test
  public void testConnectionResetByHttpURLConnection() throws IOException {
    testConnectionResetCount = 0;

    String resp = null;
    try {
      HttpURLConnection conn =
          (HttpURLConnection) new URL("http://localhost:65532/soso").openConnection();
      conn.setDoOutput(true);
      conn.setRequestMethod("POST");
      conn.getOutputStream().write("username".getBytes());
      resp = conn.getResponseCode() + "";
    } catch (IOException e) {
      Throwable ee = ExceptionUtils.getRootCause(e);
      if (ee == null) {
        ee = e;
      }
      Logger.error(this, "", ee);
      Assert.assertNotSame(NoHttpResponseException.class, ee.getClass());
      Assert.assertSame(SocketException.class, ee.getClass());
      Assert.assertTrue(
          "Connection reset".equals(ee.getMessage())
              || "Socket closed".equals(ee.getMessage())
              || "Unexpected end of file from server".equals(ee.getMessage()));
    } finally {
      Logger.info(
          this,
          "resp[HttpURLConnection]-["
              + testConnectionResetCount
              + "]=========["
              + resp
              + "]=========");
    }
    Assert.assertEquals(2, testConnectionResetCount);
  }
示例#5
0
 Response(HttpURLConnection connection) throws IOException {
   try {
     connection.connect();
     code = connection.getResponseCode();
     headers = parseHeaders(connection);
     stream = isSuccessful() ? connection.getInputStream() : connection.getErrorStream();
   } catch (UnknownHostException e) {
     throw new OAuthException("The IP address of a host could not be determined.", e);
   }
 }
示例#6
0
  @Test(
      description = "Verify the downloads links return 200 rather than 404",
      groups = {"functional"})
  public void DownloadsTab_02() throws HarnessException {

    // Determine which links should be present
    List<String> locators = new ArrayList<String>();

    if (ZimbraSeleniumProperties.zimbraGetVersionString().contains("NETWORK")) {

      locators.addAll(Arrays.asList(NetworkOnlyLocators));
      locators.addAll(Arrays.asList(CommonLocators));

    } else if (ZimbraSeleniumProperties.zimbraGetVersionString().contains("FOSS")) {

      locators.addAll(Arrays.asList(FossOnlyLocators));
      locators.addAll(Arrays.asList(CommonLocators));

    } else {
      throw new HarnessException(
          "Unable to find NETWORK or FOSS in version string: "
              + ZimbraSeleniumProperties.zimbraGetVersionString());
    }

    for (String locator : locators) {
      String href = app.zPageDownloads.sGetAttribute("xpath=" + locator + "@href");
      String page = ZimbraSeleniumProperties.getBaseURL() + href;

      HttpURLConnection connection = null;
      try {

        URL url = new URL(page);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("HEAD");
        int code = connection.getResponseCode();

        // TODO: why is 400 returned for the PDF links?
        // 200 and 400 are acceptable
        ZAssert.assertStringContains(
            "200 400", "" + code, "Verify the download URL is valid: " + url.toString());

      } catch (MalformedURLException e) {
        throw new HarnessException(e);
      } catch (IOException e) {
        throw new HarnessException(e);
      } finally {
        if (connection != null) {
          connection.disconnect();
          connection = null;
        }
      }
    }
  }
示例#7
0
  public ErrorInfo listPolicy(String polname, String token) throws IOException, RestException {

    String realm = "/";
    String data = null;
    ErrorInfo ei = null;
    InputStreamReader iss = null;
    BufferedReader br = null;
    HttpURLConnection urlc = null;
    InputStream inputStream = null;

    try {
      data =
          "policynames="
              + URLEncoder.encode(polname, "UTF-8")
              + "&realm="
              + URLEncoder.encode(realm, "UTF-8")
              + "&submit="
              + URLEncoder.encode("Submit", "UTF-8");
    } catch (UnsupportedEncodingException e) {
      System.out.println("OpenssoHelper: " + e.getMessage());
      e.printStackTrace();
    }

    if (data != null) {
      try {
        r.Connect(new URL(url + ssoadm_list));
      } catch (MalformedURLException e) {
        System.out.println("OpenssoHelper: " + e.getMessage());
        e.printStackTrace();
      }

      urlc = (HttpURLConnection) r.c;
      urlc.addRequestProperty("Cookie", "iPlanetDirectoryPro=\"" + token + "\"");
      r.Send(urlc, data);

      String answer = null;
      int status = 0;
      inputStream = urlc.getInputStream();
      iss = new InputStreamReader(inputStream);
      br = new BufferedReader(iss);
      answer = BrToString(br);
      status = urlc.getResponseCode();
      if (answer != null) {
        ei = new ErrorInfo(answer, status);
      }
      br.close();
      iss.close();
      inputStream.close();
      urlc.disconnect();
    }

    return ei;
  }
  private byte[] downloadByteArray(URL url) throws IOException {
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestProperty("Cookie", cookies);
    if (conn.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND) return (null);

    InputStream in = conn.getInputStream();
    byte[] buf = new byte[conn.getContentLength()];
    int read, offset = 0;
    while ((read = in.read(buf, offset, buf.length - offset)) != -1) {
      offset += read;
    }
    return (buf);
  }
示例#9
0
  public ErrorInfo doLogin() throws IOException, RestException {

    String data = null;
    ErrorInfo ei = null;
    InputStreamReader iss = null;
    BufferedReader br = null;
    HttpURLConnection urlc = null;
    InputStream inputStream = null;

    try {
      data =
          "username="******"UTF-8")
              + "&password="******"UTF-8");
    } catch (UnsupportedEncodingException e) {
      System.out.println("OpenssoHelper: " + e.getMessage());
      e.printStackTrace();
    }

    if (data != null) {
      try {
        r.Connect(new URL(url + authenticate));
      } catch (MalformedURLException e) {
        System.out.println("OpenssoHelper: " + e.getMessage());
        e.printStackTrace();
      }

      urlc = (HttpURLConnection) r.c;
      r.Send(urlc, data);

      String answer = null;
      int status = 0;

      inputStream = urlc.getInputStream();
      iss = new InputStreamReader(inputStream);
      br = new BufferedReader(iss);
      answer = BrToString(br);
      status = urlc.getResponseCode();
      if (answer != null) {
        ei = new ErrorInfo(answer, status);
      }
      br.close();
      iss.close();
      inputStream.close();
      urlc.disconnect();
    }

    return ei;
  }
示例#10
0
  // добавить продукт в базу json server
  public static void add(ProductREST product) throws NotValidProductException, IOException {
    try {
      check(product); // рповеряем продукт
      // connection к серверу
      HttpURLConnection con = (HttpURLConnection) ((new URL(PRODUCT_URL).openConnection()));
      con.setRequestMethod("POST"); // метод post для добавления

      // генерируем запрос
      StringBuilder urlParameters = new StringBuilder();
      urlParameters
          .append("name=")
          .append(URLEncoder.encode(product.getName(), "UTF8"))
          .append("&");
      urlParameters.append("price=").append(product.getPrice()).append("&");
      urlParameters.append("weight=").append(product.getWeight()).append("&");
      urlParameters
          .append("manufacturer=")
          .append(product.getManufacturer().getCountry())
          .append("&");
      urlParameters.append("category=").append(URLEncoder.encode(product.getCategory(), "UTF8"));

      con.setDoOutput(true); // разрешаем отправку данных
      // отправляем
      try (DataOutputStream out = new DataOutputStream(con.getOutputStream())) {
        out.writeBytes(urlParameters.toString());
      }
      // код ответа
      int responseCode = con.getResponseCode();
      System.out.println("\nSending 'POST' request to URL : " + PRODUCT_URL);
      System.out.println("Response Code : " + responseCode);

    } catch (NotValidProductException e) {
      e.printStackTrace();
      throw e;
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
      throw new UnsupportedEncodingException("cannot recognize encoding");
    } catch (ProtocolException e) {
      e.printStackTrace();
      throw new ProtocolException("No such protocol, protocol must be POST,DELETE,PATCH,GET etc.");
    } catch (MalformedURLException e) {
      e.printStackTrace();
      throw new MalformedURLException("Url is not valid");
    } catch (IOException e) {
      e.printStackTrace();
      throw new IOException("cannot write information to server");
    }
  }
 private byte[] sendHttpMessage(byte[] body) throws IOException {
   HttpMessageContext context = HttpMessageContext.getInstance();
   context.Debug("GNHttpConnection [sendHttpMessage] starts");
   if (context.getLogheader()) {
     context.Info(logMessageSetting());
   }
   connection.setDoInput(true);
   if (body != null) {
     connection.setDoOutput(true);
     OutputStream os = TimedURLConnection.getOutputStream(connection, timeout * 1000);
     context.Debug("GNHttpConnection [sendHttpMessage] sending message ...");
     os.write(body);
     context.Debug("GNHttpConnection [sendHttpMessage] message sent");
   }
   context.Debug(
       "GNHttpConnection [sendHttpMessage] TimedURLConnection.getInputStream timeout["
           + timeout
           + " S]");
   InputStream is = TimedURLConnection.getInputStream(connection, timeout * 1000);
   responseCode = connection.getResponseCode();
   context.Debug("GNHttpConnection [sendHttpMessage] responseCode[" + responseCode + "]");
   responseMessage = HttpMessageContext.getMessage(is);
   responseheaders = new Hashtable<String, String>();
   int no = 0;
   while (true) {
     String headerName = connection.getHeaderFieldKey(no);
     String headerValue = connection.getHeaderField(no);
     if (headerName != null && headerName.length() > 0) {
       responseheaders.put(headerName, headerValue);
     } else {
       if (headerValue == null || headerValue.length() <= 0) break;
     }
     no++;
   }
   if (context.getLogheader()) {
     GTConfigFile head = new GTConfigFile(responseheaders);
     context.Debug("GNHttpConnection [sendHttpMessage] responseHeader\r\n" + head);
     context.Debug(
         "GNHttpConnection [sendHttpMessage] responseMessage\r\n"
             + new String(getResponseMessage()));
     context.Info("GNHttpConnection [sendHttpMessage] success for " + url);
   } else context.Info("GNHttpConnection [sendHttpMessage] success for " + url);
   return responseMessage;
 }
示例#12
0
  @Test(groups = {"pulse"}) // test method
  public void testUserTx() throws Exception {

    try {

      String testurl =
          "http://" + host + ":" + port + "/" + strContextRoot + "/MyServlet?testcase=usertx";
      URL url = new URL(testurl);
      echo("Connecting to: " + url.toString());
      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      conn.connect();
      int responseCode = conn.getResponseCode();

      InputStream is = conn.getInputStream();
      BufferedReader input = new BufferedReader(new InputStreamReader(is));

      String line = null;
      boolean result = false;
      String testLine = null;
      String EXPECTED_RESPONSE = "user-tx-commit:true";
      String EXPECTED_RESPONSE2 = "user-tx-rollback:true";
      while ((line = input.readLine()) != null) {
        // echo(line);
        if (line.indexOf(EXPECTED_RESPONSE) != -1 && line.indexOf(EXPECTED_RESPONSE2) != -1) {
          testLine = line;
          echo(testLine);
          result = true;
          break;
        }
      }

      Assert.assertEquals(result, true, "Unexpected Results");

    } catch (Exception e) {
      e.printStackTrace();
      throw new Exception(e);
    }
  }
示例#13
0
  private boolean test(String c) throws Exception {
    String EXPECTED_RESPONSE = c + ":pass";
    boolean result = false;
    String url = "http://" + host + ":" + port + strContextRoot + "/jpa?testcase=" + c;
    // System.out.println("url="+url);

    HttpURLConnection conn = (HttpURLConnection) (new URL(url)).openConnection();
    int code = conn.getResponseCode();
    if (code != 200) {
      System.err.println("Unexpected return code: " + code);
    } else {
      InputStream is = conn.getInputStream();
      BufferedReader input = new BufferedReader(new InputStreamReader(is));
      String line = null;
      while ((line = input.readLine()) != null) {
        if (line.contains(EXPECTED_RESPONSE)) {
          result = true;
          break;
        }
      }
    }
    return result;
  }
    protected Void doInBackground(Void... params) {
      String outString;
      HttpURLConnection c = null;
      DataOutputStream os = null;

      outString = scanData.getOwnBSSID();
      outString = outString + "\nL\tX\t" + lastLat + "\t" + lastLon + "\n";

      try {
        URL connectURL = new URL("http://www.openwlanmap.org/android/upload.php");
        c = (HttpURLConnection) connectURL.openConnection();
        if (c == null) {
          return null;
        }

        c.setDoOutput(true); // enable POST
        c.setRequestMethod("POST");
        c.addRequestProperty("Content-Type", "application/x-www-form-urlencoded, *.*");
        c.addRequestProperty("Content-Length", "" + outString.length());
        os = new DataOutputStream(c.getOutputStream());
        os.write(outString.getBytes());
        os.flush();
        c.getResponseCode();
        os.close();
        outString = null;
        os = null;
      } catch (IOException ioe) {
      } finally {
        try {
          if (os != null) os.close();
          if (c != null) c.disconnect();
        } catch (IOException ioe) {
          ioe.printStackTrace();
        }
      }
      return null;
    }
示例#15
0
  /**
   * When you call this, you post the data, after which it is gone. The post is synchronous. The
   * function returns after posting and receiving a reply. Get a new data stream with
   * startDataStream() to make a new post. (You could hold on to the writer, but using it will have
   * no effect after calling this method.)
   *
   * @return HTTP response code, 200 means successful.
   */
  public int postToCDB() throws IOException, ProtocolException, UnsupportedEncodingException {
    cdbId = -1;
    if (dataWriter == null) {
      throw new IllegalStateException("call startDataStream() and write something first");
    }
    HttpURLConnection connection = (HttpURLConnection) postURL.openConnection();
    connection.setRequestMethod("POST");

    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    dataWriter.flush();
    String data = JASPER_DATA_PARAM + "=" + URLEncoder.encode(dataWriter.toString(), "UTF-8");
    dataWriter = null;

    connection.setRequestProperty("Content-Length", "" + Integer.toString(data.getBytes().length));
    connection.setUseCaches(false);
    connection.setDoInput(true);
    connection.setDoOutput(true);

    DataOutputStream out = new DataOutputStream(connection.getOutputStream());
    out.writeBytes(data);
    out.flush();
    out.close();

    int responseCode = connection.getResponseCode();
    wasSuccessful = (200 == responseCode);
    InputStream response;
    if (wasSuccessful) {
      response = connection.getInputStream();
    } else {
      response = connection.getErrorStream();
    }
    if (response != null) processResponse(response);
    connection.disconnect();

    return responseCode;
  }
示例#16
0
    @Override
    public InputSource resolveEntity(String publicId, String systemId)
        throws SAXException, IOException {
      InputSource inputSource = null;

      if (options.entityResolver != null) {
        inputSource = options.entityResolver.resolveEntity(null, systemId);
      }
      if (inputSource == null) {
        inputSource = new InputSource(systemId);
        InputStream is = null;
        int redirects = 0;
        boolean redirect;
        URL url = JAXWSUtils.getFileOrURL(inputSource.getSystemId());
        URLConnection conn = url.openConnection();
        do {
          if (conn instanceof HttpsURLConnection) {
            if (options.disableSSLHostnameVerification) {
              ((HttpsURLConnection) conn).setHostnameVerifier(new HttpClientVerifier());
            }
          }
          redirect = false;
          if (conn instanceof HttpURLConnection) {
            ((HttpURLConnection) conn).setInstanceFollowRedirects(false);
          }

          if (conn instanceof JarURLConnection) {
            if (conn.getUseCaches()) {
              doReset = true;
              conn.setDefaultUseCaches(false);
              c = conn;
            }
          }

          try {
            is = conn.getInputStream();
            // is = sun.net.www.protocol.http.HttpURLConnection.openConnectionCheckRedirects(conn);
          } catch (IOException e) {
            if (conn instanceof HttpURLConnection) {
              HttpURLConnection httpConn = ((HttpURLConnection) conn);
              int code = httpConn.getResponseCode();
              if (code == 401) {
                errorReceiver.error(
                    new SAXParseException(
                        WscompileMessages.WSIMPORT_AUTH_INFO_NEEDED(
                            e.getMessage(), systemId, WsimportOptions.defaultAuthfile),
                        null,
                        e));
                throw new AbortException();
              }
              // FOR other code we will retry with MEX
            }
            throw e;
          }

          // handle 302 or 303, JDK does not seem to handle 302 very well.
          // Need to redesign this a bit as we need to throw better error message for IOException in
          // this case
          if (conn instanceof HttpURLConnection) {
            HttpURLConnection httpConn = ((HttpURLConnection) conn);
            int code = httpConn.getResponseCode();
            if (code == 302 || code == 303) {
              // retry with the value in Location header
              List<String> seeOther = httpConn.getHeaderFields().get("Location");
              if (seeOther != null && seeOther.size() > 0) {
                URL newurl = new URL(url, seeOther.get(0));
                if (!newurl.equals(url)) {
                  errorReceiver.info(
                      new SAXParseException(
                          WscompileMessages.WSIMPORT_HTTP_REDIRECT(code, seeOther.get(0)), null));
                  url = newurl;
                  httpConn.disconnect();
                  if (redirects >= 5) {
                    errorReceiver.error(
                        new SAXParseException(
                            WscompileMessages.WSIMPORT_MAX_REDIRECT_ATTEMPT(), null));
                    throw new AbortException();
                  }
                  conn = url.openConnection();
                  inputSource.setSystemId(url.toExternalForm());
                  redirects++;
                  redirect = true;
                }
              }
            }
          }
        } while (redirect);
        inputSource.setByteStream(is);
      }

      return inputSource;
    }
示例#17
0
  public static String httpPost(String urlAddress, String[] params) {
    URL url = null;
    HttpURLConnection conn = null;
    BufferedReader in = null;
    StringBuffer sb = new StringBuffer();

    try {
      url = new URL(urlAddress);
      conn = (HttpURLConnection) url.openConnection(); // 建立连接
      // 设置通用的请求属性
      /*
       * conn.setRequestProperty("user-agent",
       * "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
       */
      conn.setRequestProperty("User-Agent", "Mozilla/5.0 ( compatible ) ");
      conn.setRequestProperty("Accept", "*/*");
      conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

      conn.setUseCaches(false);
      conn.setDoInput(true);
      // conn.setConnectTimeout(5 * 1000);
      conn.setDoOutput(true);
      conn.setRequestMethod("POST");
      String paramsTemp = "";
      for (String param : params) {
        if (param != null && !"".equals(param)) {
          if (params.length > 1) {
            paramsTemp += "&" + param;
          } else if (params.length == 1) {
            paramsTemp = params[0];
          }
        }
      }

      byte[] b = paramsTemp.getBytes();
      System.out.println("btye length:" + b.length);
      // conn.setRequestProperty("Content-Length",
      // String.valueOf(b.length));
      conn.getOutputStream().write(b, 0, b.length);
      conn.getOutputStream().flush();
      conn.getOutputStream().close();
      int count = conn.getResponseCode();
      if (200 == count) {
        in = new BufferedReader(new InputStreamReader(conn.getInputStream())); // 发送请求
      } else {
        System.out.println("错误类型:" + count);
        return "server no start-up";
      }

      while (true) {
        String line = in.readLine();
        if (line == null) {
          break;
        } else {
          sb.append(line);
        }
      }
    } catch (MalformedURLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (ProtocolException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      System.out.println("error ioexception:" + e.getMessage());
      e.printStackTrace();
      return "server no start-up";
    } finally {
      try {
        if (in != null) {
          in.close();
        }
        if (conn != null) {
          conn.disconnect();
        }
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }

    return sb.toString();
  }