List of usage examples for java.net HttpURLConnection setFixedLengthStreamingMode
public void setFixedLengthStreamingMode(long contentLength)
From source file:com.google.ytd.SubmitActivity.java
private String gdataUpload(File file, String uploadUrl, int start, int end) throws IOException { int chunk = end - start + 1; int bufferSize = 1024; byte[] buffer = new byte[bufferSize]; FileInputStream fileStream = new FileInputStream(file); HttpURLConnection urlConnection = getGDataUrlConnection(uploadUrl); // some mobile proxies do not support PUT, using X-HTTP-Method-Override to get around this problem if (isFirstRequest()) { Log.d(LOG_TAG, String.format("Uploaded %d bytes so far, using POST method.", (int) totalBytesUploaded)); urlConnection.setRequestMethod("POST"); } else {/*from ww w . j a va 2 s . c om*/ urlConnection.setRequestMethod("POST"); urlConnection.setRequestProperty("X-HTTP-Method-Override", "PUT"); Log.d(LOG_TAG, String.format("Uploaded %d bytes so far, using POST with X-HTTP-Method-Override PUT method.", (int) totalBytesUploaded)); } urlConnection.setDoOutput(true); urlConnection.setFixedLengthStreamingMode(chunk); urlConnection.setRequestProperty("Content-Type", "video/3gpp"); urlConnection.setRequestProperty("Content-Range", String.format("bytes %d-%d/%d", start, end, file.length())); Log.d(LOG_TAG, urlConnection.getRequestProperty("Content-Range")); OutputStream outStreamWriter = urlConnection.getOutputStream(); fileStream.skip(start); int bytesRead; int totalRead = 0; while ((bytesRead = fileStream.read(buffer, 0, bufferSize)) != -1) { outStreamWriter.write(buffer, 0, bytesRead); totalRead += bytesRead; this.totalBytesUploaded += bytesRead; double percent = (totalBytesUploaded / currentFileSize) * 99; /* Log.d(LOG_TAG, String.format( "fileSize=%f totalBytesUploaded=%f percent=%f", currentFileSize, totalBytesUploaded, percent)); */ dialog.setProgress((int) percent); if (totalRead == (end - start + 1)) { break; } } outStreamWriter.close(); int responseCode = urlConnection.getResponseCode(); Log.d(LOG_TAG, "responseCode=" + responseCode); Log.d(LOG_TAG, "responseMessage=" + urlConnection.getResponseMessage()); try { if (responseCode == 201) { String videoId = parseVideoId(urlConnection.getInputStream()); String latLng = null; if (this.videoLocation != null) { latLng = String.format("lat=%f lng=%f", this.videoLocation.getLatitude(), this.videoLocation.getLongitude()); } submitToYtdDomain(this.ytdDomain, this.assignmentId, videoId, this.youTubeName, SubmitActivity.this.clientLoginToken, getTitleText(), getDescriptionText(), this.dateTaken, latLng, this.tags); dialog.setProgress(100); return videoId; } else if (responseCode == 200) { Set<String> keySet = urlConnection.getHeaderFields().keySet(); String keys = urlConnection.getHeaderFields().keySet().toString(); Log.d(LOG_TAG, String.format("Headers keys %s.", keys)); for (String key : keySet) { Log.d(LOG_TAG, String.format("Header key %s value %s.", key, urlConnection.getHeaderField(key))); } Log.w(LOG_TAG, "Received 200 response during resumable uploading"); throw new IOException(String.format("Unexpected response code : responseCode=%d responseMessage=%s", responseCode, urlConnection.getResponseMessage())); } else { if ((responseCode + "").startsWith("5")) { String error = String.format("responseCode=%d responseMessage=%s", responseCode, urlConnection.getResponseMessage()); Log.w(LOG_TAG, error); // TODO - this exception will trigger retry mechanism to kick in // TODO - even though it should not, consider introducing a new type so // TODO - resume does not kick in upon 5xx throw new IOException(error); } else if (responseCode == 308) { // OK, the chunk completed succesfully Log.d(LOG_TAG, String.format("responseCode=%d responseMessage=%s", responseCode, urlConnection.getResponseMessage())); } else { // TODO - this case is not handled properly yet Log.w(LOG_TAG, String.format("Unexpected return code : %d %s while uploading :%s", responseCode, urlConnection.getResponseMessage(), uploadUrl)); } } } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } return null; }
From source file:ca.osmcanada.osvuploadr.JPMain.java
private void SendAuthTokens(String accessToken, String accessSecret) { try {/*w w w. j a v a 2 s . com*/ URL url = new URL(URL_ACCESS); URLConnection con = url.openConnection(); HttpURLConnection http = (HttpURLConnection) con; http.setRequestMethod("POST"); // PUT is another valid option http.setDoOutput(true); Map<String, String> arguments = new HashMap<>(); arguments.put("request_token", accessToken); arguments.put("secret_token", accessSecret); System.out.println("accessToken:" + accessToken + "|secret token:" + accessSecret); StringJoiner sj = new StringJoiner("&"); for (Map.Entry<String, String> entry : arguments.entrySet()) sj.add(URLEncoder.encode(entry.getKey(), "UTF-8") + "=" + URLEncoder.encode(entry.getValue(), "UTF-8")); byte[] out = sj.toString().getBytes(StandardCharsets.UTF_8); int length = out.length; http.setFixedLengthStreamingMode(length); http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); http.connect(); try (OutputStream os = http.getOutputStream()) { os.write(out); os.close(); } InputStream is = http.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte buf[] = new byte[1024]; int letti; while ((letti = is.read(buf)) > 0) baos.write(buf, 0, letti); String data = new String(baos.toByteArray()); http.disconnect(); } catch (Exception ex) { Logger.getLogger(JPMain.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.docdoku.cli.helpers.FileHelper.java
public String uploadFile(File pLocalFile, String pURL) throws IOException, LoginException, NoSuchAlgorithmException { InputStream in = null;/* ww w. j a va 2 s.c o m*/ OutputStream out = null; HttpURLConnection conn = null; try { //Hack for NTLM proxy //perform a head method to negociate the NTLM proxy authentication URL url = new URL(pURL); System.out.println("Uploading file: " + pLocalFile.getName() + " to " + url.getHost()); performHeadHTTPMethod(url); conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setUseCaches(false); conn.setAllowUserInteraction(true); conn.setRequestProperty("Connection", "Keep-Alive"); byte[] encoded = Base64.encodeBase64((login + ":" + password).getBytes("ISO-8859-1")); conn.setRequestProperty("Authorization", "Basic " + new String(encoded, "US-ASCII")); String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = "--------------------" + Long.toString(System.currentTimeMillis(), 16); byte[] header = (twoHyphens + boundary + lineEnd + "Content-Disposition: form-data; name=\"upload\";" + " filename=\"" + pLocalFile + "\"" + lineEnd + lineEnd).getBytes("ISO-8859-1"); byte[] footer = (lineEnd + twoHyphens + boundary + twoHyphens + lineEnd).getBytes("ISO-8859-1"); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); //conn.setRequestProperty("Content-Length",len + ""); long len = header.length + pLocalFile.length() + footer.length; conn.setFixedLengthStreamingMode((int) len); out = new BufferedOutputStream(conn.getOutputStream(), BUFFER_CAPACITY); out.write(header); byte[] data = new byte[CHUNK_SIZE]; int length; MessageDigest md = MessageDigest.getInstance("MD5"); in = new ConsoleProgressMonitorInputStream(pLocalFile.length(), new DigestInputStream( new BufferedInputStream(new FileInputStream(pLocalFile), BUFFER_CAPACITY), md)); while ((length = in.read(data)) != -1) { out.write(data, 0, length); } out.write(footer); out.flush(); manageHTTPCode(conn); byte[] digest = md.digest(); return Base64.encodeBase64String(digest); } finally { if (out != null) out.close(); if (in != null) in.close(); if (conn != null) conn.disconnect(); } }
From source file:watch.oms.omswatch.actioncenter.helpers.WatchPostAsyncTaskHelper.java
/** * @param//from ww w . j a va 2 s .com * @param * @return */ /*private String processPostResponse(String clientTableName, HttpEntity httpEntity){ String response = null; String jsonString = null; JSONObject responseJSONObject = null; try{ jsonString = EntityUtils.toString(httpEntity); JSONObject responseWebServiceJSON = new JSONObject(jsonString); responseJSONObject = responseWebServiceJSON .getJSONObject(OMSMessages.RESPONSE_STRING .getValue()); }catch(JSONException jex){ if(jex!=null && jex.getMessage().contains("No value for "+(OMSMessages.RESPONSE_STRING.getValue()))){ Log.d(TAG, "response key is not present. Assuming json response contains data set"); // This changes are for Oasis Project. # Start DataParser dataParser = new DataParser(context); // This changes are for Oasis Project. # End dataParser.parseAndUpdate(jsonString); response = "BLPostSuccess"; }else{ Log.e(TAG, "Exception occurred while reading the json response. Error is:" + jex.getMessage()); } return response = OMSMessages.ACTION_CENTER_FAILURE.getValue(); } catch (ParseException e) { Log.e(TAG, "Exception occurred while parsing the json response. Error is:" + e.getMessage()); } catch (IOException e) { Log.e(TAG, "IO Exception occurred while parsing the json response. Error is:" + e.getMessage()); } try{ String code = responseJSONObject .getString(OMSMessages.CODE.getValue()); if (code.equals(OMSMessages.DEFAULT_JSON_CODE.getValue())) { Log.i(TAG, "Response Message :" + responseJSONObject .getString(OMSMessages.MESSAGE .getValue())); double processedModifiedDate = responseJSONObject .getDouble(OMSMessages.PROCESSED_DATE .getValue()); parseJSONObject(jsonPayLoad.toString(), OMSDatabaseConstants.STATUS_TYPE_FINISHED, processedModifiedDate); progressString = context.getResources().getString( R.string.post_success); response = "BLPostSuccess"; } else { Log.e(TAG, "Response Message :" + responseJSONObject .getString(OMSMessages.MESSAGE .getValue())); try { Log.e(TAG, "Response Message Additional:" + responseJSONObject .getString(OMSMessages.ERROR_ADDITIONAL_MESSAGE .getValue())); } catch (JSONException je) { // ignore if field is not available } response = OMSMessages.ACTION_CENTER_FAILURE .getValue(); ContentValues contentValues = new ContentValues(); contentValues.put(OMSDatabaseConstants.TRANSACTION_QUEUE_STATUS, OMSDatabaseConstants.ACTION_STATUS_TRIED); contentValues.put(OMSDatabaseConstants.TRANSACTION_QUEUE_SERVER_URL, serviceUrl); contentValues.put(OMSDatabaseConstants.TRANSACTION_QUEUE_DATA_TABLE_NAME, tableName); contentValues.put(OMSDatabaseConstants.TRANSACTION_QUEUE_TYPE, OMSDatabaseConstants.POST_TYPE_REQUEST); contentValues.put(OMSDatabaseConstants.BL_SCHEMA_NAME, schemaName); actionCenterHelper.insertOrUpdateTransactionFailQueue(contentValues, uniqueRowId,configAppId); } } catch (JSONException e) { Log.e(TAG, "Exception occurred while updating the Action Queue status." + e.getMessage()); e.printStackTrace(); } catch (IllegalFormatConversionException e) { Log.e(TAG, "Exception occurred while updating the Action Queue status." + e.getMessage()); e.printStackTrace(); } return response; }*/ private String fetchPostResponse(JSONObject jsonPayLoad, String serviceURL) { String postResponse = ""; InputStream inputStream = null; OutputStream os = null; HttpURLConnection conn = null; try { /* conn = (HttpURLConnection) AppSecurityAndPerformance.getInstance() .getAppGuardSecuredHttpsUrlConnection(serviceURL);*/ URL urlToRequest = new URL(serviceURL); conn = (HttpURLConnection) urlToRequest.openConnection(); String jsonMessage = jsonPayLoad.toString(); conn.setReadTimeout(10000 /*milliseconds*/ ); conn.setConnectTimeout(15000 /* milliseconds */ ); conn.setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); conn.setFixedLengthStreamingMode(jsonMessage.getBytes().length); //make some HTTP header nicety conn.setRequestProperty("Content-Type", "application/json;charset=utf-8"); conn.setRequestProperty("X-Requested-With", "XMLHttpRequest"); conn.setRequestProperty("Content-Encoding", "gzip"); /*// AppMonitor analyzer.startNetworkConnection(serviceURL, OMSMessages.CONNECTION_PREFIX.getValue() + connectionID); if(conn!=null){ // AppMonitor analyzer.updateConnectionStatus(connectionID, true); } //open*/ conn.connect(); //setup send os = new BufferedOutputStream(conn.getOutputStream()); os.write(jsonMessage.getBytes()); //clean up os.flush(); inputStream = new BufferedInputStream(conn.getInputStream()); String serviceResponse = convertStreamToString(inputStream); int statusCode = conn.getResponseCode(); if (statusCode == OMSConstants.STATUSCODE_OK) { // AppMonitor /*analyzer.receivedConnectionResponse(connectionID, conn.getContentLength(), OMSDatabaseConstants.POST_TYPE_REQUEST);*/ if (serviceResponse != null) { Log.d(TAG, "PostResponse for HTTPURLConnection:::" + serviceResponse); postResponse = processHttpURLConnectionPostResponse(clientTableName, serviceResponse); String traceType = OMSApplication.getInstance().getTraceType(); OMSApplication.getInstance().setTraceType(OMSConstants.TRACE_TYPE_SERVER); /*ServerDBUpdateHelper dbhelper = new ServerDBUpdateHelper(context); dbhelper.insertCallTraceTypeData(ConsoleDBConstants.CALL_TRACE_TYPE_TABLE, ""+OMSApplication.getInstance().getAppId());*/ /*Log.i(TAG, "Server Response time::"+OMSApplication.getInstance().getServerProcessDuration()); Log.i(TAG, "DataBase Response time::"+OMSApplication.getInstance().getDatabaseProcessDuration()); */ Log.i(TAG, serviceURL + "\n" + "ServerResponseTime::" + OMSApplication.getInstance().getServerProcessDuration() + "\n" + "DataBaseResponseTime::" + OMSApplication.getInstance().getDatabaseProcessDuration()); OMSApplication.getInstance().setTraceType(traceType); return postResponse; } else { Log.e(TAG, "HttpEntity is NULL :" + jsonPayLoad.toString()); } } else { postResponse = OMSMessages.ACTION_CENTER_FAILURE.getValue(); inputStream = new BufferedInputStream(conn.getInputStream()); // AppMonitor /*analyzer.receivedConnectionResponse(connectionID, conn.getContentLength(), OMSDatabaseConstants.POST_TYPE_REQUEST);*/ String result = convertStreamToString(inputStream); if (result != null) { Log.d(TAG, "Post Service Response :" + result); try { JSONObject resultJSON = new JSONObject(result); JSONObject childResponse = resultJSON.getJSONObject("response"); if (!childResponse.getString("code").equals("00")) { postResponse = OMSMessages.BL_FAILURE.getValue(); } } catch (JSONException e) { e.printStackTrace(); } } else { try { JSONObject jsonObject = new JSONObject(); jsonObject.put(OMSMessages.ERROR.getValue(), conn.getResponseCode()); jsonObject.put(OMSMessages.ERROR_DESCRIPTION.getValue(), conn.getResponseMessage()); result = jsonObject.toString(); } catch (JSONException e) { Log.e(TAG, "JSON Exception occurred in ActionCenterFailure." + e.getMessage()); e.printStackTrace(); } } parseJSONObject(jsonPayLoad.toString(), OMSDatabaseConstants.STATUS_TYPE_TRIED, 0.0); ContentValues contentValues = new ContentValues(); contentValues.put(OMSDatabaseConstants.TRANSACTION_QUEUE_STATUS, OMSDatabaseConstants.ACTION_STATUS_TRIED); contentValues.put(OMSDatabaseConstants.TRANSACTION_QUEUE_SERVER_URL, serviceUrl); contentValues.put(OMSDatabaseConstants.TRANSACTION_QUEUE_DATA_TABLE_NAME, tableName); contentValues.put(OMSDatabaseConstants.TRANSACTION_QUEUE_TYPE, OMSDatabaseConstants.POST_TYPE_REQUEST); contentValues.put(OMSDatabaseConstants.BL_SCHEMA_NAME, schemaName); actionCenterHelper.insertOrUpdateTransactionFailQueue(contentValues, uniqueRowId, configAppId); //response = OMSMessages.FAILED.getValue(); postResponse = OMSMessages.BL_FAILURE.getValue(); Log.e(TAG, "Post Action Failed"); } } catch (SocketTimeoutException se) { progressDialog.dismiss(); Log.e(TAG, "SocketTimeoutException occurred while Posting the Actions" + se.getMessage()); if (rListener != null) { rListener.receiveResult(OMSMessages.ACTION_CENTER_FAILURE.getValue()); } se.printStackTrace(); } /* catch (ClientProtocolException e) { progressDialog.dismiss(); Log.e(TAG, "ClientProtocolException occurred while Posting the Actions" + e.getMessage()); e.printStackTrace(); }*/ catch (ProtocolException pe) { progressDialog.dismiss(); postResponse = OMSMessages.BL_FAILURE.getValue(); Log.e(TAG, "ProtocolException"); } catch (MalformedURLException mle) { progressDialog.dismiss(); postResponse = OMSMessages.BL_FAILURE.getValue(); Log.e(TAG, "MalformedURLException"); } catch (IOException e) { progressDialog.dismiss(); Log.e(TAG, "IOException occurred while Posting the Actions" + e.getMessage()); e.printStackTrace(); ContentValues contentValues = new ContentValues(); contentValues.put(OMSDatabaseConstants.TRANSACTION_QUEUE_STATUS, OMSDatabaseConstants.ACTION_STATUS_TRIED); contentValues.put(OMSDatabaseConstants.TRANSACTION_QUEUE_SERVER_URL, serviceUrl); contentValues.put(OMSDatabaseConstants.TRANSACTION_QUEUE_DATA_TABLE_NAME, tableName); contentValues.put(OMSDatabaseConstants.TRANSACTION_QUEUE_TYPE, OMSDatabaseConstants.POST_TYPE_REQUEST); contentValues.put(OMSDatabaseConstants.BL_SCHEMA_NAME, schemaName); actionCenterHelper.insertOrUpdateTransactionFailQueue(contentValues, uniqueRowId, configAppId); postResponse = OMSMessages.BL_FAILURE.getValue(); return postResponse; } finally { //clean up try { os.close(); } catch (NullPointerException ex) { postResponse = OMSMessages.BL_FAILURE.getValue(); Log.e(TAG, "NullPointerException"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { inputStream.close(); } catch (NullPointerException ex) { postResponse = OMSMessages.BL_FAILURE.getValue(); Log.e(TAG, "NullPointerException"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } conn.disconnect(); } return postResponse; }
From source file:ca.osmcanada.osvuploadr.JPMain.java
private void SendFinished(long Sequence_id, String accessToken) { try {/*from ww w . j a va 2 s. c om*/ URL url = new URL(URL_FINISH); URLConnection con = url.openConnection(); HttpURLConnection http = (HttpURLConnection) con; http.setRequestMethod("POST"); // PUT is another valid option http.setDoOutput(true); Map<String, String> arguments = new HashMap<>(); arguments.put("access_token", accessToken); arguments.put("sequenceId", Long.toString(Sequence_id)); System.out.println("accessToken:" + accessToken + "|sequenceId:" + Long.toString(Sequence_id)); StringJoiner sj = new StringJoiner("&"); for (Map.Entry<String, String> entry : arguments.entrySet()) sj.add(URLEncoder.encode(entry.getKey(), "UTF-8") + "=" + URLEncoder.encode(entry.getValue(), "UTF-8")); byte[] out = sj.toString().getBytes(StandardCharsets.UTF_8); int length = out.length; http.setFixedLengthStreamingMode(length); http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); http.connect(); try (OutputStream os = http.getOutputStream()) { os.write(out); os.close(); } InputStream is = http.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte buf[] = new byte[1024]; int letti; while ((letti = is.read(buf)) > 0) baos.write(buf, 0, letti); String data = new String(baos.toByteArray()); http.disconnect(); } catch (Exception ex) { Logger.getLogger(JPMain.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:gate.crowdsource.rest.CrowdFlowerClient.java
protected JsonElement request(String method, String uri, String... formData) throws IOException { if (log.isDebugEnabled()) { log.debug("URI: " + uri + ", formData: " + Arrays.toString(formData)); }//from w w w. ja v a 2 s . c o m URL cfUrl = new URL(CF_ENDPOINT + uri + "?key=" + apiKey); HttpURLConnection connection = (HttpURLConnection) cfUrl.openConnection(); connection.setRequestMethod(method); connection.setRequestProperty("Accept", "application/json"); if (formData != null && formData.length > 0) { // send the form data, URL encoded connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // annoyingly CrowdFlower doesn't support chunked streaming of // POSTs so we have to accumulate the content in a buffer, work // out its size and then POST with a Content-Length header ByteArrayOutputStream buffer = new ByteArrayOutputStream(4096); PrintWriter writer = new PrintWriter(new OutputStreamWriter(buffer, "UTF-8")); try { for (int i = 0; i < formData.length; i++) { String fieldName = formData[i]; String fieldValue = formData[++i]; if (i > 0) { writer.write("&"); } writer.write(URLEncoder.encode(fieldName, "UTF-8")); writer.write("="); writer.write(URLEncoder.encode(fieldValue, "UTF-8")); } } finally { writer.close(); } connection.setFixedLengthStreamingMode(buffer.size()); OutputStream connectionStream = connection.getOutputStream(); buffer.writeTo(connectionStream); connectionStream.close(); } // parse the response as JSON JsonParser parser = new JsonParser(); Reader responseReader = new InputStreamReader(connection.getInputStream(), "UTF-8"); try { return parser.parse(responseReader); } finally { responseReader.close(); } }
From source file:au.com.infiniterecursion.vidiom.utils.PublishingUtils.java
private ResumeInfo resumeFileUpload(String uploadUrl) throws IOException, ParserConfigurationException, SAXException, Internal500ResumeException { HttpURLConnection urlConnection = getGDataUrlConnection(uploadUrl); urlConnection.setRequestProperty("Content-Range", "bytes */*"); urlConnection.setRequestMethod("POST"); urlConnection.setRequestProperty("X-HTTP-Method-Override", "PUT"); urlConnection.setFixedLengthStreamingMode(0); HttpURLConnection.setFollowRedirects(false); urlConnection.connect();// w w w.jav a2s .c o m int responseCode = urlConnection.getResponseCode(); if (responseCode >= 300 && responseCode < 400) { int nextByteToUpload; String range = urlConnection.getHeaderField("Range"); if (range == null) { Log.d(TAG, String.format("PUT to %s did not return 'Range' header.", uploadUrl)); nextByteToUpload = 0; } else { Log.d(TAG, String.format("Range header is '%s'.", range)); String[] parts = range.split("-"); if (parts.length > 1) { nextByteToUpload = Integer.parseInt(parts[1]) + 1; } else { nextByteToUpload = 0; } } return new ResumeInfo(nextByteToUpload); } else if (responseCode >= 200 && responseCode < 300) { return new ResumeInfo(parseVideoId(urlConnection.getInputStream())); } else if (responseCode == 500) { // TODO this is a workaround for current problems with resuming // uploads while switching transport (Wifi->EDGE) throw new Internal500ResumeException( String.format("Unexpected response for PUT to %s: %s " + "(code %d)", uploadUrl, urlConnection.getResponseMessage(), responseCode)); } else { throw new IOException(String.format("Unexpected response for PUT to %s: %s " + "(code %d)", uploadUrl, urlConnection.getResponseMessage(), responseCode)); } }
From source file:com.ehsy.solr.util.SimplePostTool.java
/** * Reads data from the data stream and posts it to solr, * writes to the response to output/* ww w.jav a 2 s . co m*/ * @return true if success */ public boolean postData(InputStream data, Integer length, OutputStream output, String type, URL url) { if (mockMode) return true; boolean success = true; if (type == null) type = DEFAULT_CONTENT_TYPE; HttpURLConnection urlc = null; try { try { urlc = (HttpURLConnection) url.openConnection(); try { urlc.setRequestMethod("POST"); } catch (ProtocolException e) { fatal("Shouldn't happen: HttpURLConnection doesn't support POST??" + e); } urlc.setDoOutput(true); urlc.setDoInput(true); urlc.setUseCaches(false); urlc.setAllowUserInteraction(false); urlc.setRequestProperty("Content-type", type); if (url.getUserInfo() != null) { String encoding = DatatypeConverter .printBase64Binary(url.getUserInfo().getBytes(StandardCharsets.US_ASCII)); urlc.setRequestProperty("Authorization", "Basic " + encoding); } if (null != length) urlc.setFixedLengthStreamingMode(length); urlc.connect(); } catch (IOException e) { fatal("Connection error (is Solr running at " + solrUrl + " ?): " + e); success = false; } try (final OutputStream out = urlc.getOutputStream()) { pipe(data, out); } catch (IOException e) { fatal("IOException while posting data: " + e); success = false; } try { success &= checkResponseCode(urlc); try (final InputStream in = urlc.getInputStream()) { pipe(in, output); } } catch (IOException e) { warn("IOException while reading response: " + e); success = false; } } finally { if (urlc != null) urlc.disconnect(); } return success; }
From source file:ca.osmcanada.osvuploadr.JPMain.java
private long getSequence(ImageProperties imp, String accessToken) { try {/*from w ww .j av a 2 s .com*/ URL url = new URL(URL_SEQUENCE); URLConnection con = url.openConnection(); HttpURLConnection http = (HttpURLConnection) con; http.setRequestMethod("POST"); // PUT is another valid option http.setDoOutput(true); DecimalFormat df = new DecimalFormat("#.##############"); df.setRoundingMode(RoundingMode.CEILING); System.out.println("Getting Sequence ID.."); Map<String, String> arguments = new HashMap<>(); arguments.put("uploadSource", "OSVUploadr"); arguments.put("access_token", accessToken); arguments.put("currentCoordinate", df.format(imp.getLatitude()) + "," + df.format(imp.getLongitude())); System.out.println( "currentCoordinate:" + df.format(imp.getLatitude()) + "," + df.format(imp.getLongitude())); StringJoiner sj = new StringJoiner("&"); for (Map.Entry<String, String> entry : arguments.entrySet()) sj.add(URLEncoder.encode(entry.getKey(), "UTF-8") + "=" + URLEncoder.encode(entry.getValue(), "UTF-8")); byte[] out = sj.toString().getBytes(StandardCharsets.UTF_8); int length = out.length; System.out.println("Sending request:" + sj.toString()); http.setFixedLengthStreamingMode(length); http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); http.connect(); try (OutputStream os = http.getOutputStream()) { os.write(out); os.close(); } System.out.println("Request Sent getting sequence response..."); InputStream is = http.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte buf[] = new byte[1024]; int letti; while ((letti = is.read(buf)) > 0) baos.write(buf, 0, letti); String data = new String(baos.toByteArray()); int start = data.indexOf("\"osv\":{\"sequence\":{\"id\":\""); int end = data.indexOf("\"", start + 25); System.out.println("Received request:" + data); String sequence_id = data.substring(start + 25, end); System.out.println("Obtained Sequence ID: sequence_id"); http.disconnect(); return Long.parseLong(sequence_id); } catch (Exception ex) { System.out.println(ex.toString()); Logger.getLogger(JPMain.class.getName()).log(Level.SEVERE, null, ex); } return -1; }
From source file:com.BeatYourRecord.SubmitActivity.java
private String gdataUpload(File file, String uploadUrl, int start, int end) throws IOException { int chunk = end - start + 1; int bufferSize = 1024; byte[] buffer = new byte[bufferSize]; FileInputStream fileStream = new FileInputStream(file); HttpURLConnection urlConnection = getGDataUrlConnection(uploadUrl); // some mobile proxies do not support PUT, using X-HTTP-Method-Override to get around this problem if (isFirstRequest()) { Log.d(LOG_TAG, String.format("Uploaded %d bytes so far, using POST method.", (int) totalBytesUploaded)); urlConnection.setRequestMethod("POST"); } else {/*ww w.j a v a 2s . c o m*/ urlConnection.setRequestMethod("POST"); urlConnection.setRequestProperty("X-HTTP-Method-Override", "PUT"); Log.d(LOG_TAG, String.format("Uploaded %d bytes so far, using POST with X-HTTP-Method-Override PUT method.", (int) totalBytesUploaded)); } urlConnection.setDoOutput(true); urlConnection.setFixedLengthStreamingMode(chunk); urlConnection.setRequestProperty("Content-Type", "video/3gpp"); urlConnection.setRequestProperty("Content-Range", String.format("bytes %d-%d/%d", start, end, file.length())); Log.d(LOG_TAG, urlConnection.getRequestProperty("Content-Range")); //////may be //log.v("id man id",urlConnection.getRequestProperty("Content-Range")); OutputStream outStreamWriter = urlConnection.getOutputStream(); fileStream.skip(start); int bytesRead; int totalRead = 0; while ((bytesRead = fileStream.read(buffer, 0, bufferSize)) != -1) { outStreamWriter.write(buffer, 0, bytesRead); totalRead += bytesRead; this.totalBytesUploaded += bytesRead; double percent = (totalBytesUploaded / currentFileSize) * 99; /* Log.d(LOG_TAG, String.format( "fileSize=%f totalBytesUploaded=%f percent=%f", currentFileSize, totalBytesUploaded, percent)); */ dialog.setProgress((int) percent); if (totalRead == (end - start + 1)) { break; } } outStreamWriter.close(); int responseCode = urlConnection.getResponseCode(); Log.d(LOG_TAG, "responseCode=" + responseCode); Log.d(LOG_TAG, "responseMessage=" + urlConnection.getResponseMessage()); try { if (responseCode == 201) { String videoId = parseVideoId(urlConnection.getInputStream()); //log.v("Video ID", videoId); vidId = videoId; String latLng = null; if (this.videoLocation != null) { latLng = String.format("lat=%f lng=%f", this.videoLocation.getLatitude(), this.videoLocation.getLongitude()); } submitToYtdDomain(this.ytdDomain, this.assignmentId, videoId, this.youTubeName, SubmitActivity.this.clientLoginToken, getTitleText(), getDescriptionText(), this.dateTaken, latLng, this.tags); dialog.setProgress(100); //log.v("10video id",videoId); return videoId; } else if (responseCode == 200) { Set<String> keySet = urlConnection.getHeaderFields().keySet(); String keys = urlConnection.getHeaderFields().keySet().toString(); Log.d(LOG_TAG, String.format("Headers keys %s.", keys)); //////////////may be for (String key : keySet) { Log.d(LOG_TAG, String.format("Header key %s value %s.", key, urlConnection.getHeaderField(key))); } Log.w(LOG_TAG, "Received 200 response during resumable uploading"); throw new IOException(String.format("Unexpected response code : responseCode=%d responseMessage=%s", responseCode, urlConnection.getResponseMessage())); } else { if ((responseCode + "").startsWith("5")) { String error = String.format("responseCode=%d responseMessage=%s", responseCode, urlConnection.getResponseMessage()); Log.w(LOG_TAG, error); // TODO - this exception will trigger retry mechanism to kick in // TODO - even though it should not, consider introducing a new type so // TODO - resume does not kick in upon 5xx throw new IOException(error); } else if (responseCode == 308) { // OK, the chunk completed succesfully Log.d(LOG_TAG, String.format("responseCode=%d responseMessage=%s", responseCode, urlConnection.getResponseMessage())); } else { // TODO - this case is not handled properly yet Log.w(LOG_TAG, String.format("Unexpected return code : %d %s while uploading :%s", responseCode, urlConnection.getResponseMessage(), uploadUrl)); } } } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } return null; }