List of usage examples for java.io DataOutputStream flush
public void flush() throws IOException
From source file:Main.java
@SuppressWarnings("resource") public static String post(String targetUrl, Map<String, String> params, String file, byte[] data) { Logd(TAG, "Starting post..."); String html = ""; Boolean cont = true;// w w w .j av a 2 s. c o m URL url = null; try { url = new URL(targetUrl); } catch (MalformedURLException e) { Log.e(TAG, "Invalid url: " + targetUrl); cont = false; throw new IllegalArgumentException("Invalid url: " + targetUrl); } if (cont) { if (!targetUrl.startsWith("https") || gVALID_SSL.equals("true")) { HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.STRICT_HOSTNAME_VERIFIER; HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier); } else { // Create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { @Override public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { // TODO Auto-generated method stub } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { // TODO Auto-generated method stub } } }; // Install the all-trusting trust manager SSLContext sc; try { sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); // Create all-trusting host name verifier HostnameVerifier allHostsValid = new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }; // Install the all-trusting host verifier HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid); } catch (NoSuchAlgorithmException e) { Logd(TAG, "Error: " + e.getLocalizedMessage()); } catch (KeyManagementException e) { Logd(TAG, "Error: " + e.getLocalizedMessage()); } } Logd(TAG, "Filename: " + file); Logd(TAG, "URL: " + targetUrl); HttpURLConnection connection = null; DataOutputStream outputStream = null; String pathToOurFile = file; String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = "*****"; int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1 * 1024; try { connection = (HttpURLConnection) url.openConnection(); // Allow Inputs & Outputs connection.setDoInput(true); connection.setDoOutput(true); connection.setUseCaches(false); //Don't use chunked post requests (nginx doesn't support requests without a Content-Length header) //connection.setChunkedStreamingMode(1024); // Enable POST method connection.setRequestMethod("POST"); setBasicAuthentication(connection, url); connection.setRequestProperty("Connection", "Keep-Alive"); connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); outputStream = new DataOutputStream(connection.getOutputStream()); //outputStream.writeBytes(twoHyphens + boundary + lineEnd); Iterator<Entry<String, String>> iterator = params.entrySet().iterator(); while (iterator.hasNext()) { Entry<String, String> param = iterator.next(); outputStream.writeBytes(twoHyphens + boundary + lineEnd); outputStream.writeBytes("Content-Disposition: form-data;" + "name=\"" + param.getKey() + "\"" + lineEnd + lineEnd); outputStream.write(param.getValue().getBytes("UTF-8")); outputStream.writeBytes(lineEnd); } String connstr = null; if (!file.equals("")) { FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile)); outputStream.writeBytes(twoHyphens + boundary + lineEnd); connstr = "Content-Disposition: form-data; name=\"upfile\";filename=\"" + pathToOurFile + "\"" + lineEnd; outputStream.writeBytes(connstr); outputStream.writeBytes(lineEnd); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; // Read file bytesRead = fileInputStream.read(buffer, 0, bufferSize); Logd(TAG, "File length: " + bytesAvailable); try { while (bytesRead > 0) { try { outputStream.write(buffer, 0, bufferSize); } catch (OutOfMemoryError e) { e.printStackTrace(); html = "Error: outofmemoryerror"; return html; } bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.read(buffer, 0, bufferSize); } } catch (Exception e) { Logd(TAG, "Error: " + e.getLocalizedMessage()); html = "Error: Unknown error"; return html; } outputStream.writeBytes(lineEnd); fileInputStream.close(); } else if (data != null) { outputStream.writeBytes(twoHyphens + boundary + lineEnd); connstr = "Content-Disposition: form-data; name=\"upfile\";filename=\"tmp\"" + lineEnd; outputStream.writeBytes(connstr); outputStream.writeBytes(lineEnd); bytesAvailable = data.length; Logd(TAG, "File length: " + bytesAvailable); try { outputStream.write(data, 0, data.length); } catch (OutOfMemoryError e) { e.printStackTrace(); html = "Error: outofmemoryerror"; return html; } catch (Exception e) { Logd(TAG, "Error: " + e.getLocalizedMessage()); html = "Error: Unknown error"; return html; } outputStream.writeBytes(lineEnd); } outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); // Responses from the server (code and message) int serverResponseCode = connection.getResponseCode(); String serverResponseMessage = connection.getResponseMessage(); Logd(TAG, "Server Response Code " + serverResponseCode); Logd(TAG, "Server Response Message: " + serverResponseMessage); if (serverResponseCode == 200) { InputStreamReader in = new InputStreamReader(connection.getInputStream()); BufferedReader br = new BufferedReader(in); String decodedString; while ((decodedString = br.readLine()) != null) { html += decodedString; } in.close(); } outputStream.flush(); outputStream.close(); outputStream = null; } catch (Exception ex) { // Exception handling html = "Error: Unknown error"; Logd(TAG, "Send file Exception: " + ex.getMessage()); } } if (html.startsWith("success:")) Logd(TAG, "Server returned: success:HIDDEN"); else Logd(TAG, "Server returned: " + html); return html; }
From source file:com.yeahka.android.lepos.Device.java
public ResultModel uploadFile(String filePath, String userName) { SimpleDateFormat dataFormat = new SimpleDateFormat("yyyyMMddHHmmss"); String nowDataStr = dataFormat.format(new Date()); String para = android.os.Build.MODEL + "_" + userName + "_" + nowDataStr + ".data"; // String para = "LG P970" + "_" + userName + "_" + nowDataStr + // ".data";/*from w ww .j a v a 2s.co m*/ para = URLEncoder.encode(para); para = para.replaceAll("\\+", "%20"); String strUrl = UPLOAD_FILE_SERVER_CGI + "?filename=" + para; String result = ""; try { InputStream is = new FileInputStream(filePath); String strLength = is.available() + ""; URL url = new URL(strUrl); // HttpURLConnection conn = (HttpURLConnection) url.openConnection(); HttpURLConnection conn = MyHttps.getHttpURLConnection(url); conn.setReadTimeout(10 * 1000); conn.setConnectTimeout(10 * 1000); conn.setDoInput(true); // ?? conn.setDoOutput(true); // ?? conn.setUseCaches(false); // ?? conn.setRequestMethod("POST"); // ? conn.setRequestProperty("Coentent_Length", strLength); conn.setRequestProperty("Content-Type", "application/octet-stream"); DataOutputStream dos = new DataOutputStream(conn.getOutputStream()); // StringBuffer sb = new StringBuffer(); // sb.append("p="); // dos.write(sb.toString().getBytes()); byte[] bytes = new byte[10240]; int len = 0; while ((len = is.read(bytes)) != -1) { // String xmlString = URLEncoder.encode(Base64.encode(bytes, 0, // len)); // byte[] sendData = xmlString.getBytes("UTF-8"); // dos.write(sendData, 0, sendData.length); dos.write(bytes, 0, len); } is.close(); dos.flush(); dos.close(); /** * ??? 200=? ????? */ int res = conn.getResponseCode(); if (res == 200) { InputStream input = conn.getInputStream(); StringBuffer sb1 = new StringBuffer(); int ss; while ((ss = input.read()) != -1) { sb1.append((char) ss); } result = sb1.toString(); } else { return new ResultModel(Device.TRANSACTION_NET_FAIL); } return new ResultModel(new String(result)); } catch (MalformedURLException e) { e.printStackTrace(); return new ResultModel(Device.TRANSACTION_NET_FAIL); } catch (IOException e) { e.printStackTrace(); return new ResultModel(Device.TRANSACTION_NET_FAIL); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return new ResultModel(Device.TRANSACTION_NET_FAIL); } catch (KeyManagementException e) { e.printStackTrace(); return new ResultModel(Device.TRANSACTION_NET_FAIL); } }
From source file:GifEncoder.java
public void encode(BufferedImage bufferedimage, DataOutputStream dataoutputstream, Hashtable hashtable) throws Exception { try {/*from www . java 2 s . c om*/ a = bufferedimage.getWidth(); g = bufferedimage.getHeight(); e = bufferedimage.getRGB(0, 0, a, g, null, 0, a); int i4 = 0; b = hashtable.get("encoding").toString(); if (b.equals("websafe")) { int ai[] = new int[256]; i = new int[256]; h = 8; int k1 = 0; int j; int j1 = j = 0; for (; j <= 255; j += 51) { for (int l = 0; l <= 255; l += 51) { for (int i1 = 0; i1 <= 255;) { i[j1] = (j << 16) + (l << 8) + i1; ai[k1++] = j1; i1 += 51; j1++; } } } if (f > 0) { int j4 = c[0]; int l1 = ((c[0] >> 16 & 0xff) + 25) / 51; int k2 = ((c[0] >> 8 & 0xff) + 25) / 51; int j3 = ((c[0] & 0xff) + 25) / 51; i4 = l1 * 36 + k2 * 6 + j3; for (j = 1; j < f; j++) { int i2 = ((c[j] >> 16 & 0xff) + 25) / 51; int l2 = ((c[j] >> 8 & 0xff) + 25) / 51; int k3 = ((c[j] & 0xff) + 25) / 51; ai[i2 * 36 + l2 * 6 + k3] = i4; } } j = 0; try { do { int i5 = e[j]; int j2 = ((i5 >> 16 & 0xff) + 25) / 51; int i3 = ((i5 >> 8 & 0xff) + 25) / 51; int l3 = ((i5 & 0xff) + 25) / 51; e[j++] = ai[j2 * 36 + i3 * 6 + l3]; } while (true); } catch (Exception exception1) { } } /*else if(b.equals("optimized")) { try { int k4 = Integer.parseInt(hashtable.get("colors").toString()); for(h = 1; k4 - 1 >> h > 0; h++) { } i = new int[1 << h]; CSelectiveQuant cselectivequant = new CSelectiveQuant(); for(int j5 = 0; j5 < e.length; j5++) { cselectivequant.addPixel(e[j5]); } boolean flag = f > 0; int k5 = flag ? 1 : 0; int ai1[] = cselectivequant.createPalette(k4 - k5); for(int l5 = 0; l5 < i.length; l5++) { try { i[l5] = ai1[l5 - k5]; } catch(ArrayIndexOutOfBoundsException arrayindexoutofboundsexception) { i[l5] = 0; } } if(flag) { i4 = 0; for(int i6 = 0; i6 < f; i6++) { cselectivequant.setIndex(c[i6], -1); } } for(int j6 = 0; j6 < e.length; j6++) { e[j6] = cselectivequant.getIndex(e[j6]) + k5; } } catch(NumberFormatException numberformatexception) { CmsLogger.logInfo("Parameter: 'colors' is malformated..."); return; } } */ dataoutputstream.write("GIF89a".getBytes()); dataoutputstream.writeByte(a); dataoutputstream.writeByte(a >> 8); dataoutputstream.writeByte(g); dataoutputstream.writeByte(g >> 8); dataoutputstream.writeByte(0xf0 | h - 1); dataoutputstream.writeByte(0); dataoutputstream.writeByte(0); int k = 0; try { do { int l4 = i[k++]; dataoutputstream.writeByte(l4 >> 16 & 0xff); dataoutputstream.writeByte(l4 >> 8 & 0xff); dataoutputstream.writeByte(l4 & 0xff); } while (true); } catch (Exception exception) { } if (f > 0) { dataoutputstream.writeByte(33); dataoutputstream.writeByte(249); dataoutputstream.writeByte(4); dataoutputstream.writeByte(1); dataoutputstream.writeByte(0); dataoutputstream.writeByte(0); dataoutputstream.writeByte(i4); dataoutputstream.writeByte(0); } dataoutputstream.writeByte(44); dataoutputstream.writeByte(0); dataoutputstream.writeByte(0); dataoutputstream.writeByte(0); dataoutputstream.writeByte(0); dataoutputstream.writeByte(a); dataoutputstream.writeByte(a >> 8); dataoutputstream.writeByte(g); dataoutputstream.writeByte(g >> 8); dataoutputstream.writeByte(0); dataoutputstream.writeByte(h); a(e, h, dataoutputstream); dataoutputstream.writeByte(59); dataoutputstream.flush(); return; } catch (Exception e) { } }
From source file:net.maizegenetics.analysis.imputation.FILLINImputationAccuracy.java
private void accuracyMAFOut() { DecimalFormat df = new DecimalFormat("0.########"); if (this.MAF != null && this.MAFClass != null) try {//from w w w. j av a 2 s . c o m String ext = FilenameUtils.getExtension(this.outFile); File outputFile = new File(this.outFile.replace(ext, "MAFAccuracy.txt")); DataOutputStream outStream = new DataOutputStream( new BufferedOutputStream(new FileOutputStream(outputFile))); outStream.writeBytes( "##\tMAFClass\tTotalSitesMasked\tTotalSitesCompared\tTotalPropUnimputed\tNumHets\tHetToMinor\tHetToMajor\tCorrectHet\tUnimpHet\tNumMinor\tMinorToMajor\tMinorToHet\tCorrectMinor\t" + "UnimpMinor\tNumMajor\tMajorToMinor\tMajorToHet\tCorrectMajor\tUnimputedMajor\tr2\n"); for (int i = 0; i < this.MAFClass.length; i++) { outStream .writeBytes("##TotalByImputed\t" + this.MAFClass[i] + "\t" + (this.mafAll[i][0][4] + this.mafAll[i][1][4] + this.mafAll[i][2][4]) + "\t" + (this.mafAll[i][0][4] + this.mafAll[i][1][4] + this.mafAll[i][2][4] - this.mafAll[i][0][3] - this.mafAll[i][1][3] - this.mafAll[i][2][3]) + "\t" + ((this.mafAll[i][0][3] + this.mafAll[i][1][3] + this.mafAll[i][2][3]) / (this.mafAll[i][0][4] + this.mafAll[i][1][4] + this.mafAll[i][2][4])) + "\t" + this.mafAll[i][0][4] + "\t" + this.mafAll[i][0][0] + "\t" + this.mafAll[i][0][1] + "\t" + this.mafAll[i][0][2] + "\t" + this.mafAll[i][0][3] + "\t" + this.mafAll[i][1][4] + "\t" + this.mafAll[i][1][0] + "\t" + this.mafAll[i][1][1] + "\t" + this.mafAll[i][1][2] + "\t" + this.mafAll[i][1][3] + "\t" + this.mafAll[i][2][4] + "\t" + this.mafAll[i][2][0] + "\t" + this.mafAll[i][2][1] + "\t" + this.mafAll[i][2][2] + "\t" + this.mafAll[i][2][3] + "\t" + pearsonR2(this.mafAll[i], false) + "\n"); } outStream.writeBytes( "#MAFClass,Minor=0,Het=1,Major=2;x is masked(known), y is predicted\nMAF\tx\ty\tN\tprop\n"); for (int i = 0; i < this.MAFClass.length; i++) { outStream.writeBytes(this.MAFClass[i] + "\t" + 0 + "\t" + 0 + "\t" + this.mafAll[i][0][0] + "\t" + df.format((this.mafAll[i][0][0]) / (this.mafAll[i][0][0] + this.mafAll[i][0][1] + this.mafAll[i][0][2])) + "\n" + this.MAFClass[i] + "\t" + 0 + "\t" + .5 + "\t" + this.mafAll[i][0][1] + "\t" + df.format((this.mafAll[i][0][1]) / (this.mafAll[i][0][0] + this.mafAll[i][0][1] + this.mafAll[i][0][2])) + "\n" + this.MAFClass[i] + "\t" + 0 + "\t" + 1 + "\t" + this.mafAll[i][0][2] + "\t" + df.format((this.mafAll[i][0][2]) / (this.mafAll[i][0][0] + this.mafAll[i][0][1] + this.mafAll[i][0][2])) + "\n" + this.MAFClass[i] + "\t" + .5 + "\t" + 0 + "\t" + this.mafAll[i][1][0] + "\t" + df.format((this.mafAll[i][1][0]) / (this.mafAll[i][1][0] + this.mafAll[i][1][1] + this.mafAll[i][1][2])) + "\n" + this.MAFClass[i] + "\t" + .5 + "\t" + .5 + "\t" + this.mafAll[i][1][1] + "\t" + df.format((this.mafAll[i][1][1]) / (this.mafAll[i][1][0] + this.mafAll[i][1][1] + this.mafAll[i][1][2])) + "\n" + this.MAFClass[i] + "\t" + .5 + "\t" + 1 + "\t" + this.mafAll[i][1][2] + "\t" + df.format((this.mafAll[i][1][2]) / (this.mafAll[i][1][0] + this.mafAll[i][1][1] + this.mafAll[i][1][2])) + "\n" + this.MAFClass[i] + "\t" + 1 + "\t" + 0 + "\t" + this.mafAll[i][2][0] + "\t" + df.format((this.mafAll[i][2][0]) / (this.mafAll[i][2][0] + this.mafAll[i][2][1] + this.mafAll[i][2][2])) + "\n" + this.MAFClass[i] + "\t" + 1 + "\t" + .5 + "\t" + this.mafAll[i][2][1] + "\t" + df.format((this.mafAll[i][2][1]) / (this.mafAll[i][2][0] + this.mafAll[i][2][1] + this.mafAll[i][2][2])) + "\n" + this.MAFClass[i] + "\t" + 1 + "\t" + 1 + "\t" + this.mafAll[i][2][2] + "\t" + df.format((this.mafAll[i][2][2]) / (this.mafAll[i][2][0] + this.mafAll[i][2][1] + this.mafAll[i][2][2])) + "\n"); } outStream.writeBytes("#Proportion unimputed:\n#MAF\tminor\thet\tmajor\n"); for (int i = 0; i < this.MAFClass.length; i++) { outStream.writeBytes("#" + this.MAFClass[i] + "\t" + this.mafAll[i][0][3] / this.mafAll[i][0][4] + "\t" + this.mafAll[i][1][3] / this.mafAll[i][1][4] + "\t" + this.mafAll[i][2][3] / this.mafAll[i][2][4] + "\n"); } outStream.flush(); outStream.close(); } catch (Exception e) { if (this.verboseOutput) System.out.println(e); } }
From source file:com.echopf.ECHOQuery.java
/** * Sends a HTTP request with optional request contents/parameters. * @param path a request url path//from www . j a v a 2 s. co m * @param httpMethod a request method (GET/POST/PUT/DELETE) * @param data request contents/parameters * @param multipart use multipart/form-data to encode the contents * @throws ECHOException */ public static InputStream requestRaw(String path, String httpMethod, JSONObject data, boolean multipart) throws ECHOException { final String secureDomain = ECHO.secureDomain; if (secureDomain == null) throw new IllegalStateException("The SDK is not initialized.Please call `ECHO.initialize()`."); String baseUrl = new StringBuilder("https://").append(secureDomain).toString(); String url = new StringBuilder(baseUrl).append("/").append(path).toString(); HttpsURLConnection httpClient = null; try { URL urlObj = new URL(url); StringBuilder apiUrl = new StringBuilder(baseUrl).append(urlObj.getPath()).append("/rest_api=1.0/"); // Append the QueryString contained in path boolean isContainQuery = urlObj.getQuery() != null; if (isContainQuery) apiUrl.append("?").append(urlObj.getQuery()); // Append the QueryString from data if (httpMethod.equals("GET") && data != null) { boolean firstItem = true; Iterator<?> iter = data.keys(); while (iter.hasNext()) { if (firstItem && !isContainQuery) { firstItem = false; apiUrl.append("?"); } else { apiUrl.append("&"); } String key = (String) iter.next(); String value = data.optString(key); apiUrl.append(key); apiUrl.append("="); apiUrl.append(value); } } URL urlConn = new URL(apiUrl.toString()); httpClient = (HttpsURLConnection) urlConn.openConnection(); } catch (IOException e) { throw new ECHOException(e); } final String appId = ECHO.appId; final String appKey = ECHO.appKey; final String accessToken = ECHO.accessToken; if (appId == null || appKey == null) throw new IllegalStateException("The SDK is not initialized.Please call `ECHO.initialize()`."); InputStream responseInputStream = null; try { httpClient.setRequestMethod(httpMethod); httpClient.addRequestProperty("X-ECHO-APP-ID", appId); httpClient.addRequestProperty("X-ECHO-APP-KEY", appKey); // Set access token if (accessToken != null && !accessToken.isEmpty()) httpClient.addRequestProperty("X-ECHO-ACCESS-TOKEN", accessToken); // Build content if (!httpMethod.equals("GET") && data != null) { httpClient.setDoOutput(true); httpClient.setChunkedStreamingMode(0); // use default chunk size if (multipart == false) { // application/json httpClient.addRequestProperty("CONTENT-TYPE", "application/json"); BufferedWriter wrBuffer = new BufferedWriter( new OutputStreamWriter(httpClient.getOutputStream())); wrBuffer.write(data.toString()); wrBuffer.close(); } else { // multipart/form-data final String boundary = "*****" + UUID.randomUUID().toString() + "*****"; final String twoHyphens = "--"; final String lineEnd = "\r\n"; final int maxBufferSize = 1024 * 1024 * 3; httpClient.setRequestMethod("POST"); httpClient.addRequestProperty("CONTENT-TYPE", "multipart/form-data; boundary=" + boundary); final DataOutputStream outputStream = new DataOutputStream(httpClient.getOutputStream()); try { JSONObject postData = new JSONObject(); postData.putOpt("method", httpMethod); postData.putOpt("data", data); new Object() { public void post(JSONObject data, List<String> currentKeys) throws JSONException, IOException { Iterator<?> keys = data.keys(); while (keys.hasNext()) { String key = (String) keys.next(); List<String> newKeys = new ArrayList<String>(currentKeys); newKeys.add(key); Object val = data.get(key); // convert JSONArray into JSONObject if (val instanceof JSONArray) { JSONArray array = (JSONArray) val; JSONObject val2 = new JSONObject(); for (Integer i = 0; i < array.length(); i++) { val2.putOpt(i.toString(), array.get(i)); } val = val2; } // build form-data name String name = ""; for (int i = 0; i < newKeys.size(); i++) { String key2 = newKeys.get(i); name += (i == 0) ? key2 : "[" + key2 + "]"; } if (val instanceof ECHOFile) { ECHOFile file = (ECHOFile) val; if (file.getLocalBytes() == null) continue; InputStream fileInputStream = new ByteArrayInputStream( file.getLocalBytes()); if (fileInputStream != null) { String mimeType = URLConnection .guessContentTypeFromName(file.getFileName()); // write header outputStream.writeBytes(twoHyphens + boundary + lineEnd); outputStream.writeBytes("Content-Disposition: form-data; name=\"" + name + "\"; filename=\"" + file.getFileName() + "\"" + lineEnd); outputStream.writeBytes("Content-Type: " + mimeType + lineEnd); outputStream.writeBytes("Content-Transfer-Encoding: binary" + lineEnd); outputStream.writeBytes(lineEnd); // write content int bytesAvailable, bufferSize, bytesRead; do { bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); byte[] buffer = new byte[bufferSize]; bytesRead = fileInputStream.read(buffer, 0, bufferSize); if (bytesRead <= 0) break; outputStream.write(buffer, 0, bufferSize); } while (true); fileInputStream.close(); outputStream.writeBytes(lineEnd); } } else if (val instanceof JSONObject) { this.post((JSONObject) val, newKeys); } else { String data2 = null; try { // in case of boolean boolean bool = data.getBoolean(key); data2 = bool ? "true" : ""; } catch (JSONException e) { // if the value is not a Boolean or the String "true" or "false". data2 = val.toString().trim(); } // write header outputStream.writeBytes(twoHyphens + boundary + lineEnd); outputStream.writeBytes( "Content-Disposition: form-data; name=\"" + name + "\"" + lineEnd); outputStream .writeBytes("Content-Type: text/plain; charset=UTF-8" + lineEnd); outputStream.writeBytes("Content-Length: " + data2.length() + lineEnd); outputStream.writeBytes(lineEnd); // write content byte[] bytes = data2.getBytes(); for (int i = 0; i < bytes.length; i++) { outputStream.writeByte(bytes[i]); } outputStream.writeBytes(lineEnd); } } } }.post(postData, new ArrayList<String>()); } catch (JSONException e) { throw new ECHOException(e); } finally { outputStream.writeBytes(twoHyphens + boundary + lineEnd); outputStream.flush(); outputStream.close(); } } } else { httpClient.addRequestProperty("CONTENT-TYPE", "application/json"); } if (httpClient.getResponseCode() != -1 /*== HttpURLConnection.HTTP_OK*/) { responseInputStream = httpClient.getInputStream(); } } catch (IOException e) { // get http response code int errorCode = -1; try { errorCode = httpClient.getResponseCode(); } catch (IOException e1) { throw new ECHOException(e1); } // get error contents JSONObject responseObj; try { String jsonStr = ECHOQuery.getResponseString(httpClient.getErrorStream()); responseObj = new JSONObject(jsonStr); } catch (JSONException e1) { if (errorCode == 404) { throw new ECHOException(ECHOException.RESOURCE_NOT_FOUND, "Resource not found."); } throw new ECHOException(ECHOException.INVALID_JSON_FORMAT, "Invalid JSON format."); } // if (responseObj != null) { int code = responseObj.optInt("error_code"); String message = responseObj.optString("error_message"); if (code != 0 || !message.equals("")) { JSONObject details = responseObj.optJSONObject("error_details"); if (details == null) { throw new ECHOException(code, message); } else { throw new ECHOException(code, message, details); } } } throw new ECHOException(e); } return responseInputStream; }
From source file:com.yeahka.android.lepos.Device.java
/** * ?/*from w ww.java2s.c o m*/ * * @param actionUrl ? * @param file * @return * @author "Char" * @create_date 2015-8-18 */ private ResultModel sendPhotoToQuickenLoansWebServer(String actionUrl, File file) { try { int TIME_OUT = 10 * 1000; // String CHARSET = "utf-8"; // ? String result = null; String BOUNDARY = UUID.randomUUID().toString(); // ?? String PREFIX = "--", LINE_END = "\r\n"; String CONTENT_TYPE = "multipart/form-data"; // URL url = new URL(actionUrl); // HttpURLConnection conn = (HttpURLConnection) url.openConnection(); HttpURLConnection conn = MyHttps.getHttpURLConnection(url); conn.setReadTimeout(TIME_OUT); conn.setConnectTimeout(TIME_OUT); conn.setDoInput(true); // ?? conn.setDoOutput(true); // ?? conn.setUseCaches(false); // ?? conn.setRequestMethod("POST"); // ? conn.setRequestProperty("Charset", CHARSET); // ? conn.setRequestProperty("connection", "keep-alive"); conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY); if (file != null) { /** * ? */ DataOutputStream dos = new DataOutputStream(conn.getOutputStream()); StringBuffer sb = new StringBuffer(); sb.append(PREFIX); sb.append(BOUNDARY); sb.append(LINE_END); /** * ?? name???key ?key ?? * filename?????? */ sb.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"" + LINE_END); sb.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINE_END); sb.append(LINE_END); dos.write(sb.toString().getBytes()); InputStream is = new FileInputStream(file); byte[] bytes = new byte[1024]; int len = 0; while ((len = is.read(bytes)) != -1) { dos.write(bytes, 0, len); } is.close(); dos.write(LINE_END.getBytes()); byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes(); dos.write(end_data); dos.flush(); } // ?? int res = conn.getResponseCode(); InputStream in = conn.getInputStream(); InputStreamReader isReader = new InputStreamReader(in); BufferedReader bufReader = new BufferedReader(isReader); String line = null; String data = ""; StringBuilder sb2 = new StringBuilder(); if (res == 200) { while ((line = bufReader.readLine()) != null) { data += line; } } else { return new ResultModel(Device.TRANSACTION_NET_FAIL); } in.close(); conn.disconnect(); return new ResultModel(data); } catch (MalformedURLException e) { return new ResultModel(Device.TRANSACTION_NET_FAIL, e); } catch (IOException e) { return new ResultModel(Device.TRANSACTION_NET_FAIL, e); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return new ResultModel(Device.TRANSACTION_NET_FAIL, e); } catch (KeyManagementException e) { e.printStackTrace(); return new ResultModel(Device.TRANSACTION_NET_FAIL, e); } }
From source file:com.ning.arecibo.util.timeline.times.TimelineCoderImpl.java
private byte[] combineTimelines(final List<byte[]> timesList) { final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); final DataOutputStream dataStream = new DataOutputStream(outputStream); try {// w w w . j av a 2 s .c o m int lastTime = 0; int lastDelta = 0; int repeatCount = 0; int chunkCounter = 0; for (byte[] times : timesList) { final ByteArrayInputStream byteStream = new ByteArrayInputStream(times); final DataInputStream byteDataStream = new DataInputStream(byteStream); int byteCursor = 0; while (true) { // Part 1: Get the opcode, and come up with newTime, newCount and newDelta final int opcode = byteDataStream.read(); if (opcode == -1) { break; } byteCursor++; int newTime = 0; int newCount = 0; int newDelta = 0; boolean useNewDelta = false; boolean nonDeltaTime = false; if (opcode == TimelineOpcode.FULL_TIME.getOpcodeIndex()) { newTime = byteDataStream.readInt(); if (newTime < lastTime) { log.warn( "In TimelineCoder.combineTimeLines(), the fulltime read is %d, but the lastTime is %d; setting newTime to lastTime", newTime, lastTime); newTime = lastTime; } byteCursor += 4; if (lastTime == 0) { writeTime(0, newTime, dataStream); lastTime = newTime; lastDelta = 0; repeatCount = 0; continue; } else if (newTime - lastTime <= TimelineOpcode.MAX_DELTA_TIME) { newDelta = newTime - lastTime; useNewDelta = true; newCount = 1; } else { nonDeltaTime = true; } } else if (opcode <= TimelineOpcode.MAX_DELTA_TIME) { newTime = lastTime + opcode; newDelta = opcode; useNewDelta = true; newCount = 1; } else if (opcode == TimelineOpcode.REPEATED_DELTA_TIME_BYTE.getOpcodeIndex()) { newCount = byteDataStream.read(); newDelta = byteDataStream.read(); useNewDelta = true; byteCursor += 2; if (lastTime != 0) { newTime = lastTime + newDelta * newCount; } else { throw new IllegalStateException(String.format( "In TimelineCoder.combineTimelines, lastTime is 0 byte opcode = %d, byteCursor %d, chunkCounter %d, chunk %s", opcode, byteCursor, chunkCounter, new String(Hex.encodeHex(times)))); } } else if (opcode == TimelineOpcode.REPEATED_DELTA_TIME_SHORT.getOpcodeIndex()) { newCount = byteDataStream.readUnsignedShort(); newDelta = byteDataStream.read(); useNewDelta = true; byteCursor += 3; if (lastTime != 0) { newTime = lastTime + newDelta * newCount; } } else { throw new IllegalStateException(String.format( "In TimelineCoder.combineTimelines, Unrecognized byte opcode = %d, byteCursor %d, chunkCounter %d, chunk %s", opcode, byteCursor, chunkCounter, new String(Hex.encodeHex(times)))); } // Part 2: Combine existing state represented in lastTime, lastDelta and repeatCount with newTime, newCount and newDelta if (lastTime == 0) { log.error("In combineTimelines(), lastTime is 0; byteCursor %d, chunkCounter %d, times %s", byteCursor, chunkCounter, new String(Hex.encodeHex(times))); } else if (repeatCount > 0) { if (lastDelta == newDelta && newCount > 0) { repeatCount += newCount; lastTime = newTime; } else { writeRepeatedDelta(lastDelta, repeatCount, dataStream); if (useNewDelta) { lastDelta = newDelta; repeatCount = newCount; lastTime = newTime; } else { writeTime(lastTime, newTime, dataStream); lastTime = newTime; lastDelta = 0; repeatCount = 0; } } } else if (nonDeltaTime) { writeTime(lastTime, newTime, dataStream); lastTime = newTime; lastDelta = 0; repeatCount = 0; } else if (lastDelta == 0) { lastTime = newTime; repeatCount = newCount; lastDelta = newDelta; } } chunkCounter++; } if (repeatCount > 0) { writeRepeatedDelta(lastDelta, repeatCount, dataStream); } dataStream.flush(); return outputStream.toByteArray(); } catch (Exception e) { log.error(e, "In combineTimesLines(), exception combining timelines"); return new byte[0]; } }
From source file:com.viettel.hqmc.DAO.FilesDAO.java
protected static OCSPResp getOCSPResponse(String serviceUrl, OCSPReq request) throws Exception { try {/* w w w .jav a 2 s . c om*/ //Todo: Use http client. byte[] array = request.getEncoded(); if (serviceUrl.startsWith("http")) { HttpURLConnection con; URL url = new URL(serviceUrl); con = (HttpURLConnection) url.openConnection(); con.setRequestProperty("Content-Type", "application/ocsp-request"); con.setRequestProperty("Accept", "application/ocsp-response"); con.setDoOutput(true); OutputStream out = con.getOutputStream(); DataOutputStream dataOut = new DataOutputStream(new BufferedOutputStream(out)); dataOut.write(array); dataOut.flush(); dataOut.close(); //Check errors in response: if (con.getResponseCode() / 100 != 2) { throw new Exception( "Error getting ocsp response." + "Response code is " + con.getResponseCode()); } //Get Response InputStream in = (InputStream) con.getContent(); return new OCSPResp(in); } else { throw new Exception("Only http is supported for ocsp calls"); } } catch (IOException ex) { LogUtil.addLog(ex);//binhnt sonar a160901 throw new Exception("Cannot get ocspResponse from url: " + serviceUrl, ex); } }