Esempio n. 1
0
  // postToRestfulApi -
  // Note: params in the addr field need to be URLEncoded
  private String postToRestfulApi(
      String addr, String data, HttpServletRequest request, HttpServletResponse response) {
    if (localCookie) CookieHandler.setDefault(cm);
    String result = "";
    try {
      URLConnection connection = new URL(API_ROOT + addr).openConnection();
      String cookieVal = getBrowserInfiniteCookie(request);
      if (cookieVal != null) {
        connection.addRequestProperty("Cookie", "infinitecookie=" + cookieVal);
        connection.setDoInput(true);
      }
      connection.setDoOutput(true);
      connection.setRequestProperty("Accept-Charset", "UTF-8");

      // Post JSON string to URL
      OutputStream os = connection.getOutputStream();
      byte[] b = data.getBytes("UTF-8");
      os.write(b);

      // Receive results back from API
      InputStream is = connection.getInputStream();
      result = IOUtils.toString(is, "UTF-8");

      String newCookie = getConnectionInfiniteCookie(connection);
      if (newCookie != null && response != null) {
        setBrowserInfiniteCookie(response, newCookie, request.getServerPort());
      }
    } catch (Exception e) {
      // System.out.println("Exception: " + e.getMessage());
    }
    return result;
  } // TESTED
Esempio n. 2
0
  // callRestfulApi - Calls restful API and returns results as a string
  public String callRestfulApi(
      String addr, HttpServletRequest request, HttpServletResponse response) {
    if (localCookie) CookieHandler.setDefault(cm);

    try {
      ByteArrayOutputStream output = new ByteArrayOutputStream();
      URL url = new URL(API_ROOT + addr);
      URLConnection urlConnection = url.openConnection();
      String cookieVal = getBrowserInfiniteCookie(request);
      if (cookieVal != null) {
        urlConnection.addRequestProperty("Cookie", "infinitecookie=" + cookieVal);
        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(true);
        urlConnection.setRequestProperty("Accept-Charset", "UTF-8");
      }
      IOUtils.copy(urlConnection.getInputStream(), output);
      String newCookie = getConnectionInfiniteCookie(urlConnection);
      if (newCookie != null && response != null) {
        setBrowserInfiniteCookie(response, newCookie, request.getServerPort());
      }
      return output.toString();
    } catch (IOException e) {
      System.out.println(e.getMessage());
      return null;
    }
  } // TESTED
Esempio n. 3
0
  public void end() throws Exception {
    FunMessage.Builder fm = FunMessage.newBuilder().setGameId(gameId).setFunScore(rate());
    URL url = new URL("http://localhost:5000/gameFinish");
    URLConnection urlCon = url.openConnection();
    urlCon.setDoOutput(true);
    OutputStreamWriter wr = new OutputStreamWriter(urlCon.getOutputStream());
    wr.write("rating=");
    wr.flush();
    fm.build().writeTo(urlCon.getOutputStream());
    urlCon.getOutputStream().close();

    // No network I/O happens until you ask for feedback apparently
    urlCon.getInputStream();
  }
Esempio n. 4
0
  /** Creates an XMLRPC call from the given method name and parameters and sends it */
  protected void writeCall(String methodName, Object[] args) throws Exception {
    huc = u.openConnection();
    huc.setDoOutput(true);
    huc.setDoInput(true);
    huc.setUseCaches(false);
    huc.setRequestProperty("Content-Type", "binary/message-pack");
    huc.setReadTimeout(0);
    OutputStream os = huc.getOutputStream();
    Packer pk = new Packer(os);

    pk.packArray(args.length + 1);
    pk.pack(methodName);
    for (Object o : args) pk.pack(o);
    os.close();
  }
  private URLConnection prepareConnection(String fileUploadUrl, long fileSize)
      throws RemoteException, InvalidPropertyFaultMsg, RuntimeFaultFaultMsg, FileFaultFaultMsg,
          GuestOperationsFaultFaultMsg, InvalidStateFaultMsg, TaskInProgressFaultMsg,
          MalformedURLException, IOException, ProtocolException {

    // http://stackoverflow.com/questions/3386832/upload-a-file-using-http-put-in-java
    URL url = new URL(fileUploadUrl);
    URLConnection conn = url.openConnection();
    conn.setDoInput(true);
    conn.setDoOutput(true);
    if (conn instanceof HttpURLConnection) {
      ((HttpURLConnection) conn).setRequestMethod("PUT");
    } else {
      throw new IllegalStateException("Unknown connection type");
    }

    conn.setRequestProperty("Content-type", "application/octet-stream");
    conn.setRequestProperty("Content-length", "" + fileSize);
    return conn;
  }
