List of usage examples for java.net URLConnection setDoInput
public void setDoInput(boolean doinput)
From source file:net.sourceforge.atunes.kernel.modules.network.NetworkHandler.java
/** * Sends a POST request with given parameters and receives response with * given charset//from w w w.ja v a 2 s. co m * * @param requestURL * @param params * @param charset * @return * @throws IOException */ @Override public String readURL(final String requestURL, final Map<String, String> params, final String charset) throws IOException { URLConnection connection = getConnection(requestURL); connection.setUseCaches(false); connection.setDoInput(true); if (params != null && params.size() > 0) { connection.setDoOutput(true); OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.write(formatPOSTParameters(params)); writer.flush(); } InputStream input = null; try { input = connection.getInputStream(); return IOUtils.toString(input, charset); } finally { ClosingUtils.close(input); } }
From source file:org.LexGrid.LexBIG.caCore.test.rest.RESTTest.java
private String callRestfulService(String putString) throws Exception { URL url = new URL(serviceEndPoint + putString); URLConnection urlc = url.openConnection(); urlc.setDoInput(true); urlc.setDoOutput(true);//w w w . j a v a 2 s. c o m PrintStream ps = new PrintStream(urlc.getOutputStream()); ps.close(); //retrieve result BufferedReader br = new BufferedReader(new InputStreamReader(urlc.getInputStream())); String str; StringBuffer sb = new StringBuffer(); while ((str = br.readLine()) != null) { sb.append(str); sb.append("\n"); } br.close(); return sb.toString(); }
From source file:org.jab.docsearch.utils.NetUtils.java
/** * Downloads URL to file/*from w ww. jav a 2s . co m*/ * * Content type, content length, last modified and md5 will be set in SpiderUrl * * @param spiderUrl URL to download * @param file URL content downloads to this file * @return true if URL successfully downloads to a file */ public boolean downloadURLToFile(final SpiderUrl spiderUrl, final String file) { boolean downloadOk = false; BufferedInputStream inputStream = null; BufferedOutputStream outputStream = null; try { // if the file downloads - save it and return true URL url = new URL(spiderUrl.getUrl()); URLConnection conn = url.openConnection(); // set connection parameter conn.setDoInput(true); conn.setDoOutput(false); conn.setUseCaches(false); conn.setRequestProperty("User-Agent", USER_AGENT); // connect conn.connect(); // content type spiderUrl.setContentType(getContentType(conn)); // open streams inputStream = new BufferedInputStream(conn.getInputStream()); outputStream = new BufferedOutputStream(new FileOutputStream(file)); // copy data from URL to file long size = 0; int readed = 0; while ((readed = inputStream.read()) != -1) { size++; outputStream.write(readed); } // set values spiderUrl.setContentType(getContentType(conn)); spiderUrl.setSize(size); downloadOk = true; } catch (IOException ioe) { logger.fatal("downloadURLToFile() failed for URL='" + spiderUrl.getUrl() + "'", ioe); downloadOk = false; } finally { IOUtils.closeQuietly(outputStream); IOUtils.closeQuietly(inputStream); } // set values if (downloadOk) { spiderUrl.setMd5(FileUtils.getMD5Sum(file)); } return downloadOk; }
From source file:org.apache.jcs.auxiliary.lateral.http.broadcast.LateralCacheThread.java
/** Description of the Method */ public void writeObj(URLConnection connection, ICacheElement cb) { try {/*from ww w . j av a 2 s. c om*/ connection.setUseCaches(false); connection.setRequestProperty("CONTENT_TYPE", "application/octet-stream"); connection.setDoOutput(true); connection.setDoInput(true); ObjectOutputStream os = new ObjectOutputStream(connection.getOutputStream()); log.debug("os = " + os); // Write the ICacheItem to the ObjectOutputStream log.debug("Writing ICacheItem."); os.writeObject(cb); os.flush(); log.debug("closing output stream"); os.close(); } catch (IOException e) { log.error(e); } // end catch }
From source file:org.phaidra.apihooks.APIRESTHooksImpl.java
/** * Runs the hook if enabled in fedora.fcfg. * * @param method The name of the method that calls the hook * @param pid The PID that is being accessed * @param params Method parameters, depend on the method called * @return String Hook verdict. Begins with "OK" if it's ok to proceed. * @throws APIHooksException If the remote call went wrong *//*from www. j a v a2 s.c o m*/ public String runHook(String method, DOWriter w, Context context, String pid, Object[] params) throws APIHooksException { String rval = null; // Only do this if the method is enabled in fedora.fcfg if (getParameter(method) == null) { log.debug("runHook: method |" + method + "| not configured, not calling webservice"); return "OK"; } Iterator i = context.subjectAttributes(); String attrs = ""; while (i.hasNext()) { String name = ""; try { name = (String) i.next(); String[] value = context.getSubjectValues(name); for (int j = 0; j < value.length; j++) { attrs += "&attr=" + URLEncoder.encode(name + "=" + value[j], "UTF-8"); log.debug("runHook: will send |" + name + "=" + value[j] + "| as subject attribute"); } } catch (NullPointerException ex) { log.debug( "runHook: caught NullPointerException while trying to retrieve subject attribute " + name); } catch (UnsupportedEncodingException ex) { log.debug("runHook: caught UnsupportedEncodingException while trying to encode subject attribute " + name); } } String paramstr = ""; try { for (int j = 0; j < params.length; j++) { paramstr += "¶m" + Integer.toString(j) + "="; if (params[j] != null) { String p = params[j].toString(); paramstr += URLEncoder.encode(p, "UTF-8"); } } } catch (UnsupportedEncodingException ex) { log.debug("runHook: caught UnsupportedEncodingException while trying to encode a parameter"); } String loginId = context.getSubjectValue(Constants.SUBJECT.LOGIN_ID.uri); log.debug("runHook: called for method=|" + method + "|, pid=|" + pid + "|"); try { // TODO: timeout? retries? URL url; URLConnection urlConn; DataOutputStream printout; BufferedReader input; url = new URL(getParameter("restmethod")); urlConn = url.openConnection(); urlConn.setDoInput(true); urlConn.setDoOutput(true); urlConn.setUseCaches(false); urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); printout = new DataOutputStream(urlConn.getOutputStream()); String content = "method=" + URLEncoder.encode(method, "UTF-8") + "&username=" + URLEncoder.encode(loginId, "UTF-8") + "&pid=" + URLEncoder.encode(pid, "UTF-8") + paramstr + attrs; printout.writeBytes(content); printout.flush(); printout.close(); // Get response data. input = new BufferedReader(new InputStreamReader(urlConn.getInputStream(), "UTF-8")); String str; rval = ""; while (null != ((str = input.readLine()))) { rval += str + "\n"; } input.close(); String ct = urlConn.getContentType(); if (ct.startsWith("text/xml")) { log.debug("runHook: successful REST invocation for method |" + method + "|, returning: " + rval); } else if (ct.startsWith("text/plain")) { log.debug("runHook: successful REST invocation for method |" + method + "|, but hook returned an error: " + rval); throw new Exception(rval); } else { throw new Exception("Invalid content type " + ct); } } catch (Exception ex) { log.error("runHook: error calling REST hook: " + ex.toString()); throw new APIHooksException("Error calling REST hook: " + ex.toString(), ex); } return processResults(rval, w, context); }
From source file:org.apache.servicemix.jbi.itests.IntegrationTest.java
@Test public void testServiceAssembly() throws Throwable { System.out.println("Waiting for NMR"); NMR nmr = getOsgiService(NMR.class); assertNotNull(nmr);/*from www .j a v a2s . com*/ Bundle smxShared = installJbiBundle("org.apache.servicemix", "servicemix-shared", "installer", "zip"); Bundle smxJsr181 = installJbiBundle("org.apache.servicemix", "servicemix-jsr181", "installer", "zip"); Bundle smxHttp = installJbiBundle("org.apache.servicemix", "servicemix-http", "installer", "zip"); Bundle saBundle = installJbiBundle("org.apache.servicemix.samples.wsdl-first", "wsdl-first-sa", null, "zip"); smxShared.start(); smxJsr181.start(); smxHttp.start(); saBundle.start(); System.out.println("Waiting for JBI Service Assembly"); ServiceAssembly sa = getOsgiService(ServiceAssembly.class); assertNotNull(sa); Thread.sleep(500); final List<Throwable> errors = new CopyOnWriteArrayList<Throwable>(); final int nbThreads = 2; final int nbMessagesPerThread = 10; final CountDownLatch latch = new CountDownLatch(nbThreads * nbMessagesPerThread); for (int i = 0; i < nbThreads; i++) { new Thread() { public void run() { for (int i = 0; i < nbMessagesPerThread; i++) { try { URL url = new URL("http://localhost:8192/PersonService/"); URLConnection connection = url.openConnection(); connection.setDoInput(true); connection.setDoOutput(true); connection.getOutputStream().write( ("<env:Envelope xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\"\n" + " xmlns:tns=\"http://servicemix.apache.org/samples/wsdl-first/types\">\n" + " <env:Body>\n" + " <tns:GetPerson>\n" + " <tns:personId>world</tns:personId>\n" + " </tns:GetPerson>\n" + " </env:Body>\n" + "</env:Envelope>") .getBytes()); byte[] buffer = new byte[8192]; int len = connection.getInputStream().read(buffer); if (len == -1) { throw new Exception("No response available"); } String result = new String(buffer, 0, len); System.out.println(result); } catch (Throwable t) { errors.add(t); t.printStackTrace(); } finally { latch.countDown(); } } } }.start(); } if (!latch.await(60, TimeUnit.SECONDS)) { fail("Test timed out"); } if (!errors.isEmpty()) { throw errors.get(0); } //Thread.sleep(500); saBundle.uninstall(); //sa.stop(); //sa.shutDown(); }
From source file:BihuHttpUtil.java
/** * ? URL ??POST/*from w ww.ja va 2s. c o m*/ * * @param url * ?? URL * @param param * ?? name1=value1&name2=value2 ? * @param sessionId * ??? * @return ?? */ public static Map<String, String> sendPost(String url, String param, String sessionId) { Map<String, String> resultMap = new HashMap<String, String>(); PrintWriter out = null; BufferedReader in = null; String result = ""; try { URL realUrl = new URL(url); // URL URLConnection conn = realUrl.openConnection(); // //conn.setRequestProperty("Host", "quote.zhonghe-bj.com:8085"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); conn.setRequestProperty("Accept", "*/*"); conn.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3"); conn.setRequestProperty("Accept-Encoding", "gzip, deflate"); if (StringUtils.isNotBlank(sessionId)) { conn.setRequestProperty("Cookie", sessionId); } // ??POST conn.setDoOutput(true); conn.setDoInput(true); // ?URLConnection? out = new PrintWriter(conn.getOutputStream()); // ??? out.print(param); // flush? out.flush(); // BufferedReader???URL? in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String cookieValue = conn.getHeaderField("Set-Cookie"); resultMap.put("cookieValue", cookieValue); String line; while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { System.out.println("?? POST ?" + e); e.printStackTrace(); } // finally????? finally { try { if (out != null) { out.close(); } if (in != null) { in.close(); } } catch (IOException ex) { ex.printStackTrace(); } } resultMap.put("result", result); return resultMap; }
From source file:org.apache.ode.jbi.JbiTestBase.java
protected void go() throws Exception { boolean manualDeploy = Boolean.parseBoolean("" + testProperties.getProperty("manualDeploy")); if (!manualDeploy) enableProcess(getTestName(), true); try {/*w w w .ja va 2s. c o m*/ int i = 0; boolean loop; do { String prefix = i == 0 ? "" : "" + i; loop = i == 0; { String deploy = testProperties.getProperty(prefix + "deploy"); if (deploy != null) { loop = true; enableProcess(getTestName() + "/" + deploy, true); } } { String undeploy = testProperties.getProperty(prefix + "undeploy"); if (undeploy != null) { loop = true; enableProcess(getTestName() + "/" + undeploy, false); } } String request = testProperties.getProperty(prefix + "request"); if (request != null && request.startsWith("@")) { request = inputStreamToString( getClass().getResourceAsStream("/" + getTestName() + "/" + request.substring(1))); } String expectedResponse = testProperties.getProperty(prefix + "response"); { String delay = testProperties.getProperty(prefix + "delay"); if (delay != null) { loop = true; long d = Long.parseLong(delay); log.debug("Sleeping " + d + " ms"); Thread.sleep(d); } } { String httpUrl = testProperties.getProperty(prefix + "http.url"); if (httpUrl != null && request != null) { loop = true; log.debug(getTestName() + " sending http request to " + httpUrl + " request: " + request); URLConnection connection = new URL(httpUrl).openConnection(); connection.setDoOutput(true); connection.setDoInput(true); //Send request OutputStream os = connection.getOutputStream(); PrintWriter wt = new PrintWriter(os); wt.print(request); wt.flush(); wt.close(); // Read the response. String result = inputStreamToString(connection.getInputStream()); log.debug(getTestName() + " have result: " + result); matchResponse(expectedResponse, result, true); } } { if (testProperties.getProperty(prefix + "nmr.service") != null && request != null) { loop = true; InOut io = smxClient.createInOutExchange(); io.setService(QName.valueOf(testProperties.getProperty(prefix + "nmr.service"))); io.setOperation(QName.valueOf(testProperties.getProperty(prefix + "nmr.operation"))); io.getInMessage() .setContent(new StreamSource(new ByteArrayInputStream(request.getBytes()))); smxClient.sendSync(io, 20000); if (io.getStatus() == ExchangeStatus.ACTIVE) { assertNotNull(io.getOutMessage()); String result = new SourceTransformer().contentToString(io.getOutMessage()); matchResponse(expectedResponse, result, true); smxClient.done(io); } else { matchResponse(expectedResponse, "", false); } } } i++; } while (loop); } finally { if (!manualDeploy) enableProcess(getTestName(), false); } }
From source file:org.jab.docsearch.utils.NetUtils.java
/** * Get SpiderUrl status/*from ww w . ja v a 2s . c o m*/ * * Content type, content length, last modified and md5 will be set in SpiderUrl if url is changed * * @param spiderUrl URL to check * @param file URL content downloads to to this file * @return -1 if link is broken, 0 if the file is unchanged or 1 if the file * is different... part of caching algoritm. */ public int getURLStatus(final SpiderUrl spiderUrl, final String file) { // -1 means broken link // 0 means same file // 1 means changed int status; try { // attempt to obtain status from date URL url = new URL(spiderUrl.getUrl()); URLConnection conn = url.openConnection(); // set connection parameter conn.setDoInput(true); conn.setDoOutput(false); conn.setUseCaches(false); conn.setRequestProperty("User-Agent", USER_AGENT); // connect conn.connect(); // content type spiderUrl.setContentType(getContentType(conn)); // check date long spiDate = spiderUrl.getLastModified(); long urlDate = conn.getLastModified(); // same if date is equal and not zero if (spiDate == urlDate && urlDate != 0) { // the file is not changed status = 0; } else { // download the URL and compare hashes boolean downloaded = downloadURLToFile(conn, file); if (downloaded) { // download ok // compare file hashes String fileHash = FileUtils.getMD5Sum(file); if (fileHash.equals(spiderUrl.getMd5())) { // same status = 0; } else { // changed status = 1; // set changed values spiderUrl.setSize(FileUtils.getFileSize(file)); spiderUrl.setLastModified(urlDate); spiderUrl.setMd5(fileHash); } } else { // download failed // broken link status = -1; } } } catch (IOException ioe) { logger.error("getURLStatus() failed for URL='" + spiderUrl.getUrl() + "'", ioe); status = -1; } return status; }
From source file:org.lafs.hdfs.LAFS.java
private JSONArray getJSONForPath(Path path) throws IOException { URL url = new URL(httpURI.toString() + "/uri/" + getLAFSPath(path) + "?t=json"); URLConnection uc = url.openConnection(); uc.setDoInput(true); BufferedReader br;/*from w w w .j a va 2s .c o m*/ try { br = new BufferedReader(new InputStreamReader(uc.getInputStream())); } catch (ConnectException e1) { logger.severe(url.toString()); throw new IOException(e1); } StringBuilder sb = new StringBuilder(); String line = br.readLine(); while (line != null) { sb.append(line); line = br.readLine(); } br.close(); //logger.info(sb.toString()); JSONArray ja; try { ja = new JSONArray(new JSONTokener(sb.toString())); } catch (JSONException e) { throw new IOException(e.getMessage()); } return ja; }