Exemple #1
0
 public void run() {
   try {
     Thread.sleep(10);
     byte[] buf = getBuf();
     URL url = new URL("http://127.0.0.1:" + port + "/test");
     HttpURLConnection con = (HttpURLConnection) url.openConnection();
     con.setDoOutput(true);
     con.setDoInput(true);
     con.setRequestMethod("POST");
     con.setRequestProperty(
         "Content-Type",
         "Multipart/Related; type=\"application/xop+xml\"; boundary=\"----=_Part_0_6251267.1128549570165\"; start-info=\"text/xml\"");
     OutputStream out = con.getOutputStream();
     out.write(buf);
     out.close();
     InputStream in = con.getInputStream();
     byte[] newBuf = readFully(in);
     in.close();
     if (buf.length != newBuf.length) {
       System.out.println("Doesn't match");
       error = true;
     }
     synchronized (lock) {
       ++received;
       if ((received % 1000) == 0) {
         System.out.println("Received=" + received);
       }
     }
   } catch (Exception e) {
     // e.printStackTrace();
     System.out.print(".");
     error = true;
   }
 }
  // прочитать весь json в строку
  private static String readAll() throws IOException {
    StringBuilder data = new StringBuilder();
    try {
      HttpURLConnection con = (HttpURLConnection) ((new URL(PRODUCT_URL).openConnection()));
      con.setRequestMethod("GET");

      con.setDoInput(true);
      String s;
      try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) {
        while ((s = in.readLine()) != null) {
          data.append(s);
        }
      }
    } catch (MalformedURLException e) {
      e.printStackTrace();
      throw new MalformedURLException("Url is not valid");
    } catch (ProtocolException e) {
      e.printStackTrace();
      throw new ProtocolException("No such protocol, it must be POST,GET,PATCH,DELETE etc.");
    } catch (IOException e) {
      e.printStackTrace();
      throw new IOException("cannot read from  server");
    }
    return data.toString();
  }
 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;
 }
Exemple #4
0
  private int[] getNewList(int size, int min, int max) {
    int[] returnArray = new int[size];
    try {
      URL randomOrg =
          new URL(
              "http://www.random.org/cgi-bin/randnum?"
                  + "num="
                  + size
                  + "&min="
                  + min
                  + "&max="
                  + max
                  + "&col=1");
      HttpURLConnection con = (HttpURLConnection) randomOrg.openConnection();
      con.setRequestMethod("GET");
      con.setDoInput(true);
      InputStream in = con.getInputStream();
      InputStreamReader isr = new InputStreamReader(in);
      BufferedReader br = new BufferedReader(isr);
      String theLine;

      for (int i = 0; i < size; i++) {
        returnArray[i] = Integer.parseInt(br.readLine());
      }

      con.disconnect();
    }
    // if something fails, revert to something a little less random, but still good
    // the hashCode is based on the objects memory address, which is unique for each object
    catch (Exception e) {
      Random r = new Random();
      r.setSeed(r.hashCode());
      for (int i = 0; i < size; i++) returnArray[i] = r.nextInt(max);
    }
    return returnArray;
  }
Exemple #5
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;
  }
Exemple #6
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();
  }
  @Override
  public HashSet<ScoredAnnotation> solveSa2W(String text) throws AnnotationException {
    HashSet<ScoredAnnotation> res;
    try {
      res = new HashSet<ScoredAnnotation>();
      lastTime = Calendar.getInstance().getTimeInMillis();

      URL wikiApi = new URL(url);
      String parameters =
          "references=true&repeatMode=all&minProbability=0.0&source="
              + URLEncoder.encode(text, "UTF-8");
      HttpURLConnection slConnection = (HttpURLConnection) wikiApi.openConnection();
      slConnection.setRequestProperty("accept", "text/xml");
      slConnection.setDoOutput(true);
      slConnection.setDoInput(true);
      slConnection.setRequestMethod("POST");
      slConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
      slConnection.setRequestProperty("charset", "utf-8");
      slConnection.setRequestProperty(
          "Content-Length", "" + Integer.toString(parameters.getBytes().length));
      slConnection.setUseCaches(false);

      DataOutputStream wr = new DataOutputStream(slConnection.getOutputStream());
      wr.writeBytes(parameters);
      wr.flush();
      wr.close();
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      DocumentBuilder builder = factory.newDocumentBuilder();
      Document doc = builder.parse(slConnection.getInputStream());

      /*			URL wikiApi = new URL(url+"?references=true&repeatMode=all&minProbability=0.0&source="+URLEncoder.encode(text, "UTF-8"));
      			URLConnection wikiConnection = wikiApi.openConnection();
      			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      			DocumentBuilder builder = factory.newDocumentBuilder();
      			Document doc = builder.parse(wikiConnection.getInputStream());
      */

      lastTime = Calendar.getInstance().getTimeInMillis() - lastTime;

      XPathFactory xPathfactory = XPathFactory.newInstance();
      XPath xpath = xPathfactory.newXPath();
      XPathExpression idExpr = xpath.compile("//detectedTopic/@id");
      XPathExpression weightExpr = xpath.compile("//detectedTopic/@weight");
      XPathExpression referenceExpr = xpath.compile("//detectedTopic/references");

      NodeList ids = (NodeList) idExpr.evaluate(doc, XPathConstants.NODESET);
      NodeList weights = (NodeList) weightExpr.evaluate(doc, XPathConstants.NODESET);
      NodeList references = (NodeList) referenceExpr.evaluate(doc, XPathConstants.NODESET);

      for (int i = 0; i < weights.getLength(); i++) {
        if (weights.item(i).getNodeType() != Node.TEXT_NODE) {
          int id = Integer.parseInt(ids.item(i).getNodeValue());
          float weight = Float.parseFloat(weights.item(i).getNodeValue());
          //					System.out.println("ID="+ids.item(i).getNodeValue()+" weight="+weight);
          XPathExpression startExpr =
              xpath.compile("//detectedTopic[@id=" + id + "]/references/reference/@start");
          XPathExpression endExpr =
              xpath.compile("//detectedTopic[@id=" + id + "]/references/reference/@end");
          NodeList starts =
              (NodeList) startExpr.evaluate(references.item(i), XPathConstants.NODESET);
          NodeList ends = (NodeList) endExpr.evaluate(references.item(i), XPathConstants.NODESET);
          for (int j = 0; j < starts.getLength(); j++) {
            int start = Integer.parseInt(starts.item(j).getNodeValue());
            int end = Integer.parseInt(ends.item(j).getNodeValue());
            int len = end - start;
            res.add(new ScoredAnnotation(start, len, id, weight));
          }
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
      throw new AnnotationException(
          "An error occurred while querying Wikipedia Miner API. Message: " + e.getMessage());
    }
    return res;
  }