List of usage examples for java.net HttpURLConnection getOutputStream
public OutputStream getOutputStream() throws IOException
From source file:com.opensesame.opensesamedoor.GCMSender.GcmSender.java
@Override protected Long doInBackground(String... params) { String message = params[0];/*from w w w .j a va2s . c o m*/ String deviceToken = params[1]; try { // Prepare JSON containing the GCM message content. What to send and where to send. JSONObject jGcmData = new JSONObject(); JSONObject jData = new JSONObject(); jData.put("message", message.trim()); // Where to send GCM message. if (deviceToken != null) { jGcmData.put("to", deviceToken.trim()); } else { jGcmData.put("to", "/topics/global"); } // What to send in GCM message. jGcmData.put("data", jData); // Create connection to send GCM Message request. URL url = new URL("https://android.googleapis.com/gcm/send"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("Authorization", "key=" + API_KEY); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestMethod("POST"); conn.setDoOutput(true); // Send GCM message content. OutputStream outputStream = conn.getOutputStream(); outputStream.write(jGcmData.toString().getBytes()); // Read GCM response. InputStream inputStream = conn.getInputStream(); String resp = IOUtils.toString(inputStream); System.out.println(resp); System.out.println("Check your device/emulator for notification or logcat for " + "confirmation of the receipt of the GCM message."); } catch (IOException e) { System.out.println("Unable to send GCM message."); System.out.println("Please ensure that API_KEY has been replaced by the server " + "API key, and that the device's registration token is correct (if specified)."); e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } return 1L; }
From source file:com.youTransactor.uCube.mdm.task.SendLogsTask.java
@Override protected void start() { HttpURLConnection urlConnection = null; try {/*from w ww . j a v a 2 s . co m*/ urlConnection = MDMManager.getInstance().initRequest(SEND_LOGS_WS + deviceInfos.getPartNumber() + '/' + deviceInfos.getSerial() + "?type=" + fileType, MDMManager.POST_METHOD); urlConnection.setRequestProperty("Content-Type", "application/octet-stream"); OutputStream output = urlConnection.getOutputStream(); IOUtils.copy(in, output); HTTPResponseCode = urlConnection.getResponseCode(); if (HTTPResponseCode == 200) { notifyMonitor(TaskEvent.SUCCESS); return; } LogManager.debug(GetConfigTask.class.getSimpleName(), "send logs WS error: " + HTTPResponseCode); } catch (Exception e) { LogManager.debug(GetConfigTask.class.getSimpleName(), "\"send logs WS error", e); } finally { if (urlConnection != null) { urlConnection.disconnect(); } } notifyMonitor(TaskEvent.FAILED, this); }
From source file:com.cacacan.sender.GcmSenderRunnable.java
@Override public void run() { LOGGER.info("Started sender thread"); try {/*from w w w . jav a2 s .c om*/ // Prepare JSON containing the GCM message content. What to send and // where to send. final JSONObject jGcmData = new JSONObject(); final JSONObject jData = new JSONObject(); jData.put("message", message.trim()); // Where to send GCM message. jGcmData.put("to", "/topics/global"); // What to send in GCM message. jGcmData.put("data", jData); // Create connection to send GCM Message request. final URL url = new URL("https://android.googleapis.com/gcm/send"); final HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("Authorization", "key=" + API_KEY); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestMethod("POST"); conn.setDoOutput(true); // Send GCM message content. final OutputStream outputStream = conn.getOutputStream(); outputStream.write(jGcmData.toString().getBytes()); LOGGER.info("Sent message via GCM: " + message); // Read GCM response. final InputStream inputStream = conn.getInputStream(); final String resp = IOUtils.toString(inputStream); LOGGER.info(resp); } catch (IOException | JSONException e) { LOGGER.error( "Unable to send GCM message.\n" + "Please ensure that API_KEY has been replaced by the server " + "API key, and that the device's registration token is correct (if specified)."); } }
From source file:com.example.appengine.java8.LaunchDataflowTemplate.java
@Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { String project = "YOUR_PROJECT_NAME"; String bucket = "gs://YOUR_BUCKET_NAME"; ArrayList<String> scopes = new ArrayList<String>(); scopes.add("https://www.googleapis.com/auth/cloud-platform"); final AppIdentityService appIdentity = AppIdentityServiceFactory.getAppIdentityService(); final AppIdentityService.GetAccessTokenResult accessToken = appIdentity.getAccessToken(scopes); JSONObject jsonObj = null;/*from w ww. ja v a2 s . co m*/ try { JSONObject parameters = new JSONObject().put("datastoreReadGqlQuery", "SELECT * FROM Entries") .put("datastoreReadProjectId", project).put("textWritePrefix", bucket + "/output/"); JSONObject environment = new JSONObject().put("tempLocation", bucket + "/tmp/") .put("bypassTempDirValidation", false); jsonObj = new JSONObject().put("jobName", "template-" + UUID.randomUUID().toString()) .put("parameters", parameters).put("environment", environment); } catch (JSONException e) { e.printStackTrace(); } URL url = new URL(String.format("https://dataflow.googleapis.com/v1b3/projects/%s/templates" + ":launch?gcs_path=gs://dataflow-templates/latest/Datastore_to_GCS_Text", project)); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Authorization", "Bearer " + accessToken.getAccessToken()); conn.setRequestProperty("Content-Type", "application/json"); OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); jsonObj.write(writer); writer.close(); int respCode = conn.getResponseCode(); if (respCode == HttpURLConnection.HTTP_OK) { response.setContentType("application/json"); String line; BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); while ((line = reader.readLine()) != null) { response.getWriter().println(line); } reader.close(); } else { StringWriter w = new StringWriter(); IOUtils.copy(conn.getErrorStream(), w, "UTF-8"); response.getWriter().println(w.toString()); } }
From source file:de.thingweb.discovery.TDRepository.java
/** * Update existing TD/*from w w w. jav a 2 s.c o m*/ * * @param key in repository (/td/{id}) * @param content JSON-LD * @throws Exception in case of error */ public void updateTD(String key, byte[] content) throws Exception { URL url = new URL("http://" + repository_uri + key); HttpURLConnection httpCon = (HttpURLConnection) url.openConnection(); httpCon.setDoOutput(true); httpCon.setRequestProperty("content-type", "application/ld+json"); httpCon.setRequestMethod("PUT"); OutputStream out = httpCon.getOutputStream(); out.write(content); out.close(); // InputStream is = httpCon.getInputStream(); // ByteArrayOutputStream baos = new ByteArrayOutputStream(); // int b; // while ((b = is.read()) != -1) { // baos.write(b); // } int responseCode = httpCon.getResponseCode(); httpCon.disconnect(); if (responseCode != 200) { // error throw new RuntimeException("ResponseCodeError: " + responseCode); } }
From source file:com.googlecode.jsonrpc4j.JsonRpcHttpClient.java
/** * Invokes the given method with the given arguments and returns * an object of the given type, or null if void. * * @see JsonRpcClient#writeRequest(String, Object, java.io.OutputStream, String) * @param methodName the name of the method to invoke * @param arguments the arguments to the method * @param returnType the return type/* w w w . j a v a 2 s.c o m*/ * @param extraHeaders extra headers to add to the request * @return the return value * @throws Throwable on error */ public Object invoke(String methodName, Object argument, Type returnType, Map<String, String> extraHeaders) throws Throwable { // create URLConnection HttpURLConnection con = prepareConnection(extraHeaders); con.connect(); // invoke it OutputStream ops = con.getOutputStream(); try { super.invoke(methodName, argument, ops); } finally { ops.close(); } // read and return value try { InputStream ips = con.getInputStream(); try { // in case of http error try to read response body and return it in exception return super.readResponse(returnType, ips); } finally { ips.close(); } } catch (IOException e) { throw new HttpException(readString(con.getErrorStream()), e); } }
From source file:com.gmail.ferusgrim.util.UuidGrabber.java
public Map<String, UUID> call() throws Exception { JSONParser jsonParser = new JSONParser(); Map<String, UUID> responseMap = new HashMap<String, UUID>(); URL url = new URL("https://api.mojang.com/profiles/minecraft"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); connection.setUseCaches(false);//from w w w . j av a2s . c o m connection.setDoInput(true); connection.setDoOutput(true); String body = JSONArray.toJSONString(this.namesToLookup); OutputStream stream = connection.getOutputStream(); stream.write(body.getBytes()); stream.flush(); stream.close(); JSONArray array = (JSONArray) jsonParser.parse(new InputStreamReader(connection.getInputStream())); for (Object profile : array) { JSONObject jsonProfile = (JSONObject) profile; String id = (String) jsonProfile.get("id"); String name = (String) jsonProfile.get("name"); UUID uuid = Grab.uuidFromResult(id); responseMap.put(name, uuid); } return responseMap; }
From source file:com.mnxfst.stream.listener.webtrends.WebtrendsTokenRequest.java
private String httpPost(Map<String, String> requestParams) throws Exception { final URL url = new URL(authUrl); final StringBuilder data = new StringBuilder(); for (String key : requestParams.keySet()) data.append(String.format("%s=%s&", key, requestParams.get(key))); final String dataString = data.toString(); final String formData = dataString.substring(0, dataString.length() - 1); final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-type", "application/x-www-form-urlencoded"); connection.setDoOutput(true);//from w w w . j ava 2 s. c o m final OutputStream outputStream = connection.getOutputStream(); final OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream); outputStreamWriter.write(formData); outputStreamWriter.flush(); InputStream is = connection.getResponseCode() != 400 ? connection.getInputStream() : connection.getErrorStream(); final BufferedReader rd = new BufferedReader(new InputStreamReader(is)); final StringBuffer stringBuffer = new StringBuffer(); String line; while ((line = rd.readLine()) != null) stringBuffer.append(line); outputStreamWriter.close(); rd.close(); if (connection.getResponseCode() == 400) throw new Exception("error: " + stringBuffer.toString()); return stringBuffer.toString(); }
From source file:com.dnastack.ga4gh.impl.BeaconizeVariantImpl.java
/** * Queries the Variant API implementation for variants at the given position * * @param reference The reference (or chromosome) * @param position Position on the reference * @param alt The alternate allele to match against (currently not supported by GASearchVariantsRequest) * @return A JSON Object containing a GASearchVariantsResponse * @throws IOException Problems contacting API * @throws ParseException Problems parsing response *//*w w w .j a va2s .c o m*/ private JSONObject submitVariantSearchRequest(String reference, long position, String alt) throws IOException, ParseException { JSONObject obj = new JSONObject(); JSONArray list = new JSONArray(); list.addAll(Arrays.asList(variantSetIds)); obj.put("variantSetIds", list); obj.put("referenceName", reference); obj.put("start", position); obj.put("end", (position + 1)); String json = obj.toJSONString(); URL url = new URL(fullVariantSearchURL); StringBuilder postData = new StringBuilder(); postData.append(json); byte[] postDataBytes = postData.toString().getBytes("UTF-8"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length)); conn.setDoOutput(true); conn.getOutputStream().write(postDataBytes); StringBuilder sb = new StringBuilder(); Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); for (int c; (c = in.read()) >= 0;) { sb.append((char) c); } String jsonString = sb.toString(); return (JSONObject) JSONValue.parseWithException(jsonString); }
From source file:de.thingweb.discovery.TDRepository.java
/** * Adds a ThingDescription to Repository * //ww w . j a v a2 s .c o m * @param content JSON-LD * @return key of entry in repository * @throws Exception in case of error */ public String addTD(byte[] content) throws Exception { URL url = new URL("http://" + repository_uri + "/td"); HttpURLConnection httpCon = (HttpURLConnection) url.openConnection(); httpCon.setDoOutput(true); httpCon.setRequestProperty("content-type", "application/ld+json"); httpCon.setRequestMethod("POST"); OutputStream out = httpCon.getOutputStream(); out.write(content); out.close(); InputStream is = httpCon.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); int b; while ((b = is.read()) != -1) { baos.write(b); } int responseCode = httpCon.getResponseCode(); httpCon.disconnect(); String key = ""; // new String(baos.toByteArray()); if (responseCode != 201) { // error throw new RuntimeException("ResponseCodeError: " + responseCode); } else { Map<String, List<String>> hf = httpCon.getHeaderFields(); List<String> los = hf.get("Location"); if (los != null && los.size() > 0) { key = los.get(0); } } return key; }