List of usage examples for java.net URLConnection getOutputStream
public OutputStream getOutputStream() throws IOException
From source file:org.xbmc.jsonrpc.Connection.java
/** * Executes a query./*from w ww. j a va2 s . c om*/ * @param command Name of the command to execute * @param parameters Parameters * @param manager Reference back to business layer * @return Parsed JSON object, empty object on error. */ public JsonNode query(String command, JsonNode parameters, INotifiableManager manager) { URLConnection uc = null; try { final ObjectMapper mapper = Client.MAPPER; if (mUrlSuffix == null) { throw new NoSettingsException(); } final URL url = new URL(mUrlSuffix + XBMC_JSONRPC_BOOTSTRAP); uc = url.openConnection(); uc.setConnectTimeout(SOCKET_CONNECTION_TIMEOUT); uc.setReadTimeout(mSocketReadTimeout); if (authEncoded != null) { uc.setRequestProperty("Authorization", "Basic " + authEncoded); } uc.setRequestProperty("Content-Type", "application/json"); uc.setDoOutput(true); final ObjectNode data = Client.obj().p("jsonrpc", "2.0").p("method", command).p("id", "1"); if (parameters != null) { data.put("params", parameters); } final JsonFactory jsonFactory = new JsonFactory(); final JsonGenerator jg = jsonFactory.createJsonGenerator(uc.getOutputStream(), JsonEncoding.UTF8); jg.setCodec(mapper); // POST data jg.writeTree(data); jg.flush(); final JsonParser jp = jsonFactory.createJsonParser(uc.getInputStream()); jp.setCodec(mapper); final JsonNode ret = jp.readValueAs(JsonNode.class); return ret; } catch (MalformedURLException e) { manager.onError(e); } catch (IOException e) { int responseCode = -1; try { responseCode = ((HttpURLConnection) uc).getResponseCode(); } catch (IOException e1) { } // do nothing, getResponse code failed so treat as default i/o exception. if (uc != null && responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) { manager.onError(new HttpException(Integer.toString(HttpURLConnection.HTTP_UNAUTHORIZED))); } else { manager.onError(e); } } catch (NoSettingsException e) { manager.onError(e); } return new ObjectNode(null); }
From source file:junk.gui.HazardDataSetCalcCondorApp.java
/** * this connects to the servlet on web server to check if dataset name already exists * or computation have already been for these parameter settings. * @return//from w ww . j a v a 2 s. c om */ private Object checkForHazardMapComputation() { try { if (D) System.out.println("starting to make connection with servlet"); URL hazardMapServlet = new URL(DATASET_CHECK_SERVLET_URL); URLConnection servletConnection = hazardMapServlet.openConnection(); if (D) System.out.println("connection established"); // inform the connection that we will send output and accept input servletConnection.setDoInput(true); servletConnection.setDoOutput(true); // Don't use a cached version of URL connection. servletConnection.setUseCaches(false); servletConnection.setDefaultUseCaches(false); // Specify the content type that we will send binary data servletConnection.setRequestProperty("Content-Type", "application/octet-stream"); ObjectOutputStream toServlet = new ObjectOutputStream(servletConnection.getOutputStream()); //sending the parameters info. to the servlet toServlet.writeObject(getParametersInfo()); //sending the dataset id to the servlet toServlet.writeObject(datasetIdText.getText()); toServlet.flush(); toServlet.close(); // Receive the datasetnumber from the servlet after it has received all the data ObjectInputStream fromServlet = new ObjectInputStream(servletConnection.getInputStream()); Object obj = fromServlet.readObject(); //if(D) System.out.println("Receiving the Input from the Servlet:"+success); fromServlet.close(); return obj; } catch (Exception e) { ExceptionWindow bugWindow = new ExceptionWindow(this, e, getParametersInfo()); bugWindow.setVisible(true); bugWindow.pack(); } return null; }
From source file:junk.gui.HazardDataSetCalcCondorApp.java
/** * sets up the connection with the servlet on the server (gravity.usc.edu) *///from ww w . j a v a 2 s . c om private void sendParametersToServlet(SitesInGriddedRegion regionSites, ScalarIntensityMeasureRelationshipAPI imr, String eqkRupForecastLocation) { try { if (D) System.out.println("starting to make connection with servlet"); URL hazardMapServlet = new URL(SERVLET_URL); URLConnection servletConnection = hazardMapServlet.openConnection(); if (D) System.out.println("connection established"); // inform the connection that we will send output and accept input servletConnection.setDoInput(true); servletConnection.setDoOutput(true); // Don't use a cached version of URL connection. servletConnection.setUseCaches(false); servletConnection.setDefaultUseCaches(false); // Specify the content type that we will send binary data servletConnection.setRequestProperty("Content-Type", "application/octet-stream"); ObjectOutputStream toServlet = new ObjectOutputStream(servletConnection.getOutputStream()); //sending the object of the gridded region sites to the servlet toServlet.writeObject(regionSites); //sending the IMR object to the servlet toServlet.writeObject(imr); //sending the EQK forecast object to the servlet toServlet.writeObject(eqkRupForecastLocation); //send the X values in a arraylist ArrayList list = new ArrayList(); for (int i = 0; i < function.getNum(); ++i) list.add(new String("" + function.getX(i))); toServlet.writeObject(list); // send the MAX DISTANCE toServlet.writeObject(maxDistance); //sending email address to the servlet toServlet.writeObject(emailText.getText()); //sending the parameters info. to the servlet toServlet.writeObject(getParametersInfo()); //sending the dataset id to the servlet toServlet.writeObject(datasetIdText.getText()); toServlet.flush(); toServlet.close(); // Receive the datasetnumber from the servlet after it has received all the data ObjectInputStream fromServlet = new ObjectInputStream(servletConnection.getInputStream()); String dataset = fromServlet.readObject().toString(); JOptionPane.showMessageDialog(this, dataset); if (D) System.out.println("Receiving the Input from the Servlet:" + dataset); fromServlet.close(); } catch (Exception e) { ExceptionWindow bugWindow = new ExceptionWindow(this, e, getParametersInfo()); bugWindow.setVisible(true); bugWindow.pack(); } }
From source file:savant.view.swing.Savant.java
private static void logUsageStats() { try {/*from w w w. java 2s. co m*/ URLConnection urlConn; DataOutputStream printout; // URL of CGI-Bin script. // URL connection channel. urlConn = BrowserSettings.LOG_USAGE_STATS_URL.openConnection(); // Let the run-time system (RTS) know that we want input. urlConn.setDoInput(true); // Let the RTS know that we want to do output. urlConn.setDoOutput(true); // No caching, we want the real thing. urlConn.setUseCaches(false); // Specify the content type. urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // Send POST output. printout = new DataOutputStream(urlConn.getOutputStream()); DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date date = new Date(); Locale locale = Locale.getDefault(); String content = post("time", dateFormat.format(date)) + "&" + post("language", locale.getDisplayLanguage()) + "&" + post("user.timezone", System.getProperty("user.timezone")) + "&" + post("savant.version", BrowserSettings.VERSION) + "&" + post("savant.build", BrowserSettings.BUILD) //+ "&" + post("address", InetAddress.getLocalHost().getHostAddress()) + "&" + post("java.version", System.getProperty("java.version")) + "&" + post("java.vendor", System.getProperty("java.vendor")) + "&" + post("os.name", System.getProperty("os.name")) + "&" + post("os.arch", System.getProperty("os.arch")) + "&" + post("os.version", System.getProperty("os.version")) + "&" + post("user.region", System.getProperty("user.region")); printout.writeBytes(content); printout.flush(); printout.close(); urlConn.getInputStream(); } catch (Exception ex) { //LOG.error("Error logging usage stats.", ex); } }
From source file:net.sf.taverna.t2.workbench.ui.impl.UserRegistrationForm.java
/** * Post registration data to our server. *//*from www . ja v a2 s . co m*/ private boolean postUserRegistrationDataToServer(UserRegistrationData regData) { StringBuilder parameters = new StringBuilder(); /* * The 'submit' parameter - to let the server-side script know we are * submitting the user's registration form - all other requests will be * silently ignored */ try { // value does not matter enc(parameters, TAVERNA_REGISTRATION_POST_PARAMETER_NAME, "submit"); enc(parameters, TAVERNA_VERSION_POST_PARAMETER_NAME, regData.getTavernaVersion()); enc(parameters, FIRST_NAME_POST_PARAMETER_NAME, regData.getFirstName()); enc(parameters, LAST_NAME_POST_PARAMETER_NAME, regData.getLastName()); enc(parameters, EMAIL_ADDRESS_POST_PARAMETER_NAME, regData.getEmailAddress()); enc(parameters, KEEP_ME_INFORMED_POST_PARAMETER_PROPERTY_NAME, regData.getKeepMeInformed()); enc(parameters, INSTITUTION_OR_COMPANY_POST_PARAMETER_NAME, regData.getInstitutionOrCompanyName()); enc(parameters, INDUSTRY_TYPE_POST_PARAMETER_NAME, regData.getIndustry()); enc(parameters, FIELD_POST_PARAMETER_NAME, regData.getField()); enc(parameters, PURPOSE_POST_PARAMETER_NAME, regData.getPurposeOfUsingTaverna()); } catch (UnsupportedEncodingException ueex) { logger.error(FAILED + "Could not url encode post parameters", ueex); showMessageDialog(null, REGISTRATION_FAILED_MSG, "Error encoding registration data", ERROR_MESSAGE); return false; } String server = REGISTRATION_URL; logger.info("Posting user registartion to " + server + " with parameters: " + parameters); String response = ""; String failure; try { URL url = new URL(server); URLConnection conn = url.openConnection(); /* * Set timeout to e.g. 7 seconds, otherwise we might hang too long * if server is not responding and it will block Taverna */ conn.setConnectTimeout(7000); // Set connection parameters conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); // Make server believe we are HTML form data... conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // Write out the bytes of the content string to the stream. try (DataOutputStream out = new DataOutputStream(conn.getOutputStream())) { out.writeBytes(parameters.toString()); out.flush(); } // Read response from the input stream. try (BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()))) { String temp; while ((temp = in.readLine()) != null) response += temp + "\n"; // Remove the last \n character if (!response.isEmpty()) response = response.substring(0, response.length() - 1); } if (response.equals("Registration successful!")) return true; logger.error(FAILED + "Response form server was: " + response); failure = "Error saving registration data on the server"; } catch (ConnectException ceex) { /* * the connection was refused remotely (e.g. no process is listening * on the remote address/port). */ logger.error(FAILED + "Registration server is not listening of the specified url.", ceex); failure = "Registration server is not listening at the specified url"; } catch (SocketTimeoutException stex) { // timeout has occurred on a socket read or accept. logger.error(FAILED + "Socket timeout occurred.", stex); failure = "Registration server timeout"; } catch (MalformedURLException muex) { logger.error(FAILED + "Registartion server's url is malformed.", muex); failure = "Error with registration server's url"; } catch (IOException ioex) { logger.error( FAILED + "Failed to open url connection to registration server or writing/reading to/from it.", ioex); failure = "Error opening connection to the registration server"; } showMessageDialog(null, REGISTRATION_FAILED_MSG, failure, ERROR_MESSAGE); return false; }
From source file:org.diorite.impl.metrics.Metrics.java
/** * Generic method that posts a plugin to the metrics website *//*from w w w . java2s . c o m*/ private void postPlugin(final boolean isPing) throws IOException { final String serverVersion = this.getFullServerVersion(); final int playersOnline = this.getPlayersOnline(); // END server software specific section -- all code below does not use any code outside of this class / Java // Construct the post data final StringBuilder json = new StringBuilder(1024); json.append('{'); // The plugin's description file containg all of the plugin data such as name, version, author, etc appendJSONPair(json, "guid", this.getUUID()); appendJSONPair(json, "plugin_version", this.core.getVersion()); appendJSONPair(json, "server_version", serverVersion); appendJSONPair(json, "players_online", Integer.toString(playersOnline)); // New data as of R6 final String osname = System.getProperty("os.name"); String osarch = System.getProperty("os.arch"); final String osversion = System.getProperty("os.version"); final String java_version = System.getProperty("java.version"); final int coreCount = Runtime.getRuntime().availableProcessors(); // normalize os arch .. amd64 -> x86_64 if (osarch.equals("amd64")) { osarch = "x86_64"; } appendJSONPair(json, "osname", osname); appendJSONPair(json, "osarch", osarch); appendJSONPair(json, "osversion", osversion); appendJSONPair(json, "cores", Integer.toString(coreCount)); appendJSONPair(json, "auth_mode", (this.core.getOnlineMode() == OnlineMode.FALSE) ? "0" : "1"); appendJSONPair(json, "java_version", java_version); // If we're pinging, append it if (isPing) { appendJSONPair(json, "ping", "1"); } if (!this.graphs.isEmpty()) { synchronized (this.graphs) { json.append(','); json.append('"'); json.append("graphs"); json.append('"'); json.append(':'); json.append('{'); boolean firstGraph = true; for (final DynamicMetricsGraph graph : this.graphs) { final StringBuilder graphJson = new StringBuilder(); graphJson.append('{'); for (final MetricsPlotter plotter : graph.getPlotters()) { appendJSONPair(graphJson, plotter.getColumnName(), Integer.toString(plotter.getValue())); } graphJson.append('}'); if (!firstGraph) { json.append(','); } json.append(escapeJSON(graph.getName())); json.append(':'); json.append(graphJson); firstGraph = false; } json.append('}'); } } // close json json.append('}'); // Create the url final URL url = new URL(BASE_URL); // Connect to the website final URLConnection connection; connection = url.openConnection(); final byte[] uncompressed = json.toString().getBytes(); final byte[] compressed = gzip(json.toString()); // Headers connection.addRequestProperty("User-Agent", "MCStats/" + REVISION); connection.addRequestProperty("Content-Type", "application/json"); connection.addRequestProperty("Content-Encoding", "gzip"); connection.addRequestProperty("Content-Length", Integer.toString(compressed.length)); connection.addRequestProperty("Accept", "application/json"); connection.addRequestProperty("Connection", "close"); connection.setDoOutput(true); if (CoreMain.isEnabledDebug()) { SpammyError.out("[Metrics] Prepared request for Diorite uncompressed=" + uncompressed.length + " compressed=" + compressed.length, (int) TimeUnit.MINUTES.toSeconds(5), this.hashCode() + 1); } // Write the data try (final OutputStream os = connection.getOutputStream()) { os.write(compressed); os.flush(); } String response; try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { response = reader.readLine(); } if ((response == null) || response.startsWith("ERR") || response.startsWith("7")) { if (response == null) { response = "null"; } else if (response.startsWith("7")) { response = response.substring(response.startsWith("7,") ? 2 : 1); } throw new IOException(response); } else { // Is this the first update this hour? if (response.equals("1") || response.contains("This is your first update this hour")) { synchronized (this.graphs) { this.graphs.forEach(DynamicMetricsGraph::resetPlotters); } } } }
From source file:com.jaspersoft.jrx.query.JRXPathQueryExecuter.java
private Document getDocumentFromUrl(Map<String, ? extends JRValueParameter> parametersMap) throws Exception { // Get the url... String urlString = (String) getParameterValue(JRXPathQueryExecuterFactory.XML_URL); // add GET parameters to the urlString... Iterator<String> i = parametersMap.keySet().iterator(); String div = "?"; URL url = new URL(urlString); if (url.getQuery() != null) div = "&"; while (i.hasNext()) { String keyName = "" + i.next(); if (keyName.startsWith("XML_GET_PARAM_")) { String paramName = keyName.substring("XML_GET_PARAM_".length()); String value = (String) getParameterValue(keyName); urlString += div + URLEncoder.encode(paramName, "UTF-8") + "=" + URLEncoder.encode(value, "UTF-8"); div = "&"; }/* w w w .ja v a 2 s . c o m*/ } url = new URL(urlString); if (url.getProtocol().toLowerCase().equals("file")) { // do nothing return JRXmlUtils.parse(url.openStream()); } else if (url.getProtocol().toLowerCase().equals("http") || url.getProtocol().toLowerCase().equals("https")) { String username = (String) getParameterValue(JRXPathQueryExecuterFactory.XML_USERNAME); String password = (String) getParameterValue(JRXPathQueryExecuterFactory.XML_PASSWORD); if (url.getProtocol().toLowerCase().equals("https")) { JRPropertiesUtil dPROP = PropertiesHelper.DPROP; String socketFactory = dPROP .getProperty("net.sf.jasperreports.query.executer.factory.xPath.DefaultSSLSocketFactory"); if (socketFactory == null) { socketFactory = dPROP.getProperty( "net.sf.jasperreports.query.executer.factory.XPath.DefaultSSLSocketFactory"); } if (socketFactory != null) { // setSSLSocketFactory HttpsURLConnection.setDefaultSSLSocketFactory( (SSLSocketFactory) Class.forName(socketFactory).newInstance()); } else { log.debug("No SSLSocketFactory defined, using default"); } String hostnameVerifyer = dPROP .getProperty("net.sf.jasperreports.query.executer.factory.xPath.DefaultHostnameVerifier"); if (hostnameVerifyer == null) { hostnameVerifyer = dPROP.getProperty( "net.sf.jasperreports.query.executer.factory.XPath.DefaultHostnameVerifier"); } if (hostnameVerifyer != null) { // setSSLSocketFactory HttpsURLConnection.setDefaultHostnameVerifier( (HostnameVerifier) Class.forName(hostnameVerifyer).newInstance()); } else { log.debug("No HostnameVerifier defined, using default"); } } URLConnection conn = url.openConnection(); if (username != null && username.length() > 0 && password != null) { ByteArrayInputStream bytesIn = new ByteArrayInputStream((username + ":" + password).getBytes()); ByteArrayOutputStream dataOut = new ByteArrayOutputStream(); Base64Encoder enc = new Base64Encoder(bytesIn, dataOut); enc.process(); String encoding = dataOut.toString(); conn.setRequestProperty("Authorization", "Basic " + encoding); } // add POST parameters to the urlString... i = parametersMap.keySet().iterator(); String data = ""; div = ""; while (i.hasNext()) { String keyName = "" + i.next(); if (keyName.startsWith("XML_POST_PARAM_")) { String paramName = keyName.substring("XML_POST_PARAM_".length()); String value = (String) getParameterValue(keyName); data += div + URLEncoder.encode(paramName, "UTF-8") + "=" + URLEncoder.encode(value, "UTF-8"); div = "&"; } } conn.setDoOutput(true); if (data.length() > 0) { conn.setDoInput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); } try { return XMLUtils.parseNoValidation(conn.getInputStream()); } catch (SAXException e) { throw new JRException("Failed to parse the xml document", e); } catch (IOException e) { throw new JRException("Failed to parse the xml document", e); } catch (ParserConfigurationException e) { throw new JRException("Failed to create a document builder factory", e); } // return JRXmlUtils.parse(conn.getInputStream()); } else { throw new JRException("URL protocol not supported"); } }
From source file:org.signserver.client.cli.defaultimpl.TimeStampCommand.java
@SuppressWarnings("SleepWhileInLoop") // We are just using the sleep for rate limiting private void tsaRequest() throws Exception { final Random rand = new Random(); final TimeStampRequestGenerator timeStampRequestGenerator = new TimeStampRequestGenerator(); boolean doRun = true; do {//from w ww . j av a 2s .co m final int nonce = rand.nextInt(); byte[] digest = new byte[20]; if (instring != null) { final byte[] digestBytes = instring.getBytes("UTF-8"); final MessageDigest dig = MessageDigest.getInstance(TSPAlgorithms.SHA1.getId(), "BC"); dig.update(digestBytes); digest = dig.digest(); // When we have given input, we don't want to loop doRun = false; } if (infilestring != null) { // TSPAlgorithms constants changed from Strings to ASN1Encoded objects digest = digestFile(infilestring, TSPAlgorithms.SHA1.getId()); doRun = false; } final byte[] hexDigest = Hex.encode(digest); if (LOG.isDebugEnabled()) { LOG.debug("MessageDigest=" + new String(hexDigest)); } final TimeStampRequest timeStampRequest; if (inreqstring == null) { LOG.debug("Generating a new request"); timeStampRequestGenerator.setCertReq(certReq); if (reqPolicy != null) { timeStampRequestGenerator.setReqPolicy(new ASN1ObjectIdentifier(reqPolicy)); } timeStampRequest = timeStampRequestGenerator.generate(TSPAlgorithms.SHA1, digest, BigInteger.valueOf(nonce)); } else { LOG.debug("Reading request from file"); timeStampRequest = new TimeStampRequest(readFiletoBuffer(inreqstring)); } final byte[] requestBytes = timeStampRequest.getEncoded(); if (outreqstring != null) { // Store request byte[] outBytes; if (base64) { outBytes = Base64.encode(requestBytes); } else { outBytes = requestBytes; } FileOutputStream fos = null; try { fos = new FileOutputStream(outreqstring); fos.write(outBytes); } finally { if (fos != null) { fos.close(); } } } keyStoreOptions.setupHTTPS(); URL url; URLConnection urlConn; DataOutputStream printout; DataInputStream input; url = new URL(urlstring); // Take start time final long startMillis = System.currentTimeMillis(); final long startTime = System.nanoTime(); if (LOG.isDebugEnabled()) { LOG.debug("Sending request at: " + startMillis); } urlConn = url.openConnection(); urlConn.setDoInput(true); urlConn.setDoOutput(true); urlConn.setUseCaches(false); urlConn.setRequestProperty("Content-Type", "application/timestamp-query"); // Send POST output. printout = new DataOutputStream(urlConn.getOutputStream()); printout.write(requestBytes); printout.flush(); printout.close(); // Get response data. input = new DataInputStream(urlConn.getInputStream()); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); int b; while ((b = input.read()) != -1) { baos.write(b); } // Take stop time final long estimatedTime = System.nanoTime() - startTime; LOG.info("Got reply after " + TimeUnit.NANOSECONDS.toMillis(estimatedTime) + " ms"); final byte[] replyBytes = baos.toByteArray(); if (outrepstring != null) { // Store request byte[] outBytes; if (base64) { outBytes = Base64.encode(replyBytes); } else { outBytes = replyBytes; } FileOutputStream fos = null; try { fos = new FileOutputStream(outrepstring); fos.write(outBytes); } finally { if (fos != null) { fos.close(); } } } final TimeStampResponse timeStampResponse = new TimeStampResponse(replyBytes); timeStampResponse.validate(timeStampRequest); LOG.info("TimeStampRequest validated"); if (LOG.isDebugEnabled()) { final Date genTime; if (timeStampResponse.getTimeStampToken() != null && timeStampResponse.getTimeStampToken().getTimeStampInfo() != null) { genTime = timeStampResponse.getTimeStampToken().getTimeStampInfo().getGenTime(); } else { genTime = null; } LOG.debug("(Status: " + timeStampResponse.getStatus() + ", " + timeStampResponse.getFailInfo() + "): " + timeStampResponse.getStatusString() + (genTime != null ? (", genTime: " + genTime.getTime()) : "") + "\n"); } if (doRun) { Thread.sleep(sleep); } } while (doRun); }
From source file:edu.hackathon.perseus.core.httpSpeedTest.java
private double doUpload(String phpFile, InputStream uploadFileIs, String fileName) { URLConnection conn = null; OutputStream os = null;/* ww w . ja v a 2 s. co m*/ InputStream is = null; double bw = 0.0; try { String response = ""; Date oldTime = new Date(); URL url = new URL(amazonDomain + "/" + phpFile); String boundary = "---------------------------4664151417711"; conn = url.openConnection(); conn.setDoOutput(true); conn.setConnectTimeout(5000); conn.setReadTimeout(5000); byte[] fileData = new byte[uploadFileIs.available()]; uploadFileIs.read(fileData); uploadFileIs.close(); String message1 = "--" + boundary + CrLf; message1 += "Content-Disposition: form-data;"; message1 += "name=\"uploadedfile\"; filename=\"" + fileName + "\"" + CrLf; message1 += "Content-Type: text/plain; charset=UTF-8" + CrLf + CrLf; // the file is sent between the messages in the multipart message. String message2 = CrLf + "--" + boundary + "--" + CrLf; conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); int contentLenght = message1.length() + message2.length() + fileData.length; // might not need to specify the content-length when sending chunked data. conn.setRequestProperty("Content-Length", String.valueOf(contentLenght)); os = conn.getOutputStream(); os.write(message1.getBytes()); // SEND THE IMAGE int index = 0; int size = 1024; do { if ((index + size) > fileData.length) { size = fileData.length - index; } os.write(fileData, index, size); index += size; } while (index < fileData.length); os.write(message2.getBytes()); os.flush(); is = conn.getInputStream(); char buff = 512; int len; byte[] data = new byte[buff]; do { len = is.read(data); if (len > 0) { response += new String(data, 0, len); } } while (len > 0); if (response.equals("200")) { Date newTime = new Date(); double milliseconds = newTime.getTime() - oldTime.getTime(); bw = ((double) contentLenght * 8) / (milliseconds * (double) 1000); } } catch (Exception e) { System.out.println("Exception is fired in upload test. error:" + e.getMessage()); } finally { try { os.close(); } catch (Exception e) { //System.out.println("Exception is fired in os.close. error:" + e.getMessage()); } try { is.close(); } catch (Exception e) { //System.out.println("Exception is fired in is.close. error:" + e.getMessage()); } } return bw; }