public static String visitWeb(String urlStr) { URL url = null; HttpURLConnection httpConn = null; InputStream in = null; try { url = new URL(urlStr); httpConn = (HttpURLConnection) url.openConnection(); HttpURLConnection.setFollowRedirects(true); httpConn.setRequestMethod("GET"); httpConn.setRequestProperty("User-Agent", "Mozilla/4.0(compatible;MSIE 6.0;Windows 2000)"); in = httpConn.getInputStream(); return convertStreamToString(in); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { in.close(); httpConn.disconnect(); } catch (Exception ex) { ex.printStackTrace(); } } return null; }
static { dict = null; String wnhome = System.getenv("WNHOME"); String path = (new StringBuilder(String.valueOf(wnhome))) .append(File.separator) .append("dict") .toString(); System.out.println( (new StringBuilder("Path to dictionary:")).append(getWNLocation()).toString()); URL url = null; try { File f = new File( (new StringBuilder(String.valueOf(getWNLocation()))) .append(File.separator) .append("dict") .toString()); URI uri = f.toURI(); url = uri.toURL(); } catch (MalformedURLException e) { e.printStackTrace(); } dict = new Dictionary(url); dict.open(); }
public static void main(String args[]) throws IOException { try { // Create a URL object String temp = "http://ccnabaaps.hostingsiteforfree.com/folder/phppart.php?q=http://www.espncricinfo.com/india/content/player/253802.html"; URL url = new URL(temp); // Read all of the text returned by the HTTP server BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String htmlText; while ((htmlText = in.readLine()) != null) { // Keep in mind that readLine() strips the newline characters System.out.println(htmlText); } in.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
public static void main(String[] args) throws Exception { if (args.length > 0) { URL context = null; String input, result; if (args.length > 1) { context = new URL(args[0]); input = args[1]; } else { input = args[0]; } try { result = new URL(context, input).toString(); } catch (MalformedURLException e) { result = e.toString(); } System.out.println(" CONTEXT: " + context); System.out.println(" INPUT: " + input); System.out.println(" RESULT: " + result); System.exit(0); } boolean failed = false; for (int i = 0; i < cases.length; i++) { TestCase t = cases[i]; URL context = null; String result; // Create context URL try { context = (t.context == null) ? null : new URL(t.context); } catch (MalformedURLException e) { System.out.println("Oops: " + t.context + ": " + e); System.exit(1); } // Create new URL in context try { result = new URL(context, t.input).toString(); } catch (MalformedURLException e) { result = e.toString(); } // Check result if (!result.equals(t.result)) { System.out.println("Test failure (case " + i + ")"); System.out.println(" CONTEXT: " + t.context); System.out.println(" INPUT: " + t.input); System.out.println(" WANTED: " + t.result); System.out.println(" BUT GOT: " + result); failed = true; } } if (!failed) { System.out.println("Success."); } }
// test public static void main(String[] args) { String vers = "3.0"; String wnhome = "C:/Program Files/WordNet/" + vers + "/dict"; String icfile = "C:/Program Files/WordNet/" + vers + "/WordNet-InfoContent-" + vers + "/ic-semcor.dat"; URL url = null; try { url = new URL("file", null, wnhome); } catch (MalformedURLException e) { e.printStackTrace(); } if (url == null) { return; } IDictionary dict = new Dictionary(url); try { dict.open(); } catch (Exception ex) { ex.printStackTrace(); } ICFinder icfinder = new ICFinder(icfile); DepthFinder depthfinder = new DepthFinder(dict, icfile); double depth1 = depthfinder.getSynsetDepth("opposition", 2, "n"); System.out.println(depth1); }
private String getAddressXY(String x, String y) { try { StringBuilder text = new StringBuilder(); String url = properties.getProperty("geocoderUrl"); String param1 = properties.getProperty("geocoderUrlParam1"); String param2 = properties.getProperty("geocoderUrlParam2"); url = url + "?" + param1 + "=" + x + "&" + param2 + "=" + y; URL page = new URL(url); HttpURLConnection urlConn = (HttpURLConnection) page.openConnection(); urlConn.connect(); InputStreamReader in = new InputStreamReader((InputStream) urlConn.getContent()); BufferedReader buff = new BufferedReader(in); String line = buff.readLine(); while (line != null) { text.append(line); line = buff.readLine(); } String result = text.toString(); buff.close(); in.close(); return result; } catch (MalformedURLException e) { windowServer.txtErrors.append(e.getMessage() + "\n"); return ""; } catch (Exception e) { windowServer.txtErrors.append(e.getMessage() + "\n"); return ""; } }
/** Save the current spectrum to the server */ public void upload() { // save CSV and JSON: String spectraFolder = "spectra/"; SpectrumPresentation presenter = new SpectrumPresentation(spectrum.buffer); PrintWriter csv = createWriter(spectraFolder + presenter.generateFileName(typedText, "csv")); csv.print(presenter.toCsv()); csv.close(); PrintWriter json = createWriter(spectraFolder + presenter.generateFileName(typedText, "json")); json.print(presenter.toJson(presenter.generateFileName(typedText, null))); json.close(); // save PNG: save( spectraFolder + presenter.generateFileName( typedText, "png")); // this just saves the main pixel buffer // save just a subregion as PNG: PGraphics pg; // store 100 lines of history? pg = createGraphics(video.width, 100, P2D); pg.beginDraw(); for (int y = 0; y < 100; y++) { for (int x = 0; x < video.width; x++) { pg.set(x, y, pixels[headerHeight * width + y * width + x]); } } pg.endDraw(); pg.save(spectraFolder + presenter.generateFileName(typedText + "-alt", "png")); // save to web: String webTitle = presenter.generateFileName("untitled", null); try { String response; println( serverUrl + "/spectrums/create?spectrum[title]=" + webTitle + "&spectrum[author]=anonymous"); URL u = new URL( serverUrl + "/spectrums/create?spectrum[title]=" + webTitle + "&spectrum[author]=anonymous&client=0.5"); // this.postData(u,presenter.toJson(presenter.generateFileName(typedText, null)).getBytes()); response = postData(u, bufferImage(pg.get()), presenter.generateFileName(typedText, "png")); // clear label buffer typedText = "saved: type to label next spectrum"; println(serverUrl + "/spectra/edit/" + response); link(serverUrl + "/spectra/edit/" + response); } catch (MalformedURLException e) { println("ERROR " + e.getMessage()); } catch (IOException e) { println("ERROR " + e.getMessage()); } }
public HttpReport(QAT parent, String urlString, String baseDir, StatusWindow status) { // check if the basedir exists if (!(new File(baseDir).exists())) { String message = "Error - cannot generate report, directory does not exist:" + baseDir; if (status == null) { System.out.println(message); } else { status.setMessage(message); } return; } this.parent = parent; this.status = status; processedLinks = new ArrayList(); try { processURL(new URL(urlString), baseDir, status); writeDeadLinks(baseDir); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { processedLinks.clear(); } }
/** * Create a MonitoredHostProvider instance using the given HostIdentifier. * * @param hostId the host identifier for this MonitoredHost * @throws MonitorException Thrown on any error encountered while communicating with the remote * host. */ public MonitoredHostProvider(HostIdentifier hostId) throws MonitorException { this.hostId = hostId; this.listeners = new ArrayList(); this.interval = DEFAULT_POLLING_INTERVAL; this.activeVms = new HashSet(); String rmiName; String sn = serverName; String path = hostId.getPath(); if ((path != null) && (path.length() > 0)) { sn = path; } if (hostId.getPort() != -1) { rmiName = "rmi://" + hostId.getHost() + ":" + hostId.getPort() + sn; } else { rmiName = "rmi://" + hostId.getHost() + sn; } try { remoteHost = (RemoteHost) Naming.lookup(rmiName); } catch (RemoteException e) { /* * rmi registry not available * * Access control exceptions, where the rmi server refuses a * connection based on policy file configuration, come through * here on the client side. Unfortunately, the RemoteException * doesn't contain enough information to determine the true cause * of the exception. So, we have to output a rather generic message. */ String message = "RMI Registry not available at " + hostId.getHost(); if (hostId.getPort() == -1) { message = message + ":" + java.rmi.registry.Registry.REGISTRY_PORT; } else { message = message + ":" + hostId.getPort(); } if (e.getMessage() != null) { throw new MonitorException(message + "\n" + e.getMessage(), e); } else { throw new MonitorException(message, e); } } catch (NotBoundException e) { // no server with given name String message = e.getMessage(); if (message == null) message = rmiName; throw new MonitorException("RMI Server " + message + " not available", e); } catch (MalformedURLException e) { // this is a programming problem e.printStackTrace(); throw new IllegalArgumentException("Malformed URL: " + rmiName); } this.vmManager = new RemoteVmManager(remoteHost); this.timer = new Timer(true); }
// прочитать весь json в строку private static String readAll() throws IOException { StringBuilder data = new StringBuilder(); try { HttpURLConnection con = (HttpURLConnection) ((new URL(PRODUCT_URL).openConnection())); con.setRequestMethod("GET"); con.setDoInput(true); String s; try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) { while ((s = in.readLine()) != null) { data.append(s); } } } catch (MalformedURLException e) { e.printStackTrace(); throw new MalformedURLException("Url is not valid"); } catch (ProtocolException e) { e.printStackTrace(); throw new ProtocolException("No such protocol, it must be POST,GET,PATCH,DELETE etc."); } catch (IOException e) { e.printStackTrace(); throw new IOException("cannot read from server"); } return data.toString(); }
public URL getURL() { try { return new URL(elt.getAttribute("url")); } catch (MalformedURLException e) { e.printStackTrace(); } return null; }
/** * 请求xml数据 * * @param url * @param soapAction * @param xml * @return */ public static String sendXMl(String url, String soapAction, String xml) { HttpURLConnection conn = null; InputStream in = null; InputStreamReader isr = null; OutputStream out = null; StringBuffer result = null; try { byte[] sendbyte = xml.getBytes("UTF-8"); URL u = new URL(url); conn = (HttpURLConnection) u.openConnection(); conn.setRequestProperty("Content-Type", "text/xml; charset=utf-8"); conn.setRequestProperty("SOAPAction", soapAction); conn.setRequestProperty("Content-Length", sendbyte.length + ""); conn.setDoInput(true); conn.setDoOutput(true); conn.setConnectTimeout(5000); conn.setReadTimeout(5000); out = conn.getOutputStream(); out.write(sendbyte); if (conn.getResponseCode() == 200) { result = new StringBuffer(); in = conn.getInputStream(); isr = new InputStreamReader(in, "UTF-8"); char[] c = new char[1024]; int a = isr.read(c); while (a != -1) { result.append(new String(c, 0, a)); a = isr.read(c); } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (conn != null) { conn.disconnect(); } try { if (in != null) { in.close(); } if (isr != null) { isr.close(); } if (out != null) { out.close(); } } catch (IOException e) { e.printStackTrace(); } } return result == null ? null : result + ""; }
public static String httsRequest(String url, String contentdata) { String str_return = ""; SSLContext sc = null; try { sc = SSLContext.getInstance("SSL"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } try { sc.init( null, new TrustManager[] {new TrustAnyTrustManager()}, new java.security.SecureRandom()); } catch (KeyManagementException e) { e.printStackTrace(); } URL console = null; try { console = new URL(url); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } HttpsURLConnection conn; try { conn = (HttpsURLConnection) console.openConnection(); conn.setRequestMethod("POST"); conn.setSSLSocketFactory(sc.getSocketFactory()); conn.setHostnameVerifier(new TrustAnyHostnameVerifier()); conn.setRequestProperty("Accept", "application/json"); conn.setDoInput(true); conn.setDoOutput(true); // contentdata="username=arcgis&password=arcgis123&client=requestip&f=json" String inpputs = contentdata; OutputStream os = conn.getOutputStream(); os.write(inpputs.getBytes()); os.close(); conn.connect(); InputStream is = conn.getInputStream(); // // DataInputStream indata = new DataInputStream(is); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String ret = ""; while (ret != null) { ret = reader.readLine(); if (ret != null && !ret.trim().equals("")) { str_return = str_return + ret; } } is.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return str_return; }
public URL getImageURL() { if (imageURL != null) { try { return new URL(imageURL); } catch (MalformedURLException e) { e.printStackTrace(); } } return null; }
/** * @param url The URL of the Virtual Center Server * <p>https://<Server IP / host name>/sdk * <p>The method establishes connection with the web service port on the server. This is not * to be confused with the session connection. */ private static void initVimPort(String url) { VimServiceLocator locator = new VimServiceLocator(); locator.setMaintainSession(true); try { VIM_PORT = locator.getVimPort(new URL(url)); } catch (MalformedURLException mue) { mue.printStackTrace(); } catch (Exception se) { se.printStackTrace(); } }
private void buildUrlSets(String url) { try { outputMessage("\nFetching " + url, TEST_SUMMARY_MESSAGE); URL srcUrl = new URL(url); // URLConnection conn = srcUrl.openConnection(); // String type = conn.getContentType(); // type = conn.getHeaderField("content-type"); // InputStream istr = conn.getInputStream(); LockssUrlConnection conn = UrlUtil.openConnection(url, connectionPool); if (proxyHost != null) { conn.setProxy(proxyHost, proxyPort); } if (userAgent != null) { conn.setRequestProperty("user-agent", userAgent); } try { conn.execute(); int resp = conn.getResponseCode(); if (resp != 200) { outputMessage("Resp: " + resp + ": " + conn.getResponseMessage(), TEST_SUMMARY_MESSAGE); return; } depth_fetched[m_curDepth - 1]++; String cookies = conn.getResponseHeaderValue("Set-Cookie"); if (cookies != null) { outputMessage("Cookies: " + cookies, PLAIN_MESSAGE); } String type = conn.getResponseContentType(); if (type == null || !type.toLowerCase().startsWith("text/html")) { outputMessage("Type: " + type + ", not parsing", URL_SUMMARY_MESSAGE); return; } outputMessage("Type: " + type + ", extracting Urls", URL_SUMMARY_MESSAGE); InputStream istr = conn.getResponseInputStream(); InputStreamReader reader = new InputStreamReader(istr); // MyMockCachedUrl mcu = new MyMockCachedUrl(srcUrl.toString(), reader); GoslingHtmlLinkExtractor extractor = new GoslingHtmlLinkExtractor(); extractor.extractUrls(null, istr, null, srcUrl.toString(), new MyLinkExtractorCallback()); istr.close(); depth_parsed[m_curDepth - 1]++; } finally { conn.release(); } } catch (MalformedURLException murle) { murle.printStackTrace(); outputErrResults(url, "Malformed URL:" + murle.getMessage()); } catch (IOException ex) { ex.printStackTrace(); outputErrResults(url, "IOException: " + ex.getMessage()); } }
public ErrorInfo listPolicy(String polname, String token) throws IOException, RestException { String realm = "/"; String data = null; ErrorInfo ei = null; InputStreamReader iss = null; BufferedReader br = null; HttpURLConnection urlc = null; InputStream inputStream = null; try { data = "policynames=" + URLEncoder.encode(polname, "UTF-8") + "&realm=" + URLEncoder.encode(realm, "UTF-8") + "&submit=" + URLEncoder.encode("Submit", "UTF-8"); } catch (UnsupportedEncodingException e) { System.out.println("OpenssoHelper: " + e.getMessage()); e.printStackTrace(); } if (data != null) { try { r.Connect(new URL(url + ssoadm_list)); } catch (MalformedURLException e) { System.out.println("OpenssoHelper: " + e.getMessage()); e.printStackTrace(); } urlc = (HttpURLConnection) r.c; urlc.addRequestProperty("Cookie", "iPlanetDirectoryPro=\"" + token + "\""); r.Send(urlc, data); String answer = null; int status = 0; inputStream = urlc.getInputStream(); iss = new InputStreamReader(inputStream); br = new BufferedReader(iss); answer = BrToString(br); status = urlc.getResponseCode(); if (answer != null) { ei = new ErrorInfo(answer, status); } br.close(); iss.close(); inputStream.close(); urlc.disconnect(); } return ei; }
private void downloadImage() { String myURL = equip.getImage_url(); try { URL url = new URL(myURL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); bitmap = BitmapFactory.decodeStream(conn.getInputStream()); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
/** Loop a sound file (in .wav, .mid, or .au format) in a background thread. */ public static void loop(String filename) { URL url = null; try { File file = new File(filename); if (file.canRead()) url = file.toURI().toURL(); } catch (MalformedURLException e) { e.printStackTrace(); } // URL url = StdAudio.class.getResource(filename); if (url == null) throw new RuntimeException("audio " + filename + " not found"); AudioClip clip = Applet.newAudioClip(url); clip.loop(); }
public static WMSCapabilities retrieve(URI uri) throws Exception { try { CapabilitiesRequest request = new CapabilitiesRequest(uri); return new WMSCapabilities(request); } catch (URISyntaxException e) { e.printStackTrace(); } catch (MalformedURLException e) { e.printStackTrace(); } return null; }
public String symantic_query(String query) { String st = query.split("\\[")[1].split("\\]")[0]; String res = ""; try { res = helpers.getExpand( "http://www.kbresearch.nl/tripple.cgi?query=" + helpers.urlEncode(st), log); } catch (MalformedURLException e) { res = (e.getMessage()); } return (res); }
@Nullable static ClassLoader createPluginClassLoader( @NotNull File[] classPath, @NotNull ClassLoader[] parentLoaders, @NotNull IdeaPluginDescriptor pluginDescriptor) { if (pluginDescriptor.getUseIdeaClassLoader()) { try { final ClassLoader loader = PluginManagerCore.class.getClassLoader(); final Method addUrlMethod = getAddUrlMethod(loader); for (File aClassPath : classPath) { final File file = aClassPath.getCanonicalFile(); addUrlMethod.invoke(loader, file.toURI().toURL()); } return loader; } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } PluginId pluginId = pluginDescriptor.getPluginId(); File pluginRoot = pluginDescriptor.getPath(); // if (classPath.length == 0) return null; if (isUnitTestMode()) return null; try { final List<URL> urls = new ArrayList<URL>(classPath.length); for (File aClassPath : classPath) { final File file = aClassPath .getCanonicalFile(); // it is critical not to have "." and ".." in classpath // elements urls.add(file.toURI().toURL()); } return new PluginClassLoader( urls, parentLoaders, pluginId, pluginDescriptor.getVersion(), pluginRoot); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }
public SOAPMessage get(Object endPoint) throws SOAPException { if (closed) { log.severe("SAAJ0011.p2p.get.already.closed.conn"); throw new SOAPExceptionImpl("Connection is closed"); } Class urlEndpointClass = null; try { urlEndpointClass = Class.forName("javax.xml.messaging.URLEndpoint"); } catch (Exception ex) { // Do nothing. URLEndpoint is available only when JAXM is there. } if (urlEndpointClass != null) { if (urlEndpointClass.isInstance(endPoint)) { String url = null; try { Method m = urlEndpointClass.getMethod("getURL", (Class[]) null); url = (String) m.invoke(endPoint, (Object[]) null); } catch (Exception ex) { log.severe("SAAJ0004.p2p.internal.err"); throw new SOAPExceptionImpl("Internal error: " + ex.getMessage()); } try { endPoint = new URL(url); } catch (MalformedURLException mex) { log.severe("SAAJ0005.p2p."); throw new SOAPExceptionImpl("Bad URL: " + mex.getMessage()); } } } if (endPoint instanceof java.lang.String) { try { endPoint = new URL((String) endPoint); } catch (MalformedURLException mex) { log.severe("SAAJ0006.p2p.bad.URL"); throw new SOAPExceptionImpl("Bad URL: " + mex.getMessage()); } } if (endPoint instanceof URL) try { SOAPMessage response = doGet((URL) endPoint); return response; } catch (Exception ex) { throw new SOAPExceptionImpl(ex); } else throw new SOAPExceptionImpl("Bad endPoint type " + endPoint); }
/** * Запрос с указанием параметров. * * @see MoneyDownloader#login * @see MoneyDownloader#password * @see MoneyDownloader#dateStart * @see MoneyDownloader#dateEnd */ public final void run() { File file = new File(directory + "/Results.tsv"); // File test = new File(directory + "/tmp/result.tsv"); try { if (!file.exists()) { file.createNewFile(); } } catch (IOException e) { e.printStackTrace(); } String request = "https://rt.miran.ru?user="******"&pass="******"http://rt.miran.ru/rt/Search/Results.tsv?user="******"&pass="******"&Format=%27__Created__%2FTITLE%3A%D0%94%D0%B0%D1%82%D0%B0%27%2C%0A%27%20%20%20%3Cb%3E%3Ca%20href%3D%22%2Frt%2FTicket%2FDisplay.html%3Fid%3D__id__%22%3E__id__%3C%2Fa%3E%3C%2Fb%3E%2FTITLE%3A%23%27%2C%0A%27__Subject__%2FTITLE%3A%D0%A2%D0%B5%D0%BC%D0%B0%27%2C%0A%27__QueueName__%2FTITLE%3A%D0%9E%D1%87%D0%B5%D1%80%D0%B5%D0%B4%D1%8C%27%2C%0A%27__CustomField.%7Binteraction%20type%7D__%2FTITLE%3A%D0%A2%D0%B8%D0%BF%27%2C%0A%27__CustomField.%7Bbussines%7D__%2FTITLE%3A%D0%91%D0%B8%D0%B7%D0%BD%D0%B5%D1%81%27%2C%0A%27__CustomField.%7Bdirection%7D__%2FTITLE%3A%D0%9D%D0%B0%D0%BF%D1%80%D0%B0%D0%B2%D0%BB%D0%B5%D0%BD%D0%B8%D0%B5%27%2C%0A%27__CustomField.%7Bservice%7D__%2FTITLE%3A%D0%A3%D1%81%D0%BB%D1%83%D0%B3%D0%B0%27%2C%0A%27__CustomField.%7BSD%20Type%7D__%2FTITLE%3A%D0%9A%D0%B0%D1%82%D0%B5%D0%B3%D0%BE%D1%80%D0%B8%D1%8F%27%2C%0A%27__CustomField.%7BSD%20Detail%7D__%2FTITLE%3A%D0%91%D0%BE%D0%BD%D1%83%D1%81%27%2C%0A%27__CustomField.%7BQA%7D__%2FTITLE%3A%D0%92%D1%8B%D0%BF%D0%BE%D0%BB%D0%BD%D0%B8%D0%BB%27&Order=DESC%7CASC%7CASC%7CASC&OrderBy=Created%7C%7C%7C&Page=1&Query=Created%20%3E%20%27" + dateStart + "%27%20AND%20Created%20%3C%20%27" + dateEnd + "%27%20AND%20Status%20%3D%20%27closed%27%20AND%20Queue%20!%3D%20%27manager%27%20AND%20Queue%20!%3D%20%27sales%27%20AND%20%27CF.%7BQA%7D%27%20%3D%20%27__CurrentUser__%27&RowsPerPage=0&SavedChartSearchId=new&SavedSearchId="; System.out.println(tickets); ListCookieHandler cookieHandler = new ListCookieHandler(); CookieHandler.setDefault(cookieHandler); try { URL url = new URL(request); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.getResponseCode(); GetMethod method = new GetMethod(tickets); method.addRequestHeader("Cookie", cookieHandler.getCookiez()); method.addRequestHeader("Referer", "http://rt.miran.ru/"); HttpClient httpClient = new HttpClient(); httpClient.executeMethod(method); InputStream in = method.getResponseBodyAsStream(); System.out.println(in.available()); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
public void init() { context = this.getAppletContext(); String audioURL = this.getParameter("audio"); if (audioURL == null) { audioURL = "http://localhost:8080/TGMC-version1/abc.wav?Text=who"; } try { URL url = new URL(this.getDocumentBase(), audioURL); clip = context.getAudioClip(url); } catch (MalformedURLException e) { e.printStackTrace(); context.showStatus("Could not load audio file!"); } }
public ErrorInfo doLogin() throws IOException, RestException { String data = null; ErrorInfo ei = null; InputStreamReader iss = null; BufferedReader br = null; HttpURLConnection urlc = null; InputStream inputStream = null; try { data = "username="******"UTF-8") + "&password="******"UTF-8"); } catch (UnsupportedEncodingException e) { System.out.println("OpenssoHelper: " + e.getMessage()); e.printStackTrace(); } if (data != null) { try { r.Connect(new URL(url + authenticate)); } catch (MalformedURLException e) { System.out.println("OpenssoHelper: " + e.getMessage()); e.printStackTrace(); } urlc = (HttpURLConnection) r.c; r.Send(urlc, data); String answer = null; int status = 0; inputStream = urlc.getInputStream(); iss = new InputStreamReader(inputStream); br = new BufferedReader(iss); answer = BrToString(br); status = urlc.getResponseCode(); if (answer != null) { ei = new ErrorInfo(answer, status); } br.close(); iss.close(); inputStream.close(); urlc.disconnect(); } return ei; }
private InputStream openStream(String urlpath) { InputStream stream = null; try { URL url = new URL(urlpath); stream = url.openStream(); return stream; } catch (MalformedURLException e) { System.out.println("Something's wrong with the URL: " + urlpath); e.printStackTrace(); } catch (IOException e) { System.out.println("there's a problem downloading from: " + urlpath); e.printStackTrace(); } return stream; }
/** * Gets the url associated with this resource. * * @return the URL */ public URL getURL() { if (url == null && file != null) { String path = getAbsolutePath(); try { if (path.startsWith("/")) { // $NON-NLS-1$ url = new URL("file:" + path); // $NON-NLS-1$ } else { url = new URL("file:/" + path); // $NON-NLS-1$ } } catch (MalformedURLException ex) { ex.printStackTrace(); } } return url; }
/** * opens existing file * * @param a_file */ public GlyphFile(File a_file) { super(); m_fileName = a_file; URL url = null; try { url = a_file.toURI().toURL(); } catch (MalformedURLException e) { e.printStackTrace(); } init(url); }
// добавить продукт в базу json server public static void add(ProductREST product) throws NotValidProductException, IOException { try { check(product); // рповеряем продукт // connection к серверу HttpURLConnection con = (HttpURLConnection) ((new URL(PRODUCT_URL).openConnection())); con.setRequestMethod("POST"); // метод post для добавления // генерируем запрос StringBuilder urlParameters = new StringBuilder(); urlParameters .append("name=") .append(URLEncoder.encode(product.getName(), "UTF8")) .append("&"); urlParameters.append("price=").append(product.getPrice()).append("&"); urlParameters.append("weight=").append(product.getWeight()).append("&"); urlParameters .append("manufacturer=") .append(product.getManufacturer().getCountry()) .append("&"); urlParameters.append("category=").append(URLEncoder.encode(product.getCategory(), "UTF8")); con.setDoOutput(true); // разрешаем отправку данных // отправляем try (DataOutputStream out = new DataOutputStream(con.getOutputStream())) { out.writeBytes(urlParameters.toString()); } // код ответа int responseCode = con.getResponseCode(); System.out.println("\nSending 'POST' request to URL : " + PRODUCT_URL); System.out.println("Response Code : " + responseCode); } catch (NotValidProductException e) { e.printStackTrace(); throw e; } catch (UnsupportedEncodingException e) { e.printStackTrace(); throw new UnsupportedEncodingException("cannot recognize encoding"); } catch (ProtocolException e) { e.printStackTrace(); throw new ProtocolException("No such protocol, protocol must be POST,DELETE,PATCH,GET etc."); } catch (MalformedURLException e) { e.printStackTrace(); throw new MalformedURLException("Url is not valid"); } catch (IOException e) { e.printStackTrace(); throw new IOException("cannot write information to server"); } }