List of usage examples for java.io DataOutputStream close
@Override public void close() throws IOException
From source file:com.otisbean.keyring.Ring.java
/** * Export data to the specified file.//w w w. jav a2 s.com * * @param outFile Path to the output file * @throws IOException * @throws GeneralSecurityException */ public void save(String outFile) throws IOException, GeneralSecurityException { log("save(" + outFile + ")"); if (outFile.startsWith("http")) { URL url = new URL(outFile); URLConnection urlConn = url.openConnection(); urlConn.setDoInput(true); urlConn.setDoOutput(true); urlConn.setUseCaches(false); urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); DataOutputStream dos = new DataOutputStream(urlConn.getOutputStream()); String message = "data=" + URLEncoder.encode(getExportData().toJSONString(), "UTF-8"); dos.writeBytes(message); dos.flush(); dos.close(); // the server responds by saying // "OK" or "ERROR: blah blah" BufferedReader br = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); String s = br.readLine(); if (!s.equals("OK")) { StringBuilder sb = new StringBuilder(); sb.append("Failed to save to URL '"); sb.append(url); sb.append("': "); while ((s = br.readLine()) != null) { sb.append(s); } throw new IOException(sb.toString()); } br.close(); } else { Writer writer = getWriter(outFile); getExportData().writeJSONString(writer); closeWriter(writer, outFile); } }
From source file:com.dao.ShopThread.java
private boolean doPTShop() throws Exception { long startTime = System.currentTimeMillis(); // loadCookie(); boolean result = true; LogUtil.webPrintf("??..."); String postParams = addPTDynamicParams(); LogUtil.webPrintf("???"); LogUtil.webPrintf("?..."); HttpURLConnection loginConn = getHttpPostConn(this.ptshopurl); loginConn.setRequestProperty("Host", "danbao.5173.com"); loginConn.setRequestProperty("Content-Length", Integer.toString(postParams.length())); LogUtil.debugPrintf("?HEADER===" + loginConn.getRequestProperties()); DataOutputStream wr = new DataOutputStream(loginConn.getOutputStream()); wr.writeBytes(postParams);//from www. j av a 2s . co m wr.flush(); wr.close(); int responseCode = loginConn.getResponseCode(); LogUtil.debugPrintf("\nSending 'POST' request to URL : " + this.ptshopurl); LogUtil.debugPrintf("Post parameters : " + postParams); LogUtil.debugPrintf("Response Code : " + responseCode); Map<String, List<String>> header = loginConn.getHeaderFields(); LogUtil.debugPrintf("??HEADER===" + header); List<String> cookie = header.get("Set-Cookie"); if (cookie == null || cookie.size() == 0) { result = false; LogUtil.webPrintf("?!"); } else { LogUtil.webPrintf("??!"); LogUtil.debugPrintf("cookie====" + cookie); LogUtil.debugPrintf("Location :" + loginConn.getURL().toString()); setCookies(cookie); LogUtil.webPrintf("?..."); String payurl = getPayKey(loginConn, "db"); LogUtil.webPrintf("??"); if (payurl != null && !payurl.equals("")) { LogUtil.debugPrintf("?url:" + payurl); LogUtil.webPrintf("..."); pay(payurl); LogUtil.webPrintf("?"); } else { LogUtil.webPrintf("?"); LogUtil.debugPrintf("?url"); } } return result; }
From source file:com.dao.ShopThread.java
private boolean doJSShop() throws Exception { LogUtil.debugPrintf("?----------->"); // loadCookie(); boolean result = true; LogUtil.webPrintf("??..."); String postParams = addJSDynamicParams(); LogUtil.webPrintf("???"); LogUtil.webPrintf("?..."); HttpURLConnection loginConn = getHttpPostConn(this.jsshopurl); loginConn.setRequestProperty("Content-Length", Integer.toString(postParams.length())); LogUtil.debugPrintf("?HEADER===" + loginConn.getRequestProperties()); DataOutputStream wr = new DataOutputStream(loginConn.getOutputStream()); wr.writeBytes(postParams);/*from w w w . j a v a2s. c o m*/ wr.flush(); wr.close(); int responseCode = loginConn.getResponseCode(); LogUtil.debugPrintf("\nSending 'POST' request to URL : " + this.jsshopurl); LogUtil.debugPrintf("Post parameters : " + postParams); LogUtil.debugPrintf("Response Code : " + responseCode); Map<String, List<String>> header = loginConn.getHeaderFields(); LogUtil.debugPrintf("??HEADER===" + header); List<String> cookie = header.get("Set-Cookie"); if (cookie == null || cookie.size() == 0) { result = false; LogUtil.webPrintf("?!"); } else { LogUtil.webPrintf("??!"); LogUtil.debugPrintf("cookie====" + cookie); LogUtil.debugPrintf("Location :" + loginConn.getURL().toString()); setCookies(cookie); LogUtil.webPrintf("?..."); String payurl = getPayKey(loginConn, "js"); LogUtil.webPrintf("??"); if (payurl != null && !payurl.equals("")) { LogUtil.debugPrintf("?url:" + payurl); LogUtil.webPrintf("..."); pay(payurl); LogUtil.webPrintf("?"); } else { LogUtil.webPrintf("?"); LogUtil.debugPrintf("?url"); } } LogUtil.debugPrintf("??----------->"); // System.out.println(list.toHtml()); return result; }
From source file:it.unimi.dsi.sux4j.io.ChunkedHashStore.java
/** Closes this store, disposing all associated resources. * //from w w w . ja v a 2 s .com */ public void close() { if (!closed) { closed = true; for (DataOutputStream d : dos) try { d.close(); } catch (IOException e) { throw new RuntimeException(e); } for (File f : file) f.delete(); } }
From source file:com.dao.ShopThread.java
private void pay(String payurl) { LogUtil.debugPrintf("----------->"); try {//from w w w . j a v a2 s. c o m String postParams = getPayDynamicParams(payurl); HttpsURLConnection loginConn = getHttpSConn(payurl, "POST", Integer.toString(postParams.length())); if (null != this.cookies) { loginConn.addRequestProperty("Cookie", GenericUtil.cookieFormat(this.cookies)); } LogUtil.debugPrintf("HEADER===" + loginConn.getRequestProperties()); DataOutputStream wr = new DataOutputStream(loginConn.getOutputStream()); wr.writeBytes(postParams); wr.flush(); wr.close(); int responseCode = loginConn.getResponseCode(); LogUtil.debugPrintf("\nSending 'POST' request to URL : " + payurl); LogUtil.debugPrintf("Post parameters :" + postParams); LogUtil.debugPrintf("Response Code : " + responseCode); Map<String, List<String>> header = loginConn.getHeaderFields(); LogUtil.debugPrintf("conn.getHeaderFields():" + header); BufferedReader in = new BufferedReader(new InputStreamReader(loginConn.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(2000); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); String payresponse = response.toString(); LogUtil.debugPrintf("payresponse:" + payresponse); List<String> cookie = header.get("Set-Cookie"); String loginInfo; if (responseCode != 302) { LogUtil.debugPrintf("----------->"); loginInfo = ""; } else { LogUtil.debugPrintf("?----------->"); if (null != cookie && cookie.size() > 0) { LogUtil.debugPrintf("cookie====" + cookie); setCookies(cookie); } loginInfo = "?"; } LogUtil.webPrintf(loginInfo); } catch (Exception e) { e.printStackTrace(); } }
From source file:ioc.wiki.processingmanager.http.HttpFileSender.java
/** * Prepara la comanda a enviar al servidor, l'envia i rep la resposta en un string. * Cont informaci sobre el xit de guardar el fitxer al servidor. * @return Retorna un string amb la resposta del servidor. *///w w w . ja v a 2 s .c o m @Override public String sendCommand() { super.prepareCommand(); try { ((HttpURLConnection) urlConnection).setRequestMethod(REQUEST_METHOD); urlConnection.setRequestProperty(PROPERTY_CONTENT_TYPE, content_type + boundary); DataOutputStream request = new DataOutputStream(urlConnection.getOutputStream()); //Capalera fitxer request.writeBytes(twoHyphens + boundary + crlf); request.writeBytes(contentDispositionFile + quote + this.destFilename + quote + crlf); request.writeBytes(contentTypeFile + crlf); request.writeBytes(contentTransferEncodingFile + crlf); request.writeBytes(crlf); //IMAGE String base64Image = Base64.encodeBase64String(this.image); request.writeBytes(base64Image); //Tancament fitxer request.writeBytes(crlf); request.writeBytes(twoHyphens + boundary + twoHyphens + crlf); request.flush(); request.close(); } catch (IOException ex) { throw new ProcessingRtURLException(ex); } return super.receiveResponse(); }
From source file:com.pearson.pdn.learningstudio.core.AbstractService.java
/** * Performs HTTP operations using the selected authentication method * //from w w w .ja va 2 s. c om * @param extraHeaders Extra headers to include in the request * @param method The HTTP Method to user * @param relativeUrl The URL after .com (/me) * @param body The body of the message * @return Output in the preferred data format * @throws IOException */ protected Response doMethod(Map<String, String> extraHeaders, HttpMethod method, String relativeUrl, String body) throws IOException { if (body == null) { body = ""; } // append .xml extension when XML data format enabled. if (dataFormat == DataFormat.XML) { logger.debug("Using XML extension on route"); String queryString = ""; int queryStringIndex = relativeUrl.indexOf('?'); if (queryStringIndex != -1) { queryString = relativeUrl.substring(queryStringIndex); relativeUrl = relativeUrl.substring(0, queryStringIndex); } String compareUrl = relativeUrl.toLowerCase(); if (!compareUrl.endsWith(".xml")) { relativeUrl += ".xml"; } if (queryStringIndex != -1) { relativeUrl += queryString; } } final String fullUrl = API_DOMAIN + relativeUrl; if (logger.isDebugEnabled()) { logger.debug("REQUEST - Method: " + method.name() + ", URL: " + fullUrl + ", Body: " + body); } URL url = new URL(fullUrl); Map<String, String> oauthHeaders = getOAuthHeaders(method, url, body); if (oauthHeaders == null) { throw new RuntimeException("Authentication method not selected. SEE useOAuth# methods"); } if (extraHeaders != null) { for (String key : extraHeaders.keySet()) { if (!oauthHeaders.containsKey(key)) { oauthHeaders.put(key, extraHeaders.get(key)); } else { throw new RuntimeException("Extra headers can not include OAuth headers"); } } } HttpsURLConnection request = (HttpsURLConnection) url.openConnection(); try { request.setRequestMethod(method.toString()); Set<String> oauthHeaderKeys = oauthHeaders.keySet(); for (String oauthHeaderKey : oauthHeaderKeys) { request.addRequestProperty(oauthHeaderKey, oauthHeaders.get(oauthHeaderKey)); } request.addRequestProperty("User-Agent", getServiceIdentifier()); if ((method == HttpMethod.POST || method == HttpMethod.PUT) && body.length() > 0) { if (dataFormat == DataFormat.XML) { request.setRequestProperty("Content-Type", "application/xml"); } else { request.setRequestProperty("Content-Type", "application/json"); } request.setRequestProperty("Content-Length", String.valueOf(body.getBytes("UTF-8").length)); request.setDoOutput(true); DataOutputStream out = new DataOutputStream(request.getOutputStream()); try { out.writeBytes(body); out.flush(); } finally { out.close(); } } Response response = new Response(); response.setMethod(method.toString()); response.setUrl(url.toString()); response.setStatusCode(request.getResponseCode()); response.setStatusMessage(request.getResponseMessage()); response.setHeaders(request.getHeaderFields()); InputStream inputStream = null; if (response.getStatusCode() < ResponseStatus.BAD_REQUEST.code()) { inputStream = request.getInputStream(); } else { inputStream = request.getErrorStream(); } boolean isBinary = false; if (inputStream != null) { StringBuilder responseBody = new StringBuilder(); String contentType = request.getContentType(); if (contentType != null) { if (!contentType.startsWith("text/") && !contentType.startsWith("application/xml") && !contentType.startsWith("application/json")) { // assume binary isBinary = true; inputStream = new Base64InputStream(inputStream, true); // base64 encode } } BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")); try { String line = null; while ((line = bufferedReader.readLine()) != null) { responseBody.append(line); } } finally { bufferedReader.close(); } response.setContentType(contentType); if (isBinary) { String content = responseBody.toString(); if (content.length() == 0) { response.setBinaryContent(new byte[0]); } else { response.setBinaryContent(Base64.decodeBase64(responseBody.toString())); } } else { response.setContent(responseBody.toString()); } } if (logger.isDebugEnabled()) { if (isBinary) { logger.debug("RESPONSE - binary response omitted"); } else { logger.debug("RESPONSE - " + response.toString()); } } return response; } finally { request.disconnect(); } }
From source file:com.proofpoint.zookeeper.io.TempLocalDirectory.java
public TempFileBackedOutputStream newTempFileBackedOutputStream(String destinationPath) throws IOException { final File tempFile = newFile(); final File destinationFile = new File(destinationPath); final DataOutputStream tempFileOutputStream = new DataOutputStream( new BufferedOutputStream(new FileOutputStream(tempFile))); return new TempFileBackedOutputStream() { @Override/*from w ww .ja v a 2 s . c o m*/ public DataOutputStream getStream() { return tempFileOutputStream; } @Override public void commit() throws IOException { close(true); } @Override public void release() throws IOException { close(false); } private void close(boolean upload) throws IOException { if (isOpen) { isOpen = false; tempFileOutputStream.close(); if (upload) { if (!tempFile.renameTo(destinationFile)) { throw new IOException( "Could not rename " + tempFile.getPath() + " to " + destinationFile.getPath()); } } else { deleteFile(tempFile); } } } private boolean isOpen = true; }; }
From source file:com.intacct.ws.APISession.java
/** * You won't normally use this function, but if you just want to pass a fully constructed XML document * to Intacct, then use this function.//from w w w . ja va 2 s . c om * * @param String body a Valid XML string * @param String endPoint URL to post the XML to * * @throws exception * @return String the raw XML returned by Intacct */ public static String execute(String body, String endpoint) throws IOException { StringBuffer response = null; HttpURLConnection connection = null; // Create connection URL url = new URL(endpoint); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", "" + Integer.toString(body.getBytes().length)); connection.setRequestProperty("Content-Language", "en-US"); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); //Send request DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); /* wr.writeBytes ("fName=" + URLEncoder.encode("???", "UTF-8") + body + "&lName=" + URLEncoder.encode("???", "UTF-8")); */ wr.writeBytes("xmlrequest=" + URLEncoder.encode(body, "UTF-8")); wr.flush(); wr.close(); //Get Response InputStream is = connection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; response = new StringBuffer(); while ((line = rd.readLine()) != null) { response.append(line); response.append('\r'); } rd.close(); if (connection != null) { connection.disconnect(); } return response.toString(); }
From source file:com.webkey.Ipc.java
public void comBinAuth(String turl, String postData) { readAuthKey();//from w w w. j a va2 s. c o m try { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(_context); port = prefs.getString("port", "80"); Socket s = new Socket("127.0.0.1", Integer.parseInt(port)); //outgoing stream redirect to socket DataOutputStream dataOutputStream = new DataOutputStream(s.getOutputStream()); byte[] utf = postData.getBytes("UTF-8"); dataOutputStream.writeBytes("POST /" + authKey + turl + " HTTP/1.1\r\n" + "Host: 127.0.0.1\r\n" + "Connection: close\r\n" + "Content-Length: " + Integer.toString(utf.length) + "\r\n\r\n"); dataOutputStream.write(utf, 0, utf.length); dataOutputStream.flush(); dataOutputStream.close(); s.close(); } catch (IOException e1) { //e1.printStackTrace(); } /* // Log.d(TAG,"post data"); String target = "http://127.0.0.1:"+port+"/"+authKey+turl; //Log.d(TAG,target); URL url = new URL(target); URLConnection conn = url.openConnection(); // Set connection parameters. conn.setDoInput (true); conn.setDoOutput (true); conn.setUseCaches (false); //Make server believe we are form data... conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); DataOutputStream out = new DataOutputStream (conn.getOutputStream ()); // Write out the bytes of the content string to the stream. out.writeBytes(postData); out.flush (); out.close (); // Read response BufferedReader in = new BufferedReader (new InputStreamReader(conn.getInputStream ())); String temp; String response = null; while ((temp = in.readLine()) != null){ response += temp + "\n"; } temp = null; in.close (); System.out.println("Server response:\n'" + response + "'"); }catch(Exception e){ Log.d(TAG,e.toString()); } */ }