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(); }
// 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
private void sendFile(InputStream in, URLConnection conn) throws IOException { conn.connect(); OutputStream out = conn.getOutputStream(); try { StreamUtils.copyStream(in, out, IO_BUFFER_SIZE); } finally { out.close(); } }
public void run() { OutputStream outputstream = null; try { outputstream = c.getOutputStream(); } catch (IOException ioexception) { b = ioexception; } a = outputstream; synchronized (event) { event.notifyAll(); } }
/** 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(); }
/** * 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(); }
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(); }
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; }
/** 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; } }