Esempio n. 6
0
  /**
   * Makes a POST request and returns the server response.
   *
   * @param urlString the URL to post to
   * @param nameValuePairs a map of name/value pairs to supply in the request.
   * @return the server reply (either from the input stream or the error stream)
   */
  public static String doPost(String urlString, Map<String, String> nameValuePairs)
      throws IOException {
    URL url = new URL(urlString);
    URLConnection connection = url.openConnection();
    connection.setDoOutput(true);

    PrintWriter out = new PrintWriter(connection.getOutputStream());

    boolean first = true;
    for (Map.Entry<String, String> pair : nameValuePairs.entrySet()) {
      if (first) first = false;
      else out.print('&');
      String name = pair.getKey();
      String value = pair.getValue();
      out.print(name);
      out.print('=');
      out.print(URLEncoder.encode(value, "UTF-8"));
    }

    out.close();

    Scanner in;
    StringBuilder response = new StringBuilder();
    try {
      in = new Scanner(connection.getInputStream());
    } catch (IOException e) {
      if (!(connection instanceof HttpURLConnection)) throw e;
      InputStream err = ((HttpURLConnection) connection).getErrorStream();
      if (err == null) throw e;
      in = new Scanner(err);
    }

    while (in.hasNextLine()) {
      response.append(in.nextLine());
      response.append("\n");
    }

    in.close();
    return response.toString();
  }
Esempio n. 7
0
  public static String doPost(String urlString, Map<Object, Object> nameValuePairs)
      throws IOException {
    URL url = new URL(urlString);
    URLConnection connection = url.openConnection();
    connection.setDoOutput(true);
    String encoding = connection.getContentEncoding();
    if (encoding == null) encoding = "ISO-8859-1";

    try (PrintWriter out = new PrintWriter(connection.getOutputStream())) {
      boolean first = true;
      for (Map.Entry<Object, Object> pair : nameValuePairs.entrySet()) {
        if (first) first = false;
        else out.print('&');
        String name = pair.getKey().toString();
        String value = pair.getValue().toString();
        out.print(name);
        out.print('=');
        out.print(URLEncoder.encode(value, encoding));
      }
    }

    StringBuilder response = new StringBuilder();
    try (Scanner in = new Scanner(connection.getInputStream(), encoding)) {
      while (in.hasNextLine()) {
        response.append(in.nextLine());
        response.append("\n");
      }
    } catch (IOException e) {
      if (!(connection instanceof HttpURLConnection)) throw e;
      InputStream err = ((HttpURLConnection) connection).getErrorStream();
      if (err == null) throw e;
      Scanner in = new Scanner(err);
      response.append(in.nextLine());
      response.append("\n");
    }

    return response.toString();
  }
Esempio n. 8
0
 public static String sendPost(String url, String params) {
   PrintWriter out = null;
   BufferedReader in = null;
   String result = "";
   try {
     URL realUrl = new URL(url);
     URLConnection conn = realUrl.openConnection();
     conn.setRequestProperty("accept", "*/*");
     conn.setRequestProperty("connection", "Keep-Alive");
     conn.setRequestProperty(
         "user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
     conn.setDoOutput(true);
     conn.setDoInput(true);
     out = new PrintWriter(conn.getOutputStream());
     out.print(params);
     out.flush();
     in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
     String line;
     while ((line = in.readLine()) != null) {
       result += "\n" + line;
     }
   } catch (Exception e) {
     e.printStackTrace();
   } finally {
     try {
       if (out != null) {
         out.close();
       }
       if (in != null) {
         in.close();
       }
     } catch (IOException ex) {
       ex.printStackTrace();
     }
   }
   return result;
 }
Esempio n. 9
0
  /** Submits POST command to the server, and reads the reply. */
  public boolean post(
      String url,
      String fileName,
      String cryptToken,
      String type,
      String path,
      String content,
      String comment)
      throws IOException {

    String sep = "89692781418184";
    while (content.indexOf(sep) != -1) sep += "x";

    String message = makeMimeForm(fileName, cryptToken, type, path, content, comment, sep);

    // for test
    // URL server = new URL("http", "localhost", 80, savePath);
    URL server =
        new URL(getCodeBase().getProtocol(), getCodeBase().getHost(), getCodeBase().getPort(), url);
    URLConnection connection = server.openConnection();

    connection.setAllowUserInteraction(false);
    connection.setDoOutput(true);
    // connection.setDoInput(true);
    connection.setUseCaches(false);

    connection.setRequestProperty("Content-type", "multipart/form-data; boundary=" + sep);
    connection.setRequestProperty("Content-length", Integer.toString(message.length()));

    // System.out.println(url);
    String replyString = null;
    try {
      DataOutputStream out = new DataOutputStream(connection.getOutputStream());
      out.writeBytes(message);
      out.close();
      // System.out.println("Wrote " + message.length() +
      //		   " bytes to\n" + connection);

      try {
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String reply = null;
        while ((reply = in.readLine()) != null) {
          if (reply.startsWith("ERROR ")) {
            replyString = reply.substring("ERROR ".length());
          }
        }
        in.close();
      } catch (IOException ioe) {
        replyString = ioe.toString();
      }
    } catch (UnknownServiceException use) {
      replyString = use.getMessage();
      System.out.println(message);
    }
    if (replyString != null) {
      // System.out.println("---- Reply " + replyString);
      if (replyString.startsWith("URL ")) {
        URL eurl = getURL(replyString.substring("URL ".length()));
        getAppletContext().showDocument(eurl);
      } else if (replyString.startsWith("java.io.FileNotFoundException")) {
        // debug; when run from appletviewer, the http connection
        // is not available so write the file content
        if (path.endsWith(".draw") || path.endsWith(".map")) System.out.println(content);
      } else showStatus(replyString);
      return false;
    } else {
      showStatus(url + " saved");
      return true;
    }
  }