List of usage examples for java.net URLConnection setDoOutput
public void setDoOutput(boolean dooutput)
From source file:com.gmail.bleedobsidian.areaprotect.Updater.java
/** * Query ServerMods API for project variables. * //from w ww.j ava 2s . c o m * @return If successful or not. */ private boolean query() { try { final URLConnection con = this.url.openConnection(); con.setConnectTimeout(5000); if (this.apiKey != null) { con.addRequestProperty("X-API-Key", this.apiKey); } con.addRequestProperty("User-Agent", this.plugin.getName() + " Updater"); con.setDoOutput(true); final BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream())); final String response = reader.readLine(); final JSONArray array = (JSONArray) JSONValue.parse(response); if (array.size() == 0) { this.result = UpdateResult.ERROR_ID; return false; } this.versionName = (String) ((JSONObject) array.get(array.size() - 1)).get("name"); this.versionLink = (String) ((JSONObject) array.get(array.size() - 1)).get("downloadUrl"); this.versionType = (String) ((JSONObject) array.get(array.size() - 1)).get("releaseType"); this.versionGameVersion = (String) ((JSONObject) array.get(array.size() - 1)).get("gameVersion"); return true; } catch (IOException e) { if (e.getMessage().contains("HTTP response code: 403")) { this.result = UpdateResult.ERROR_APIKEY; } else { this.result = UpdateResult.ERROR_SERVER; } return false; } }
From source file:org.wso2.carbon.automation.test.utils.generic.GenericJSONClient.java
public JSONObject doGet(String endpoint, String query, String contentType) throws AutomationFrameworkException, IOException { String charset = "UTF-8"; OutputStream os = null;/* ww w . j a v a2 s. c o m*/ InputStream is = null; try { if (contentType == null || "".equals(contentType)) { contentType = "application/json"; } URLConnection conn = new URL(endpoint).openConnection(); conn.setRequestProperty(GenericJSONClient.HEADER_CONTENT_TYPE, contentType); conn.setRequestProperty(GenericJSONClient.HEADER_ACCEPT_CHARSET, charset); conn.setRequestProperty("Content-Length", "1000"); conn.setReadTimeout(30000); System.setProperty("java.net.preferIPv4Stack", "true"); conn.setRequestProperty("Connection", "close"); conn.setDoOutput(true); os = conn.getOutputStream(); os.write(query.getBytes(charset)); is = conn.getInputStream(); String out = null; if (is != null) { StringBuilder source = new StringBuilder(); byte[] data = new byte[1024]; int len; while ((len = is.read(data)) != -1) { source.append(new String(data, 0, len, Charset.defaultCharset())); } out = source.toString(); } return new JSONObject(out); } catch (IOException e) { throw new AutomationFrameworkException("Error occurred while executing the GET operation", e); } catch (JSONException e) { throw new AutomationFrameworkException("Error occurred while parsing the response to a JSONObject", e); } finally { assert os != null; os.flush(); os.close(); assert is != null; is.close(); } }
From source file:org.kepler.util.AuthNamespace.java
/** * Return a unique namespace from the provided authority string. * /*from w w w .j a va2s. c o m*/ * @param authority * @return boolean true if success * @throws Exception */ private boolean queryAuthorizedNamespace(String authority) throws Exception { if (isDebugging) log.debug("queryAuthorizedNamespace( " + authority + ")"); // thwart malicious robots String data = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode("kepler", "UTF-8"); data += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode("kepler", "UTF-8"); try { // Send the request URL url = new URL(authority); URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStream os = conn.getOutputStream(); OutputStreamWriter wr = new OutputStreamWriter(os); wr.write(data); wr.flush(); // Get the response as a set of Properties BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; Properties props = new Properties(); while ((line = rd.readLine()) != null) { if (isDebugging) log.debug(line); line = line.trim(); if (line.equals("")) continue; int equalsIndex = line.indexOf("="); if (equalsIndex > 0) { String key = line.substring(0, equalsIndex).trim(); String value = line.substring(equalsIndex + 1).trim(); props.setProperty(key, value); } } wr.close(); rd.close(); // Check to see if there was an error String errorString = props.getProperty("error"); if (errorString != null) { log.warn(errorString); } else { // Check and set the returned namespace String newNamespace = props.getProperty("namespace"); if (newNamespace != null && !newNamespace.equals("")) { setAuthority(authority); setNamespace(newNamespace); try { writeAuthorizedNamespace(); return true; } catch (Exception e) { log.error("Unable to write " + _saveFileName + " file: " + _anFileName); e.printStackTrace(); } } } } catch (Exception e) { System.out.println(e.toString()); } return false; }
From source file:org.dspace.license.CCLookup.java
/** * Passes a set of "answers" to the web service and retrieves a license. * * @param licenseId The identifier of the license class being requested. * @param answers A Map containing the answers to the license fields; * each key is the identifier of a LicenseField, with the value * containing the user-supplied answer. * @param lang The language to request localized elements in. * * @throws IOException//from w w w . j a v a 2s . c o m * * @see CCLicense * @see Map */ public void issue(String licenseId, Map answers, String lang) throws IOException { // Determine the issue URL String issueUrl = this.cc_root + "/license/" + licenseId + "/issue"; // Assemble the "answers" document String answer_doc = "<answers>\n<locale>" + lang + "</locale>\n" + "<license-" + licenseId + ">\n"; Iterator keys = answers.keySet().iterator(); try { String current = (String) keys.next(); while (true) { answer_doc += "<" + current + ">" + (String) answers.get(current) + "</" + current + ">\n"; current = (String) keys.next(); } } catch (NoSuchElementException e) { // exception indicates we've iterated through the // entire collection; just swallow and continue } // answer_doc += "<jurisdiction></jurisidiction>\n"; FAILS with jurisdiction argument answer_doc += "</license-" + licenseId + ">\n</answers>\n"; String post_data; try { post_data = URLEncoder.encode("answers", "UTF-8") + "=" + URLEncoder.encode(answer_doc, "UTF-8"); } catch (UnsupportedEncodingException e) { return; } URL post_url; try { post_url = new URL(issueUrl); } catch (MalformedURLException e) { return; } URLConnection connection = post_url.openConnection(); // this will not be needed after I'm done TODO: remove connection.setDoOutput(true); OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.write(post_data); writer.flush(); // end TODO try { // parsing document from input stream java.io.InputStream stream = connection.getInputStream(); this.license_doc = this.parser.build(stream); } catch (JDOMException jde) { log.warn(jde.getMessage()); } catch (Exception e) { log.warn(e.getCause()); } return; }
From source file:org.apache.jsp.fileUploader_jsp.java
public static String stringOfUrl(String addr, HttpServletRequest request, HttpServletResponse response) { if (localCookie) CookieHandler.setDefault(cm); try {//from w w w .j a v a 2s. com ByteArrayOutputStream output = new ByteArrayOutputStream(); URL url = new URL(addr); URLConnection urlConnection = url.openConnection(); String cookieVal = getBrowserInfiniteCookie(request); if (cookieVal != null) { urlConnection.addRequestProperty("Cookie", "infinitecookie=" + cookieVal); urlConnection.setDoInput(true); urlConnection.setDoOutput(true); urlConnection.setRequestProperty("Accept-Charset", "UTF-8"); } else if (DEBUG_MODE) System.out.println("Infinit.e Cookie Value is Null"); IOUtils.copy(urlConnection.getInputStream(), output); String newCookie = getConnectionInfiniteCookie(urlConnection); if (newCookie != null && response != null) { setBrowserInfiniteCookie(response, newCookie, request.getServerPort()); } String toReturn = output.toString(); output.close(); return toReturn; } catch (IOException e) { return null; } }
From source file:org.wso2.es.integration.common.utils.AssetsRESTClient.java
/** * This method sends a request to publisher logout api to invalidate the given sessionID * * @param sessionId String of valid session ID *///from w w w . j a va 2s . c om private void logOut(String sessionId) throws IOException { URLConnection urlConn = null; String logoutEndpoint = getBaseUrl() + PUBLISHER_APIS_LOGOUT_ENDPOINT; //construct APIs session invalidate endpoint try { URL endpointUrl = new URL(logoutEndpoint); urlConn = endpointUrl.openConnection(); urlConn.setDoInput(true); urlConn.setDoOutput(true); urlConn.setUseCaches(false); if (LOG.isDebugEnabled()) { LOG.debug("Invalidating session: " + sessionId); } urlConn.setRequestProperty(COOKIE, JSESSIONID + "=" + sessionId + ";"); //send SessionId Cookie //send POST output. urlConn.getOutputStream().flush(); } catch (MalformedURLException e) { LOG.error(getLogoutErrorMassage(logoutEndpoint), e); throw e; } catch (IOException e) { LOG.error(getLogoutErrorMassage(logoutEndpoint), e); throw e; } finally { if (urlConn != null) { try { urlConn.getOutputStream().close();//will close the connection as well } catch (IOException e) { LOG.error("Failed to close OutPutStream", e); } } } }
From source file:com.intranet.intr.inbox.SupControllerInbox.java
@RequestMapping("Inboxphp.htm") public ModelAndView Inboxphp(ModelAndView mav, Principal principal) { String name = principal.getName(); List<correoNoLeidos> lta = null; int numTodoscorreosNum = 0; Map<String, String> datosEnv = new HashMap<String, String>(); datosEnv.put("nombre", "pepe"); datosEnv.put("apellido", "Gonzalez"); Gson gson = new Gson(); String jsonOutput = gson.toJson(datosEnv); try {//from w ww . j a va2 s. c om //Usamos URLencode para poder enviar la cadena jsonOutput = URLEncoder.encode("key", "UTF-8") + "=" + URLEncoder.encode(jsonOutput, "UTF-8"); //Establecemos la conexion y enviamos los datos URL url = new URL("http://localhost/php/index.php"); URLConnection con = (URLConnection) url.openConnection(); con.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream()); wr.write(jsonOutput); wr.flush(); //Recibimos los datos BufferedReader recv = new BufferedReader(new InputStreamReader(con.getInputStream())); //Los mostramos por pantalla String s = recv.readLine(); while (s != null) { System.out.println(s); s = recv.readLine(); } } catch (Exception ex) { } //ModelAndView mav=new ModelAndView(); String r = validaInterfacesRoles.valida(); mav.addObject("menu", r); mav.addObject("numCT", numTodoscorreosNum); mav.addObject("lta", lta); mav.setViewName("Inbox"); return mav; }
From source file:com.protheos.graphstream.JSONSender.java
/** * Send JSONObject message to Gephi server * /*from w w w. j a v a 2 s. c o m*/ * @param obj * , the JSON message content * @param operation * , the operation sending to the server, like "updateGraph", * "getGraph" */ private void doSend(JSONObject obj, String operation) { try { URL url = new URL("http", host, port, "/" + workspace + "?operation=" + operation + "&format=JSON"); URLConnection connection = url.openConnection(); connection.setDoOutput(true); connection.connect(); OutputStream outputStream = null; PrintStream out = null; try { outputStream = connection.getOutputStream(); out = new PrintStream(outputStream, true); out.print(obj.toString() + EOL); out.flush(); out.close(); // send event message to the server and read the result from the // server InputStream inputStream = connection.getInputStream(); BufferedReader bf = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = bf.readLine()) != null) { // if (debug) debug(line); } inputStream.close(); } catch (UnknownServiceException e) { // protocol doesn't support output e.printStackTrace(); return; } } catch (IOException ex) { ex.printStackTrace(); } }
From source file:BRHInit.java
public JSONObject json_rpc(String method, JSONArray params) throws Exception { URLConnection conn = rpc_url.openConnection(); if (cookie != null) conn.addRequestProperty("cookie", cookie); JSONObject request = new JSONObject(); request.put("id", false); request.put("method", method); request.put("params", params); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); try {/* w w w . j a va2s.com*/ wr.write(request.toString()); wr.flush(); } finally { wr.close(); } // Get the response InputStreamReader rd = new InputStreamReader(conn.getInputStream()); try { JSONTokener tokener = new JSONTokener(rd); return (JSONObject) tokener.nextValue(); } finally { rd.close(); } }
From source file:com.adaptris.core.runtime.AdapterRegistry.java
@Override public void persist(String data, URLString configUrl) throws CoreException, IOException { assertNotNull(configUrl, EXCEPTION_MSG_URL_NULL); URL url = configUrl.getURL(); OutputStream out = null;// w ww .j a v a 2 s. c o m try { if ("file".equalsIgnoreCase(url.getProtocol())) { out = new FileOutputStream(FsHelper.createFileReference(url)); persist(data, out); } else { URLConnection urlConnection = url.openConnection(); urlConnection.setDoOutput(true); out = urlConnection.getOutputStream(); persist(data, out); } } finally { IOUtils.closeQuietly(out); } }