List of usage examples for java.net HttpURLConnection setUseCaches
public void setUseCaches(boolean usecaches)
From source file:by.belisa.util.OnlineConvert.java
/** * apiCall Make an API call to server based on action and parameters. * * @param action API action name//from ww w . j a v a 2 s. c o m * @param query Map Object of xml data * @param formatOptionXml xml string for extra format options * @return xml response string from server. */ private String apiCall(String action, Map query, String formatOptionXml) { String currentUrl = OnlineConvert.URL; String xmlResponse = ""; /* if (!"get-queue".equals(action)) { this.getServer(this.targetTypeOptions.get(this.targetType)); }*/ try { URL browser = new URL(currentUrl + "/" + action); HttpURLConnection conn = (HttpURLConnection) browser.openConnection(); String params = "queue=" + URLEncoder.encode( this.getMap2XML(query, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>", formatOptionXml), "UTF-8"); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length", String.valueOf(params.length())); conn.setUseCaches(false); conn.setDoOutput(true); conn.setDoInput(true); OutputStream wr = conn.getOutputStream(); wr.write(params.getBytes()); wr.flush(); // Get the response BufferedReader in; in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } xmlResponse = response.toString(); wr.close(); in.close(); } catch (IOException e) { } return xmlResponse; }
From source file:com.docdoku.client.actions.MainController.java
private void uploadFileWithServlet(final Component pParent, File pLocalFile, String pURL) throws IOException { System.out.println("Uploading file with servlet"); InputStream in = null;// w w w. ja 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 performHeadHTTPMethod(pURL); MainModel model = MainModel.getInstance(); URL url = new URL(pURL); conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setUseCaches(false); conn.setAllowUserInteraction(true); conn.setRequestProperty("Connection", "Keep-Alive"); byte[] encoded = org.apache.commons.codec.binary.Base64 .encodeBase64((model.getLogin() + ":" + model.getPassword()).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(), Config.BUFFER_CAPACITY); out.write(header); byte[] data = new byte[Config.CHUNK_SIZE]; int length; in = new ProgressMonitorInputStream(pParent, I18N.BUNDLE.getString("UploadMsg_part1") + " " + pLocalFile.getName() + " (" + (int) (pLocalFile.length() / 1024) + I18N.BUNDLE.getString("UploadMsg_part2"), new BufferedInputStream(new FileInputStream(pLocalFile), Config.BUFFER_CAPACITY)); while ((length = in.read(data)) != -1) { out.write(data, 0, length); } out.write(footer); out.flush(); int code = conn.getResponseCode(); System.out.println("Upload HTTP response code: " + code); if (code != 200) { //TODO create a more suitable exception throw new IOException(); } out.close(); } catch (InterruptedIOException pEx) { throw pEx; } catch (IOException pEx) { out.close(); throw pEx; } finally { in.close(); conn.disconnect(); } }
From source file:org.maikelwever.droidpile.backend.ApiConnecter.java
public String postData(ArrayList<NameValuePair> payload, String... data) throws IOException { if (data.length < 1) { throw new IllegalArgumentException("More than 1 argument is required."); }/*from w ww.ja v a 2 s. com*/ String url = this.baseUrl; String suffix = ""; for (String arg : data) { suffix += "/" + arg; } suffix += "/"; Log.d("droidpile", "URL we will call: " + url + suffix); url += suffix; URL uri = new URL(url); InputStreamReader is; HttpURLConnection con; if (url.startsWith("https")) { con = (HttpsURLConnection) uri.openConnection(); } else { con = (HttpURLConnection) uri.openConnection(); } String urlParameters = URLEncodedUtils.format(payload, ENCODING); con.setDoInput(true); con.setDoOutput(true); con.setInstanceFollowRedirects(false); con.setRequestMethod("POST"); con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); con.setRequestProperty("charset", ENCODING); con.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes(ENCODING).length)); con.setUseCaches(false); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); is = new InputStreamReader(con.getInputStream(), ENCODING); StringBuilder sb = new StringBuilder(); BufferedReader br = new BufferedReader(is); String read = br.readLine(); while (read != null) { sb.append(read); read = br.readLine(); } String stringData = sb.toString(); con.disconnect(); return stringData; }
From source file:calliope.db.CouchConnection.java
/** * PUT a json file to the database/*from w ww . j a va 2 s . c o m*/ * @param db the database name * @param docID the docID of the resource * @param json the json to put there * @return the server response */ @Override public String putToDb(String db, String docID, String json) throws AeseException { HttpURLConnection conn = null; try { docIDCheck(db, docID); docID = convertDocID(docID); String login = (user == null) ? "" : user + ":" + password + "@"; String url = "http://" + login + host + ":" + dbPort + "/" + db + "/" + docID; String revid = getRevId(db, docID); if (revid != null) json = addRevId(json, revid); URL u = new URL(url); conn = (HttpURLConnection) u.openConnection(); conn.setRequestMethod("PUT"); conn.setRequestProperty("Content-Type", MIMETypes.JSON); byte[] jData = json.getBytes(); conn.setRequestProperty("Content-Length", Integer.toString(jData.length)); conn.setRequestProperty("Content-Language", "en-US"); conn.setUseCaches(false); conn.setDoInput(true); conn.setDoOutput(true); DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); wr.writeBytes(json); wr.flush(); wr.close(); //Get Response return readResponse(conn, 0L, ""); } catch (Exception e) { if (conn != null) conn.disconnect(); throw new AeseException(e); } }
From source file:com.culvereq.vimp.networking.ConnectionHandler.java
public Vehicle addVehicle(TempVehicle vehicle) throws IOException, JSONException { URL requestURL = new URL(vehicleURL + "add"); HttpURLConnection connection = (HttpURLConnection) requestURL.openConnection(); connection.setDoInput(true);//from w w w . j av a 2 s . co m connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("charset", "utf-8"); String urlParameters = ""; urlParameters += "key=" + Globals.access_key; urlParameters += "&vehicle-name=" + vehicle.getName(); urlParameters += "&vehicle-type-id=" + vehicle.getType().getValue(); urlParameters += "&vehicle-make=" + vehicle.getMake(); urlParameters += "&vehicle-model" + vehicle.getModel(); urlParameters += "&vehicle-year" + vehicle.getYear(); urlParameters += "&vehicle-mileage" + vehicle.getMileage(); urlParameters += "&vehicle-vin" + vehicle.getVin(); urlParameters += "&vehicle-license-no" + vehicle.getLicenseNumber(); connection.setRequestProperty("Content-Length", "" + urlParameters.getBytes().length); connection.setUseCaches(false); OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.write(urlParameters); writer.flush(); writer.close(); int responseCode = connection.getResponseCode(); if (responseCode == 201) { BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); JSONObject json = new JSONObject(response.toString()); return new Deserializer().deserializeVehicle(json, response.toString()); } else if (responseCode == 400) { BufferedReader in = new BufferedReader(new InputStreamReader(connection.getErrorStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); throw new IOException(response.toString()); } else { throw new IOException("Got response code: " + responseCode); } }
From source file:com.smartbear.collaborator.issue.IssueRest.java
/** * Uploads zip file of raw files to Collaborator server * // www. ja v a 2 s.c o m * @param targetZipFile * @throws Exception */ private void uploadRawFilesToCollab(java.io.File targetZipFile) throws Exception { HttpURLConnection httpUrlConnection = null; try { String crlf = "\r\n"; String twoHyphens = "--"; String boundary = "*****"; URL url = new URL(configModel.getUrl() + URI_COLAB_UPLOAD); httpUrlConnection = (HttpURLConnection) url.openConnection(); httpUrlConnection.setUseCaches(false); httpUrlConnection.setDoOutput(true); httpUrlConnection.setRequestMethod("POST"); httpUrlConnection.setRequestProperty("Connection", "Keep-Alive"); httpUrlConnection.setRequestProperty("Cache-Control", "no-cache"); httpUrlConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); String loginCookie = "CodeCollaboratorLogin=" + configModel.getLogin(); String ticketCookie = "CodeCollaboratorTicketId=" + configModel.getAuthTicket(); httpUrlConnection.setRequestProperty("Cookie", loginCookie + "," + ticketCookie); DataOutputStream request = new DataOutputStream(httpUrlConnection.getOutputStream()); request.writeBytes(twoHyphens + boundary + crlf); request.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\"" + targetZipFile.getName() + "\"" + crlf); request.writeBytes("Content-Type: application/x-zip-compressed" + crlf); request.writeBytes(crlf); InputStream fileInStream = new FileInputStream(targetZipFile); request.write(IOUtils.toByteArray(fileInStream)); request.writeBytes(crlf); request.writeBytes(twoHyphens + boundary + twoHyphens + crlf); request.flush(); request.close(); if (httpUrlConnection.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new Exception(); } } catch (Exception e) { LOGGER.error(e); throw new Exception( "Can't upload raw versions to Collaborator Server. Check plugin collaborator configuration (url, login, password).", e); } finally { if (httpUrlConnection != null) { httpUrlConnection.disconnect(); } } }
From source file:com.odoko.solrcli.actions.CrawlPostAction.java
/** * Reads data from the data stream and posts it to solr, * writes to the response to output/*from ww w .j a va 2s .c o m*/ * @return true if success */ public boolean postData(InputStream data, Integer length, OutputStream output, String type, URL url) { 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 (null != length) urlc.setFixedLengthStreamingMode(length); } catch (IOException e) { fatal("Connection error (is Solr running at " + solrUrl + " ?): " + e); success = false; } OutputStream out = null; try { out = urlc.getOutputStream(); pipe(data, out); } catch (IOException e) { fatal("IOException while posting data: " + e); success = false; } finally { try { if(out!=null) out.close(); } catch (IOException x) { /*NOOP*/ } } InputStream in = null; try { if (HttpURLConnection.HTTP_OK != urlc.getResponseCode()) { warn("Solr returned an error #" + urlc.getResponseCode() + " " + urlc.getResponseMessage()); success = false; } in = urlc.getInputStream(); pipe(in, output); } catch (IOException e) { warn("IOException while reading response: " + e); success = false; } finally { try { if(in!=null) in.close(); } catch (IOException x) { /*NOOP*/ } } } finally { if(urlc!=null) urlc.disconnect(); } return success; }
From source file:com.emc.ecs.smart.SmartUploader.java
/** * Does a standard PUT upload using HttpURLConnection. *//* ww w . j a va 2 s. c o m*/ private void doSimpleUpload() { try { fileSize = Files.size(fileToUpload); HttpURLConnection conn = null; long start = System.currentTimeMillis(); try (DigestInputStream is = new DigestInputStream(Files.newInputStream(fileToUpload), MessageDigest.getInstance("MD5"))) { conn = (HttpURLConnection) uploadUrl.openConnection(); conn.setFixedLengthStreamingMode(fileSize); conn.setDoInput(true); conn.setDoOutput(true); conn.setInstanceFollowRedirects(false); conn.setUseCaches(false); conn.setRequestMethod(HttpMethod.PUT); conn.setRequestProperty(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM); OutputStream os = conn.getOutputStream(); byte[] buf = new byte[CHUNK_SIZE]; int len; while ((len = is.read(buf)) != -1) { os.write(buf, 0, len); bytesUploaded += len; printPercent(); } os.close(); if (conn.getResponseCode() != ClientResponse.Status.OK.getStatusCode()) { throw new RuntimeException("Unable to upload object content: status=" + conn.getResponseCode()); } else { List<String> eTags = conn.getHeaderFields().get(HttpHeaders.ETAG); if (eTags == null || eTags.size() < 1) { throw new RuntimeException("Unable to get ETag for uploaded data"); } else { byte[] sentMD5 = is.getMessageDigest().digest(); String eTag = eTags.get(0); byte[] gotMD5 = DatatypeConverter.parseHexBinary(eTag.substring(1, eTag.length() - 1)); if (!Arrays.equals(gotMD5, sentMD5)) { throw new RuntimeException("ETag doesn't match streamed data's MD5."); } } } } catch (IOException e) { throw new Exception("IOException while uploading object content after writing " + bytesUploaded + " of " + fileSize + " bytes: " + e.getMessage()); } finally { if (conn != null) conn.disconnect(); } long elapsed = System.currentTimeMillis() - start; printRate(fileSize, elapsed); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.sim2dial.dialer.ChatFragment.java
private String uploadImage(String filePath, Bitmap file, int compressorQuality, final int imageSize) { String fileName;//from w w w . j ava 2 s. c o m if (filePath != null) { File sourceFile = new File(filePath); fileName = sourceFile.getName(); } else { fileName = getString(R.string.temp_photo_name_with_date).replace("%s", String.valueOf(System.currentTimeMillis())); } if (getResources().getBoolean(R.bool.hash_images_as_name_before_upload)) { fileName = String.valueOf(hashBitmap(file)) + ".jpg"; } String response = null; HttpURLConnection conn = null; try { String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = "---------------------------14737809831466499882746641449"; URL url = new URL(uploadServerUri); conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("ENCTYPE", "multipart/form-data"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); conn.setRequestProperty("uploaded_file", fileName); ProgressOutputStream pos = new ProgressOutputStream(conn.getOutputStream()); pos.setListener(new OutputStreamListener() { @Override public void onBytesWrite(int count) { bytesSent += count; progressBar.setProgress(bytesSent * 100 / imageSize); } }); DataOutputStream dos = new DataOutputStream(pos); dos.writeBytes(lineEnd + twoHyphens + boundary + lineEnd); dos.writeBytes( "Content-Disposition: form-data; name=\"userfile\"; filename=\"" + fileName + "\"" + lineEnd); dos.writeBytes("Content-Type: application/octet-stream" + lineEnd); dos.writeBytes(lineEnd); file.compress(CompressFormat.JPEG, compressorQuality, dos); dos.writeBytes(lineEnd); dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); dos.flush(); dos.close(); InputStream is = conn.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); int bytesRead; byte[] bytes = new byte[1024]; while ((bytesRead = is.read(bytes)) != -1) { baos.write(bytes, 0, bytesRead); } byte[] bytesReceived = baos.toByteArray(); baos.close(); is.close(); response = new String(bytesReceived); } catch (Exception e) { e.printStackTrace(); } finally { if (conn != null) { conn.disconnect(); } } return response; }
From source file:org.xingjitong.ChatFragment.java
private String uploadImage(String filePath, Bitmap file, int compressorQuality, final int imageSize) { String fileName;/* ww w.j a v a 2 s. c o m*/ if (filePath != null) { File sourceFile = new File(filePath); fileName = sourceFile.getName(); } else { fileName = getString(R.string.temp_photo_name_with_date).replace("%s", String.valueOf(System.currentTimeMillis())); } String response = null; HttpURLConnection conn = null; try { String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = "---------------------------14737809831466499882746641449"; URL url = new URL(uploadServerUri); conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("ENCTYPE", "multipart/form-data"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); conn.setRequestProperty("uploaded_file", fileName); ProgressOutputStream pos = new ProgressOutputStream(conn.getOutputStream()); pos.setListener(new OutputStreamListener() { @Override public void onBytesWrite(int count) { bytesSent += count; progressBar.setProgress(bytesSent * 100 / imageSize); } }); DataOutputStream dos = new DataOutputStream(pos); dos.writeBytes(lineEnd + twoHyphens + boundary + lineEnd); dos.writeBytes( "Content-Disposition: form-data; name=\"userfile\"; filename=\"" + fileName + "\"" + lineEnd); dos.writeBytes("Content-Type: application/octet-stream" + lineEnd); dos.writeBytes(lineEnd); file.compress(CompressFormat.JPEG, compressorQuality, dos); dos.writeBytes(lineEnd); dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); dos.flush(); dos.close(); InputStream is = conn.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); int bytesRead; byte[] bytes = new byte[1024]; while ((bytesRead = is.read(bytes)) != -1) { baos.write(bytes, 0, bytesRead); } byte[] bytesReceived = baos.toByteArray(); baos.close(); is.close(); response = new String(bytesReceived); } catch (Exception e) { e.printStackTrace(); } finally { if (conn != null) { conn.disconnect(); } } return response; }