List of usage examples for java.net HttpURLConnection setUseCaches
public void setUseCaches(boolean usecaches)
From source file:org.bigbluebutton.impl.BBBProxyImpl.java
/** Make an API call */ public static Map<String, Object> doAPICall(String query) { Map<String, Object> response = new HashMap<String, Object>(); StringBuilder urlStr = new StringBuilder(query); try {//from ww w .j a v a2s .c o m // open connection log.debug("doAPICall.call: " + query); URL url = new URL(urlStr.toString()); HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection(); httpConnection.setUseCaches(false); httpConnection.setDoOutput(true); httpConnection.setRequestMethod("GET"); httpConnection.connect(); int responseCode = httpConnection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { // read response InputStreamReader isr = null; BufferedReader reader = null; StringBuilder xml = new StringBuilder(); try { isr = new InputStreamReader(httpConnection.getInputStream(), "UTF-8"); reader = new BufferedReader(isr); String line = reader.readLine(); while (line != null) { if (!line.startsWith("<?xml version=\"1.0\"?>")) xml.append(line.trim()); line = reader.readLine(); } } finally { if (reader != null) reader.close(); if (isr != null) isr.close(); } httpConnection.disconnect(); // parse response log.debug("doAPICall.responseXml: " + xml); //Patch to fix the NaN error String stringXml = xml.toString(); stringXml = stringXml.replaceAll(">.\\s+?<", "><"); DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder; try { docBuilder = docBuilderFactory.newDocumentBuilder(); Document dom = null; dom = docBuilder.parse(new InputSource(new StringReader(stringXml))); response = getNodesAsMap(dom, "response"); log.debug("doAPICall.responseMap: " + response); String returnCode = (String) response.get("returncode"); if (BBBProxy.APIRESPONSE_FAILED.equals(returnCode)) { log.debug("doAPICall." + (String) response.get("messageKey") + ": Message=" + (String) response.get("message")); } } catch (ParserConfigurationException e) { log.debug("Failed to initialise BaseProxy: " + e.getMessage()); } } else { log.debug("doAPICall.HTTPERROR: Message=" + "BBB server responded with HTTP status code " + responseCode); } } catch (IOException e) { log.debug("doAPICall.IOException: Message=" + e.getMessage()); } catch (SAXException e) { log.debug("doAPICall.SAXException: Message=" + e.getMessage()); } catch (IllegalArgumentException e) { log.debug("doAPICall.IllegalArgumentException: Message=" + e.getMessage()); } catch (Exception e) { log.debug("doAPICall.Exception: Message=" + e.getMessage()); } return response; }
From source file:flow.visibility.tapping.OpenDaylightHelper.java
/** The function for inserting the flow */ public static boolean installFlow(JSONObject postData, String user, String password, String baseURL) { StringBuffer result = new StringBuffer(); /** Check the connection to ODP REST API page */ try {/*from w w w . ja va 2s .co m*/ if (!baseURL.contains("http")) { baseURL = "http://" + baseURL; } baseURL = baseURL + "/controller/nb/v2/flowprogrammer/default/node/OF/" + postData.getJSONObject("node").get("id") + "/staticFlow/" + postData.get("name"); /** Create URL = base URL + container */ URL url = new URL(baseURL); /** Create authentication string and encode it to Base64*/ String authStr = user + ":" + password; String encodedAuthStr = Base64.encodeBase64String(authStr.getBytes()); /** Create Http connection */ HttpURLConnection connection = (HttpURLConnection) url.openConnection(); /** Set connection properties */ connection.setRequestMethod("PUT"); connection.setRequestProperty("Authorization", "Basic " + encodedAuthStr); connection.setRequestProperty("Content-Type", "application/json"); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); /** Set JSON Post Data */ OutputStream os = connection.getOutputStream(); os.write(postData.toString().getBytes()); os.close(); /** Get the response from connection's inputStream */ InputStream content = (InputStream) connection.getInputStream(); BufferedReader in = new BufferedReader(new InputStreamReader(content)); String line = ""; while ((line = in.readLine()) != null) { result.append(line); } } catch (Exception e) { e.printStackTrace(); } /** checking the result of REST API connection */ if ("success".equalsIgnoreCase(result.toString())) { return true; } else { return false; } }
From source file:lu.list.itis.dkd.aig.util.FusekiHttpHelper.java
/** * Upload ontology content on specified dataset. Graph used is the default * one except if specified/*from ww w . j a v a 2s . c o m*/ * * @param ontology * @param datasetName * @param graphName * @throws IOException * @throws HttpException */ public static void uploadOntology(InputStream ontology, String datasetName, @Nullable String graphName) throws IOException, HttpException { graphName = Strings.emptyToNull(graphName); logger.info("upload ontology in dataset: " + datasetName + " graph:" + Strings.nullToEmpty(graphName)); boolean createGraph = (graphName != null) ? true : false; String dataSetEncoded = URLEncoder.encode(datasetName, "UTF-8"); String graphEncoded = createGraph ? URLEncoder.encode(graphName, "UTF-8") : null; URL url = new URL(HOST + '/' + dataSetEncoded + "/data" + (createGraph ? "?graph=" + graphEncoded : "")); final HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection(); String boundary = "------------------" + System.currentTimeMillis() + Long.toString(Math.round(Math.random() * 1000)); httpConnection.setUseCaches(false); httpConnection.setRequestMethod("POST"); httpConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); httpConnection.setRequestProperty("Connection", "keep-alive"); httpConnection.setRequestProperty("Cache-Control", "no-cache"); // set content httpConnection.setDoOutput(true); final OutputStreamWriter out = new OutputStreamWriter(httpConnection.getOutputStream()); out.write(BOUNDARY_DECORATOR + boundary + EOL); out.write("Content-Disposition: form-data; name=\"files[]\"; filename=\"ontology.owl\"" + EOL); out.write("Content-Type: application/octet-stream" + EOL + EOL); out.write(CharStreams.toString(new InputStreamReader(ontology))); out.write(EOL + BOUNDARY_DECORATOR + boundary + BOUNDARY_DECORATOR + EOL); out.close(); // handle HTTP/HTTPS strange behaviour httpConnection.connect(); httpConnection.disconnect(); // handle response switch (httpConnection.getResponseCode()) { case HttpURLConnection.HTTP_CREATED: checkState(createGraph, "bad state - code:" + httpConnection.getResponseCode() + " message: " + httpConnection.getResponseMessage()); break; case HttpURLConnection.HTTP_OK: checkState(!createGraph, "bad state - code:" + httpConnection.getResponseCode() + " message: " + httpConnection.getResponseMessage()); break; default: throw new HttpException( httpConnection.getResponseCode() + " message: " + httpConnection.getResponseMessage()); } }
From source file:com.openforevent.main.UserPosition.java
public static Map<String, Object> userLocationProperties(DispatchContext ctx, Map<String, ? extends Object> context) throws IOException { Delegator delegator = ctx.getDelegator(); LocalDispatcher dispatcher = ctx.getDispatcher(); String visitId = (String) context.get("visitId"); if (Debug.infoOn()) { Debug.logInfo("In userLocationProperties", module); }//from www . j a va 2 s .co m // get user coords coordsOfUserPosition(ctx, context); URL url = new URL( "https://graph.facebook.com/search?since=now&limit=4&q=2012-05-07&type=event&access_token=" + "AAACEdEose0cBAN9CB2ErxVN3JvK2gsrLslPt6e6Y7hJ0OrMEkMoyNwvHgSZCAEu2lCHZALlVWXZCW5JL8asMWoaPN3UAXFpZBsJJ6SvXRAAIZAXeTo0fD"); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); // Set properties of the connection urlConnection.setRequestMethod("GET"); urlConnection.setDoInput(true); urlConnection.setDoOutput(true); urlConnection.setUseCaches(false); urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // Retrieve the output int responseCode = urlConnection.getResponseCode(); InputStream inputStream; if (responseCode == HttpURLConnection.HTTP_OK) { inputStream = urlConnection.getInputStream(); } else { inputStream = urlConnection.getErrorStream(); } StringWriter writer = new StringWriter(); IOUtils.copy(inputStream, writer, "UTF-8"); String theString = writer.toString(); Debug.logInfo("Facebook stream = ", theString); if (theString.contains("AuthException") == true) { url = new URL("https://graph.facebook.com/oauth/access_token?" + "client_id= 283576871735609&" + "client_secret= 5cf1fe4e531dff8de228bfac61b8fdfa&" + "grant_type=fb_exchange_token&" + "fb_exchange_token=" + "AAACEdEose0cBAN9CB2ErxVN3JvK2gsrLslPt6e6Y7hJ0OrMEkMoyNwvHgSZCAEu2lCHZALlVWXZCW5JL8asMWoaPN3UAXFpZBsJJ6SvXRAAIZAXeTo0fD"); HttpURLConnection urlConnection1 = (HttpURLConnection) url.openConnection(); // Set properties of the connection urlConnection1.setRequestMethod("GET"); urlConnection1.setDoInput(true); urlConnection1.setDoOutput(true); urlConnection1.setUseCaches(false); urlConnection1.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // Retrieve the output int responseCode1 = urlConnection1.getResponseCode(); InputStream inputStream1; if (responseCode == HttpURLConnection.HTTP_OK) { inputStream1 = urlConnection1.getInputStream(); } else { inputStream1 = urlConnection1.getErrorStream(); } StringWriter writer1 = new StringWriter(); IOUtils.copy(inputStream1, writer1, "UTF-8"); String theString1 = writer1.toString(); Debug.logInfo("Facebook stream1 = ", theString1); } Map<String, Object> paramOut = FastMap.newInstance(); paramOut.put("geoName", "aaa"); paramOut.put("abbreviation", "bbb"); return paramOut; }
From source file:com.codelanx.codelanxlib.util.auth.UUIDFetcher.java
/** * Opens the connection to Mojang's profile API * //from ww w. j av a2s . c om * @since 0.0.1 * @version 0.0.1 * * @return The {@link HttpURLConnection} object to the API server * @throws IOException If there is a problem opening the stream, a malformed * URL, or if there is a ProtocolException */ private static HttpURLConnection createConnection() throws IOException { URL url = new URL(UUIDFetcher.PROFILE_URL); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); return connection; }
From source file:fr.zcraft.zlib.tools.mojang.UUIDFetcher.java
/** * Opens a GET connection.//from www.j a va2s . c o m * * @param url The URL to connect to. * * @return A GET connection to this URL. * @throws IOException If an exception occurred while contacting the server. */ static private HttpURLConnection getGETConnection(String url) throws IOException { HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); connection.setRequestMethod("GET"); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); return connection; }
From source file:com.keepsafe.switchboard.SwitchBoard.java
/** * Returns a String containing the server response from a GET request * @param address Valid http addess./* ww w . java 2s.c om*/ * @param params String of params. Multiple params seperated with &. No leading ? in string * @return Returns String from server or null when failed. */ private static String readFromUrlGET(String address, String params) { if (address == null || params == null) return null; String completeUrl = address + "?" + params; if (DEBUG) Log.d(TAG, "readFromUrl(): " + completeUrl); try { URL url = new URL(completeUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setUseCaches(false); connection.setDoOutput(true); // get response InputStream is = connection.getInputStream(); InputStreamReader inputStreamReader = new InputStreamReader(is); BufferedReader bufferReader = new BufferedReader(inputStreamReader, 8192); String line = ""; StringBuffer resultContent = new StringBuffer(); while ((line = bufferReader.readLine()) != null) { if (DEBUG) Log.d(TAG, line); resultContent.append(line); } bufferReader.close(); if (DEBUG) Log.d(TAG, "readFromUrl() result: " + resultContent.toString()); return resultContent.toString(); } catch (ProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }
From source file:com.gson.util.HttpKit.java
/** * /* www . j ava2 s.c o m*/ * @param url * @param params * @param file * @return * @throws IOException * @throws NoSuchAlgorithmException * @throws NoSuchProviderException * @throws KeyManagementException */ public static String upload(String url, File file) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException { String BOUNDARY = "----WebKitFormBoundaryiDGnV9zdZA1eM1yL"; // ? StringBuffer bufferRes = null; URL urlGet = new URL(url); HttpURLConnection conn = (HttpURLConnection) urlGet.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.107 Safari/537.36"); conn.setRequestProperty("Charsert", "UTF-8"); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); OutputStream out = new DataOutputStream(conn.getOutputStream()); byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();// ?? StringBuilder sb = new StringBuilder(); sb.append("--"); sb.append(BOUNDARY); sb.append("\r\n"); sb.append("Content-Disposition: form-data;name=\"media\";filename=\"" + file.getName() + "\"\r\n"); sb.append("Content-Type:application/octet-stream\r\n\r\n"); byte[] data = sb.toString().getBytes(); out.write(data); DataInputStream fs = new DataInputStream(new FileInputStream(file)); int bytes = 0; byte[] bufferOut = new byte[1024]; while ((bytes = fs.read(bufferOut)) != -1) { out.write(bufferOut, 0, bytes); } out.write("\r\n".getBytes()); // fs.close(); out.write(end_data); out.flush(); out.close(); // BufferedReader???URL? InputStream in = conn.getInputStream(); BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET)); String valueString = null; bufferRes = new StringBuffer(); while ((valueString = read.readLine()) != null) { bufferRes.append(valueString); } in.close(); if (conn != null) { // conn.disconnect(); } return bufferRes.toString(); }
From source file:com.hichengdai.qlqq.front.util.HttpKit.java
/** * /*from w ww. j a v a 2s . co m*/ * * @param url * @param params * @param file * @return * @throws IOException * @throws NoSuchAlgorithmException * @throws NoSuchProviderException * @throws KeyManagementException */ public static String upload(String url, File file) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException { String BOUNDARY = "----WebKitFormBoundaryiDGnV9zdZA1eM1yL"; // ? StringBuffer bufferRes = null; URL urlGet = new URL(url); HttpURLConnection conn = (HttpURLConnection) urlGet.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.107 Safari/537.36"); conn.setRequestProperty("Charsert", "UTF-8"); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); OutputStream out = new DataOutputStream(conn.getOutputStream()); byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();// ?? StringBuilder sb = new StringBuilder(); sb.append("--"); sb.append(BOUNDARY); sb.append("\r\n"); sb.append("Content-Disposition: form-data;name=\"media\";filename=\"" + file.getName() + "\"\r\n"); sb.append("Content-Type:application/octet-stream\r\n\r\n"); byte[] data = sb.toString().getBytes(); out.write(data); DataInputStream fs = new DataInputStream(new FileInputStream(file)); int bytes = 0; byte[] bufferOut = new byte[1024]; while ((bytes = fs.read(bufferOut)) != -1) { out.write(bufferOut, 0, bytes); } out.write("\r\n".getBytes()); // fs.close(); out.write(end_data); out.flush(); out.close(); // BufferedReader???URL? InputStream in = conn.getInputStream(); BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET)); String valueString = null; bufferRes = new StringBuffer(); while ((valueString = read.readLine()) != null) { bufferRes.append(valueString); } in.close(); if (conn != null) { // conn.disconnect(); } return bufferRes.toString(); }
From source file:com.concentricsky.android.khanacademy.util.ThumbnailManager.java
/** * Attempt to download a bitmap from the given url. * /*from w w w . j a va 2 s . c o m*/ * @param url The url of the thumbnail to download. * @return A {@link Bitmap} of the thumbnail, or {@code null} if it cannot be downloaded and is not cached locally. * @throws java.net.MalformedURLException if the url is malformed! * @throws java.io.IOException if a connection cannot be opened to the given url, or if an IOException is thrown by {@link ResponseCache} or by {@link CacheResponse}. */ public static Bitmap bitmap_from_url(String url) throws java.net.MalformedURLException, IOException { HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); connection.setConnectTimeout(CONNECT_TIMEOUT); connection.setUseCaches(true); InputStream input = null; try { connection.connect(); input = connection.getInputStream(); return BitmapFactory.decodeStream(input); } catch (SocketTimeoutException e) { e.printStackTrace(); return null; } finally { if (input != null) input.close(); } }