List of usage examples for java.net HttpURLConnection setUseCaches
public void setUseCaches(boolean usecaches)
From source file:de.bps.course.nodes.vc.provider.wimba.WimbaClassroomProvider.java
private String sendRequest(Map<String, String> parameters) { URL url = createRequestUrl(parameters); HttpURLConnection urlConn; try {// w ww. j a va 2 s . co m urlConn = (HttpURLConnection) url.openConnection(); // setup url connection urlConn.setDoOutput(true); urlConn.setUseCaches(false); urlConn.setInstanceFollowRedirects(false); // add content type urlConn.setRequestProperty("Content-Type", CONTENT_TYPE); // add cookie information if (cookie != null) urlConn.setRequestProperty("Cookie", cookie); // send request urlConn.connect(); // detect redirect int code = urlConn.getResponseCode(); boolean moved = code == HttpURLConnection.HTTP_MOVED_PERM | code == HttpURLConnection.HTTP_MOVED_TEMP; if (moved) { String location = urlConn.getHeaderField("Location"); List<String> headerVals = urlConn.getHeaderFields().get("Set-Cookie"); for (String val : headerVals) { if (val.startsWith(COOKIE)) cookie = val; } url = createRedirectUrl(location); urlConn = (HttpURLConnection) url.openConnection(); urlConn.setRequestProperty("Cookie", cookie); } // read response BufferedReader input = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); StringBuilder response = new StringBuilder(); String line; while ((line = input.readLine()) != null) response.append(line).append("\n"); input.close(); if (isLogDebugEnabled()) logDebug("Response: " + response); return response.toString(); } catch (IOException e) { logError("Sending request to Wimba Classroom failed. Request: " + url.toString(), e); return ""; } }
From source file:com.ichi2.anki.SyncClient.java
public static void fullSyncFromLocal(String password, String username, String deckName, String deckPath) { URL url;/*ww w . j a v a 2 s. c o m*/ try { Log.i(AnkiDroidApp.TAG, "Fullup"); url = new URL(AnkiDroidProxy.SYNC_URL + "fullup"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "close"); conn.setRequestProperty("Charset", "UTF-8"); // conn.setRequestProperty("Content-Length", "8494662"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + MIME_BOUNDARY); conn.setRequestProperty("Host", AnkiDroidProxy.SYNC_HOST); DataOutputStream ds = new DataOutputStream(conn.getOutputStream()); Log.i(AnkiDroidApp.TAG, "Pass"); ds.writeBytes(TWO_HYPHENS + MIME_BOUNDARY + END); ds.writeBytes("Content-Disposition: form-data; name=\"p\"" + END + END + password + END); Log.i(AnkiDroidApp.TAG, "User"); ds.writeBytes(TWO_HYPHENS + MIME_BOUNDARY + END); ds.writeBytes("Content-Disposition: form-data; name=\"u\"" + END + END + username + END); Log.i(AnkiDroidApp.TAG, "DeckName"); ds.writeBytes(TWO_HYPHENS + MIME_BOUNDARY + END); ds.writeBytes("Content-Disposition: form-data; name=\"d\"" + END + END + deckName + END); Log.i(AnkiDroidApp.TAG, "Deck"); ds.writeBytes(TWO_HYPHENS + MIME_BOUNDARY + END); ds.writeBytes("Content-Disposition: form-data; name=\"deck\";filename=\"deck\"" + END); ds.writeBytes("Content-Type: application/octet-stream" + END); ds.writeBytes(END); FileInputStream fStream = new FileInputStream(deckPath); byte[] buffer = new byte[Utils.CHUNK_SIZE]; int length = -1; Deflater deflater = new Deflater(Deflater.BEST_SPEED); DeflaterOutputStream dos = new DeflaterOutputStream(ds, deflater); Log.i(AnkiDroidApp.TAG, "Writing buffer..."); while ((length = fStream.read(buffer)) != -1) { dos.write(buffer, 0, length); Log.i(AnkiDroidApp.TAG, "Length = " + length); } dos.finish(); fStream.close(); ds.writeBytes(END); ds.writeBytes(TWO_HYPHENS + MIME_BOUNDARY + TWO_HYPHENS + END); Log.i(AnkiDroidApp.TAG, "Closing streams..."); ds.flush(); ds.close(); // Ensure we got the HTTP 200 response code int responseCode = conn.getResponseCode(); if (responseCode != 200) { Log.i(AnkiDroidApp.TAG, "Response code = " + responseCode); // throw new Exception(String.format("Received the response code %d from the URL %s", responseCode, // url)); } else { Log.i(AnkiDroidApp.TAG, "Response code = 200"); } // Read the response InputStream is = conn.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] bytes = new byte[1024]; int bytesRead; while ((bytesRead = is.read(bytes)) != -1) { baos.write(bytes, 0, bytesRead); } byte[] bytesReceived = baos.toByteArray(); baos.close(); is.close(); String response = new String(bytesReceived); Log.i(AnkiDroidApp.TAG, "Finished!"); } catch (MalformedURLException e) { Log.i(AnkiDroidApp.TAG, "MalformedURLException = " + e.getMessage()); } catch (IOException e) { Log.i(AnkiDroidApp.TAG, "IOException = " + e.getMessage()); } }
From source file:com.docdoku.client.data.MainModel.java
private void performHeadHTTPMethod(String pURL) throws MalformedURLException, IOException { URL url = new URL(pURL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setUseCaches(false); conn.setAllowUserInteraction(true);//from w ww .ja v a 2 s . c o m conn.setRequestProperty("Connection", "Keep-Alive"); byte[] encoded = org.apache.commons.codec.binary.Base64 .encodeBase64((getLogin() + ":" + getPassword()).getBytes("ISO-8859-1")); conn.setRequestProperty("Authorization", "Basic " + new String(encoded, "US-ASCII")); conn.setRequestMethod("HEAD"); conn.connect(); int code = conn.getResponseCode(); System.out.println("Head HTTP response code: " + code); }
From source file:com.culvereq.vimp.networking.ConnectionHandler.java
public ServiceRecord addServiceRecord(TempServiceRecord serviceRecord) throws IOException, JSONException { URL requestURL = new URL(serviceURL + "add"); HttpURLConnection connection = (HttpURLConnection) requestURL.openConnection(); connection.setDoInput(true);/*w ww .j a v 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-id=" + serviceRecord.getParentVehicle().getId(); urlParameters += "&type-id=" + serviceRecord.getType().getValue(); urlParameters += "&service-desc=" + serviceRecord.getDescription(); urlParameters += "&service-date=" + serviceRecord.getServiceDate().getMillis() / 1000L; urlParameters += "&service-mileage=" + serviceRecord.getMileage(); 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().deserializeService(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:easyshop.downloadhelper.HttpPageGetter.java
public HttpPage getDHttpPage(PageRef url, String charSet) { count++;//from w w w . ja va 2 s . c o m log.debug("getURL(" + count + ")"); if (url.getUrlStr() == null) { ConnResponse conRes = new ConnResponse(null, null, 0, 0, 0); return new OriHttpPage(-1, null, null, null, conRes, null); } URL requestedURL = null; try { requestedURL = new URL(url.getUrlStr()); } catch (MalformedURLException e1) { // TODO Auto-generated catch block log.error("wrong urlstr" + url.getUrlStr()); ConnResponse conRes = new ConnResponse(null, null, 0, 0, 0); return new OriHttpPage(-1, null, null, null, conRes, null); } ; // System.out.println(""+requestedURL.toExternalForm()); URL referer = null; try { log.debug("Creating HTTP connection to " + requestedURL); HttpURLConnection conn = (HttpURLConnection) requestedURL.openConnection(); if (referer != null) { log.debug("Setting Referer header to " + referer); conn.setRequestProperty("Referer", referer.toExternalForm()); } if (userAgent != null) { log.debug("Setting User-Agent to " + userAgent); conn.setRequestProperty("User-Agent", userAgent); } // DateFormat dateFormat=DateFormat.getDateInstance(); // conn.setRequestProperty("If-Modlfied-Since",dateFormat.parse("2005-08-15 20:18:30").toGMTString()); conn.setUseCaches(false); // conn.setRequestProperty("connection","keep-alive"); for (Iterator it = conn.getRequestProperties().keySet().iterator(); it.hasNext();) { String key = (String) it.next(); if (key == null) { break; } String value = conn.getHeaderField(key); // System.out.println("Request header " + key + ": " + value); } log.debug("Opening URL"); long startTime = System.currentTimeMillis(); conn.connect(); String resp = conn.getResponseMessage(); log.debug("Remote server response: " + resp); int code = conn.getResponseCode(); if (code != 200) { log.error("Could not get connection for code=" + code); System.err.println("Could not get connection for code=" + code); ConnResponse conRes = new ConnResponse(null, null, 0, 0, code); return new HttpPage(requestedURL.toExternalForm(), null, conRes, null); } // if (conn.getContentLength()<=0||conn.getContentLength()>10000000){ // log.error("Content length==0"); // System.err.println("Content length==0"); // ConnResponse conRes=new ConnResponse(null,null,null,0,0,-100); // return new URLObject(-1,requestedURL, null,null,conRes); // } String respStr = conn.getHeaderField(0); long serverDate = conn.getDate(); // log.info("Server response: " + respStr); for (int i = 1; i < conn.getHeaderFields().size(); i++) { String key = conn.getHeaderFieldKey(i); if (key == null) { break; } String value = conn.getHeaderField(key); // System.out.println("Received header " + key + ": " + value); // log.debug("Received header " + key + ": " + value); } // log.debug("Getting buffered input stream from remote connection"); log.debug("start download(" + count + ")"); BufferedInputStream remoteBIS = new BufferedInputStream(conn.getInputStream()); ByteArrayOutputStream baos = new ByteArrayOutputStream(10240); byte[] buf = new byte[1024]; int bytesRead = 0; while (bytesRead >= 0) { baos.write(buf, 0, bytesRead); bytesRead = remoteBIS.read(buf); } // baos.write(remoteBIS.read(new byte[conn.getContentLength()])); // remoteBIS.close(); byte[] content = baos.toByteArray(); long timeTaken = System.currentTimeMillis() - startTime; if (timeTaken < 100) timeTaken = 500; int bytesPerSec = (int) ((double) content.length / ((double) timeTaken / 1000.0)); // log.info("Downloaded " + content.length + " bytes, " + bytesPerSec + " bytes/sec"); if (content.length < conn.getContentLength()) { log.warn("Didn't download full content for URL: " + url); // failureCount++; ConnResponse conRes = new ConnResponse(conn.getContentType(), null, content.length, serverDate, code); return new HttpPage(requestedURL.toExternalForm(), null, conRes, conn.getContentType()); } log.debug("download(" + count + ")"); ConnResponse conRes = new ConnResponse(conn.getContentType(), null, conn.getContentLength(), serverDate, code); String c = charSet; if (c == null) c = conRes.getCharSet(); HttpPage obj = new HttpPage(requestedURL.toExternalForm(), content, conRes, c); return obj; } catch (IOException ioe) { log.warn("Caught IO Exception: " + ioe.getMessage(), ioe); failureCount++; ConnResponse conRes = new ConnResponse(null, null, 0, 0, 0); return new HttpPage(requestedURL.toExternalForm(), null, conRes, null); } catch (Exception e) { log.warn("Caught Exception: " + e.getMessage(), e); failureCount++; ConnResponse conRes = new ConnResponse(null, null, 0, 0, 0); return new HttpPage(requestedURL.toExternalForm(), null, conRes, null); } }
From source file:compiler.downloader.MegaHandler.java
private String api_request(String data) { HttpURLConnection connection = null; try {//w ww.j a v a 2 s . c om String urlString = "https://g.api.mega.co.nz/cs?id=" + sequence_number; if (sid != null) { urlString += "&sid=" + sid; } URL url = new URL(urlString); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); //use post method connection.setDoOutput(true); //we will send stuff connection.setDoInput(true); //we want feedback connection.setUseCaches(false); //no caches connection.setAllowUserInteraction(false); connection.setRequestProperty("Content-Type", "text/xml"); OutputStream out = connection.getOutputStream(); try { OutputStreamWriter wr = new OutputStreamWriter(out); wr.write("[" + data + "]"); //data is JSON object containing the api commands wr.flush(); wr.close(); } catch (IOException e) { e.printStackTrace(); } finally { //in this case, we are ensured to close the output stream if (out != null) { out.close(); } } InputStream in = connection.getInputStream(); StringBuffer response = new StringBuffer(); try { BufferedReader rd = new BufferedReader(new InputStreamReader(in)); String line; while ((line = rd.readLine()) != null) { response.append(line); } rd.close(); //close the reader } catch (IOException e) { e.printStackTrace(); } finally { //in this case, we are ensured to close the input stream if (in != null) { in.close(); } } return response.toString().substring(1, response.toString().length() - 1); } catch (IOException e) { e.printStackTrace(); } return ""; }
From source file:com.mendhak.gpslogger.senders.googledrive.GoogleDriveJob.java
private String createEmptyFile(String authToken, String fileName, String mimeType, String parentFolderId) { String fileId = null;//from ww w . ja v a 2s. co m HttpURLConnection conn = null; String createFileUrl = "https://www.googleapis.com/drive/v2/files"; String createFilePayload = " {\n" + " \"title\": \"" + fileName + "\",\n" + " \"mimeType\": \"" + mimeType + "\",\n" + " \"parents\": [\n" + " {\n" + " \"id\": \"" + parentFolderId + "\"\n" + " }\n" + " ]\n" + " }"; try { URL url = new URL(createFileUrl); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("User-Agent", "GPSLogger for Android"); conn.setRequestProperty("Authorization", "Bearer " + authToken); conn.setRequestProperty("Content-Type", "application/json"); conn.setUseCaches(false); conn.setDoInput(true); conn.setDoOutput(true); conn.setConnectTimeout(10000); conn.setReadTimeout(30000); DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); wr.writeBytes(createFilePayload); wr.flush(); wr.close(); fileId = null; String fileMetadata = Streams.getStringFromInputStream(conn.getInputStream()); JSONObject fileMetadataJson = new JSONObject(fileMetadata); fileId = fileMetadataJson.getString("id"); LOG.debug("File created with ID " + fileId + " of type " + mimeType); } catch (Exception e) { LOG.error("Could not create file", e); } finally { if (conn != null) { conn.disconnect(); } } return fileId; }
From source file:AIR.Common.Web.HttpWebHelper.java
public String submitForm1(String url, Map<String, Object> formParameters, int maxTries, _Ref<Integer> httpStatusCode) throws IOException { // 1 Create the Apache Commons PostMethod object. // 2 Add everything from formParameters to the PostMethod object as // parameters. Remember to run .toString on each object. // 3 Make POST calls as show in here: // http://hc.apache.org/httpclient-3.x/tutorial.html // 4 One divergence from example code in step 3 is that the whole block // needs to go into a for loop that will loop over maxTries time until // successful or maxTries reached. // 5 If any exception happens then wrap that exception in an IOException. // 6 Set httpStatusCode to statusCode from the example. byte[] encodeDataInBytes = null; StringBuilder strn = new StringBuilder(); StringBuilder payloadBuilder = new StringBuilder(); for (Map.Entry<String, Object> entry : formParameters.entrySet()) { payloadBuilder.append(UrlEncoderDecoderUtils.encode(entry.getKey()) + "=" + UrlEncoderDecoderUtils.encode(entry.getValue().toString()) + "&"); strn.append(entry.getKey() + "=" + entry.getValue().toString() + "\n"); }/* ww w. j a va2s . c o m*/ String encodedData = payloadBuilder.toString(); // _logger.info ("Python request URL: " + url + " ; request data: " + // encodedData); encodeDataInBytes = encodedData.getBytes(); for (int i = 1; i <= maxTries; i++) { HttpURLConnection connection = null; OutputStream os = null; BufferedReader rd = null; try { connection = (HttpURLConnection) new URL(url).openConnection(); connection.setConnectTimeout(getTimeoutInMillis()); connection.setReadTimeout(getTimeoutInMillis()); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Length", "" + encodeDataInBytes.length); // connection.setRequestProperty ("Connection", "Close"); //connection.setRequestProperty ("expect", "100-continue"); connection.setUseCaches(false); os = connection.getOutputStream(); os.write(encodeDataInBytes); httpStatusCode.set(connection.getResponseCode()); // try reading the result from the server. if there is an error we will // automatically go to the exception handler rd = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuilder sb = new StringBuilder(); String line = null; while ((line = rd.readLine()) != null) sb.append(line + "\n"); return sb.toString(); } catch (Exception e) { _logger.error("Error Url : " + url + " ; post data: " + encodedData); _logger.error("================Start Raw==============\n"); _logger.error(strn.toString()); _logger.error("================End Raw==============\n"); _logger.error("Could not retrieve response: ", e.getMessage()); _logger.error("Stacktrace : " + TDSStringUtils.exceptionToString(e)); if (i == maxTries) throw new IOException(e); } finally { // close the output stream try { if (os != null) os.close(); } catch (Exception e) { _logger.error("Error closing socket output stream: ", e.getMessage()); _logger.error("Stacktrace : " + TDSStringUtils.exceptionToString(e)); e.printStackTrace(); } // close the input stream try { if (rd != null) rd.close(); } catch (Exception e) { _logger.error("Error closing socket input stream: ", e.getMessage()); _logger.error("Stacktrace : " + TDSStringUtils.exceptionToString(e)); e.printStackTrace(); } try { if (connection != null) { // read the errorStream if any and close it. InputStream es = ((HttpURLConnection) connection).getErrorStream(); if (es != null) { try { BufferedReader esBfr = new BufferedReader(new InputStreamReader(es)); String line = null; // read the response body while ((line = esBfr.readLine()) != null) { } } catch (Exception exp) { _logger.error("Stacktrace : " + TDSStringUtils.exceptionToString(exp)); } es.close(); } } } catch (Exception e) { _logger.error("Printing error stream: ", e.getMessage()); _logger.error("Stacktrace : " + TDSStringUtils.exceptionToString(e)); e.printStackTrace(); } /* * try { if (connection != null) { connection.disconnect (); } } catch * (Exception e) { _logger.error ("Disconnecting socket: ", e.getMessage * ()); _logger.error ("Stacktrace : " + * TDSStringUtils.exceptionToString (e)); e.printStackTrace (); } */ } } // for some reason we ended here. just throw an exception. throw new IOException("Could not retrive result."); }
From source file:com.lastdaywaiting.example.kalkan.service.SecureManager.java
/** * CRL- ? , ? ? , ? ?/*from w w w. j a v a2 s . c o m*/ * ? * * @param crlName */ private void loadCrlObject(String crlName) { TypeOfCrlLoaded oldState = MAP_OF_LOAD_CRL_LABEL.get(crlName); if (TypeOfCrlLoaded.LOADING.equals(oldState)) { return; } MAP_OF_LOAD_CRL_LABEL.put(crlName, TypeOfCrlLoaded.LOADING); String location = MAP_OF_CRL_PATH.get(crlName); try { URL url = new URL(location); HttpURLConnection conn = null; if (useProxy) { Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyAddress, proxyPort)); conn = (HttpURLConnection) url.openConnection(proxy); } else { conn = (HttpURLConnection) url.openConnection(); } conn.setUseCaches(false); conn.setDoInput(true); conn.connect(); if (conn.getResponseCode() == 200) { CertificateFactory cf = CertificateFactory.getInstance("X.509", "KALKAN"); X509CRL crlObject = (X509CRL) cf.generateCRL(conn.getInputStream()); MAP_OF_XCRL.put(crlName, crlObject); } else { String msg = "(1) ? CRL- : '" + location + "' : " + conn.getResponseCode() + " , " + conn.getResponseMessage(); log.warning(msg); } } catch (Exception e) { String msg = "(1) ? CRL- : '" + location + "' : " + e.getMessage(); log.warning(msg); } //MAP_OF_LOAD_CRL_LABEL.put(crlName, oldState ) ; MAP_OF_LOAD_CRL_TIME.put(crlName, new Date()); MAP_OF_LOAD_CRL_LABEL.put(crlName, TypeOfCrlLoaded.LOADED); }