List of usage examples for java.net URL openConnection
public URLConnection openConnection() throws java.io.IOException
From source file:connector.ISConnector.java
public static JSONObject processRequest(String servlet, byte[] query) { JSONObject response = null;/*from ww w . ja v a2s . c o m*/ if (servlet != null && !servlet.startsWith("/")) servlet = "/" + servlet; try { // Establish HTTP connection with Identity Service URL url = new URL(CONTEXT_PATH + servlet); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); conn.setAllowUserInteraction(false); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); //Create the form content try (OutputStream out = conn.getOutputStream()) { out.write(query); out.close(); } // Buffer the result into a string BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while ((line = rd.readLine()) != null) { sb.append(line); } rd.close(); conn.disconnect(); response = (JSONObject) new JSONParser().parse(sb.toString()); } catch (Exception e) { e.printStackTrace(); } return response; }
From source file:localSPs.SpiderOakAPI.java
public static String connectWithREST(String url, String method) throws IOException, ProtocolException, MalformedURLException { String newURL = ""; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // Connect with a REST Method: GET, DELETE, PUT con.setRequestMethod(method);/*from w w w . ja v a 2 s.c o m*/ //add request header con.setReadTimeout(20000); con.setConnectTimeout(20000); con.setRequestProperty("User-Agent", "Mozilla/5.0"); if (method.equals(DELETE) || method.equals(PUT)) con.addRequestProperty("Authorization", "Base M5XWW5JNONZWUMSANBXXI3LBNFWC4Y3PNU5E2NDSNFXTEMZVJ5QWW"); int responseCode = con.getResponseCode(); // Read response BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); newURL = response.toString(); return newURL; }
From source file:Main.java
public static void DownloadFile(String u) { try {/* w ww .java 2 s .co m*/ Logd(TAG, "Starting download of: " + u); URL url = new URL(u); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.setDoOutput(true); urlConnection.connect(); //File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); checkStorageDir(); File storageDir = new File( Environment.getExternalStorageDirectory() + "/Android/data/com.nowsci.odm/.storage"); File file = new File(storageDir, getFileName(u)); Logd(TAG, "Storage directory: " + storageDir.toString()); Logd(TAG, "File name: " + file.toString()); FileOutputStream fileOutput = new FileOutputStream(file); InputStream inputStream = urlConnection.getInputStream(); byte[] buffer = new byte[1024]; int bufferLength = 0; while ((bufferLength = inputStream.read(buffer)) > 0) { fileOutput.write(buffer, 0, bufferLength); } fileOutput.close(); Logd(TAG, "File written"); } catch (ProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:com.fluidops.iwb.cms.util.OpenUp.java
public static List<Statement> extract(String text, URI uri) throws IOException { List<Statement> res = new ArrayList<Statement>(); String textEncoded = URLEncoder.encode(text, "UTF-8"); String send = "format=rdfxml&text=" + textEncoded; // service limit is 10000 chars if (mode() == Mode.demo) send = stripToDemoLimit(send);//from w ww.j ava 2 s. c o m // GET only works for smaller texts // URL url = new URL("http://openup.tso.co.uk/des/enriched-text?text=" + textEncoded + "&format=rdfxml"); URL url = new URL(getConfig().getOpenUpUrl()); URLConnection conn = url.openConnection(); conn.setDoOutput(true); IOUtils.write(send, conn.getOutputStream()); Repository repository = new SailRepository(new MemoryStore()); try { repository.initialize(); RepositoryConnection con = repository.getConnection(); con.add(conn.getInputStream(), uri.stringValue(), RDFFormat.RDFXML); RepositoryResult<Statement> iter = con.getStatements(null, null, null, false); while (iter.hasNext()) { Statement s = iter.next(); res.add(s); } } catch (Exception e) { throw new RuntimeException(e); } return res; }
From source file:Main.java
private static InputStream getInputStreamFromUrl_V9(Context paramContext, String paramString) { if (confirmDownload(paramContext, paramString)) { try {// w w w.j a va2 s .com URL localURL = new URL(paramString); HttpURLConnection localHttpURLConnection2 = (HttpURLConnection) localURL.openConnection(); localHttpURLConnection2.setRequestProperty("Accept-Charset", "UTF-8"); localHttpURLConnection2.setReadTimeout(30000); localHttpURLConnection2.setConnectTimeout(30000); localHttpURLConnection2.setRequestMethod("GET"); localHttpURLConnection2.setDoInput(true); localHttpURLConnection2.connect(); return localHttpURLConnection2.getInputStream(); } catch (Throwable localThrowable) { localThrowable.printStackTrace(); return null; } } else { return null; } }
From source file:org.liberty.android.fantastischmemo.downloader.DownloaderUtils.java
public static File downloadFile(String url, String savedPath) throws IOException { File outFile = new File(savedPath); OutputStream out;/*from w ww .j a va 2s . com*/ // Delete and backup if the file exists AMUtil.deleteFileWithBackup(savedPath); // Create the dir if necessary File parentDir = outFile.getParentFile(); parentDir.mkdirs(); outFile.createNewFile(); out = new FileOutputStream(outFile); Log.i(TAG, "URL to download is: " + url); URL myURL = new URL(url); URLConnection ucon = myURL.openConnection(); byte[] buf = new byte[8192]; InputStream is = ucon.getInputStream(); BufferedInputStream bis = new BufferedInputStream(is, 8192); int len = 0; while ((len = bis.read(buf)) != -1) { out.write(buf, 0, len); } out.close(); is.close(); return outFile; }
From source file:Main.java
public static Document getUrlAsDocument(String urlAsString, int timeout) throws Exception { URL url = new URL(urlAsString); //using proxy may increase latency HttpURLConnection hConn = (HttpURLConnection) url.openConnection(); hConn.setReadTimeout(timeout);/*from w ww . j a v a 2s. co m*/ hConn.setConnectTimeout(timeout); // hConn.setRequestProperty("Accept-Encoding", "gzip, deflate"); InputStream is = hConn.getInputStream(); // if ("gzip".equals(hConn.getContentEncoding())) // is = new GZIPInputStream(is); return newDocumentBuilder().parse(is); }
From source file:Main.java
/** * * @param url - String//from w w w. j a v a 2 s.c o m * @param reqParam refer POST method * @param accessToken - String * @return ArrayList<String> 0: responseBody * 1: responseCode */ public static ArrayList<String> getResponse(String url, String reqParam, String accessToken) { StringBuilder response = null; StringBuilder urlBuilder = null; BufferedReader in = null; HttpsURLConnection con = null; ArrayList<String> responseList = new ArrayList<String>(); int responseCode = -1; try { response = new StringBuilder(); urlBuilder = new StringBuilder(); urlBuilder.append(url); urlBuilder.append("?").append(reqParam); urlBuilder.append("&access_token=").append(accessToken); URL urlObj = new URL(urlBuilder.toString()); con = (HttpsURLConnection) urlObj.openConnection(); con.setRequestMethod("GET"); con.setDoInput(true); con.setDoOutput(false); con.setRequestProperty("Authorization: Bearer", accessToken); in = new BufferedReader(new InputStreamReader(con.getInputStream())); responseCode = con.getResponseCode(); String inputLine = ""; while ((inputLine = in.readLine()) != null) { response.append(inputLine); } } catch (Exception e) { in = new BufferedReader(new InputStreamReader(con.getErrorStream())); String inputLine = ""; try { while ((inputLine = in.readLine()) != null) { response.append(inputLine); } } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } if (responseCode == -1) { } else { System.out.println(response.toString()); } } finally { try { in.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } responseList.add(response.toString()); responseList.add(String.valueOf(responseCode)); return responseList; }
From source file:com.apps.android.viish.encyclolpedia.tools.ImageManager.java
private static void downloadAndSaveImageWithPrefix(Context context, String prefix, String fileName) throws IOException { String stringUrl = BASE_URL + prefix + fileName; URL url = new URL(stringUrl); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); InputStream is = urlConnection.getInputStream(); BufferedInputStream bis = new BufferedInputStream(is); FileOutputStream fos = getFileOutputStream(context, fileName); ByteArrayBuffer baf = new ByteArrayBuffer(65535); int current = 0; while ((current = bis.read()) != -1) { baf.append((byte) current); }// www . java 2 s . c o m fos.write(baf.toByteArray()); fos.close(); bis.close(); }
From source file:com.jlgranda.fede.ejb.url.reader.FacturaElectronicaURLReader.java
/** * Leer contenido texto UTF-8 desde el URL dado * * @param _url el URL a leer//w w w .j a v a 2s. c o m * @return el contenido del URL como String * @throws Exception */ public static String read(String _url) throws Exception { StringBuilder b = new StringBuilder(); try { //logger.info("HTTP request: " + _url); final URL url = new URL(_url); final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.65 Safari/537.31"); b.append(slurp(connection.getInputStream(), 1024)); connection.disconnect(); } catch (IOException e) { e.printStackTrace(); } return b.toString(); }