List of usage examples for java.net HttpURLConnection setRequestProperty
public void setRequestProperty(String key, String value)
From source file:com.cacacan.sender.GcmSenderRunnable.java
@Override public void run() { LOGGER.info("Started sender thread"); try {/*w w w.j ava 2 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.deltadna.android.sdk.net.RequestBody.java
void fill(HttpURLConnection connection) throws IOException { connection.setFixedLengthStreamingMode(content.length); connection.setRequestProperty("Content-Type", type); OutputStream output = null;/* ww w . ja v a2 s . c om*/ try { output = connection.getOutputStream(); output.write(content); } finally { if (output != null) { output.close(); } } }
From source file:ict.servlet.UploadToServer.java
public static int upLoad2Server(String sourceFileUri) { String upLoadServerUri = "http://vbacdu.ddns.net:8080/WBS/newjsp.jsp"; // String [] string = sourceFileUri; String fileName = sourceFileUri; int serverResponseCode = 0; HttpURLConnection conn = null; DataOutputStream dos = null;/*w w w . jav a 2s . c o m*/ DataInputStream inStream = null; String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = "*****"; int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1 * 1024 * 1024; String responseFromServer = ""; File sourceFile = new File(sourceFileUri); if (!sourceFile.isFile()) { return 0; } try { // open a URL connection to the Servlet FileInputStream fileInputStream = new FileInputStream(sourceFile); URL url = new URL(upLoadServerUri); conn = (HttpURLConnection) url.openConnection(); // Open a HTTP connection to the URL conn.setDoInput(true); // Allow Inputs conn.setDoOutput(true); // Allow Outputs conn.setUseCaches(false); // Don't use a Cached Copy conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("ENCTYPE", "multipart/form-data"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); conn.setRequestProperty("uploaded_file", fileName); dos = new DataOutputStream(conn.getOutputStream()); dos.writeBytes(twoHyphens + boundary + lineEnd); dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\"" + fileName + "\"" + lineEnd); dos.writeBytes(lineEnd); bytesAvailable = fileInputStream.available(); // create a buffer of maximum size bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; // read file and write it into form... bytesRead = fileInputStream.read(buffer, 0, bufferSize); while (bytesRead > 0) { dos.write(buffer, 0, bufferSize); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.read(buffer, 0, bufferSize); } // send multipart form data necesssary after file data... dos.writeBytes(lineEnd); dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); // Responses from the server (code and message) serverResponseCode = conn.getResponseCode(); String serverResponseMessage = conn.getResponseMessage(); m_log.info("Upload file to server" + "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode); // close streams m_log.info("Upload file to server" + fileName + " File is written"); fileInputStream.close(); dos.flush(); dos.close(); } catch (MalformedURLException ex) { // ex.printStackTrace(); m_log.error("Upload file to server" + "error: " + ex.getMessage(), ex); } catch (Exception e) { // e.printStackTrace(); } //this block will give the response of upload link /* try { BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { m_log.info("Huzza" + "RES Message: " + line); } rd.close(); } catch (IOException ioex) { m_log.error("Huzza" + "error: " + ioex.getMessage(), ioex); }*/ return serverResponseCode; // like 200 (Ok) }
From source file:com.opensesame.opensesamedoor.GCMSender.GcmSender.java
@Override protected Long doInBackground(String... params) { String message = params[0];//w ww.ja va 2 s .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.graphhopper.http.NominatimGeocoder.java
HttpURLConnection openConnection(String url) throws IOException { HttpURLConnection hConn = (HttpURLConnection) new URL(url).openConnection(); ;/* ww w .j av a 2 s. c o m*/ hConn.setRequestProperty("User-Agent", userAgent); hConn.setRequestProperty("content-charset", "UTF-8"); hConn.setConnectTimeout(timeoutInMillis); hConn.setReadTimeout(timeoutInMillis); hConn.connect(); return hConn; }
From source file:eu.serco.dhus.server.http.webapp.wps.controller.WpsAdfSearchController.java
@RequestMapping(value = "/auxiliaries/download", method = { RequestMethod.GET }) public ResponseEntity<?> downloadAuxiliaries(@RequestParam(value = "uuid", defaultValue = "") String uuid, @RequestParam(value = "filename", defaultValue = "file") String filename) { try {// w ww. j av a 2s. co m String hashedString = ConfigurationManager.getHashedConnectionString(); //SD-1928 add download filename archive extension String downloadFilename = (filename.endsWith(DOWNLOAD_EXT)) ? (filename) : filename + DOWNLOAD_EXT; String urlString = ConfigurationManager.getExternalDHuSHost() + "odata/v1/Products('" + uuid + "')/$value"; logger.info("urlString:::: " + urlString); URL url = new URL(urlString); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("Authorization", "Basic " + hashedString); InputStream is = conn.getInputStream(); InputStreamResource isr = new InputStreamResource(is); HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.add("Authorization", "Basic " + hashedString); httpHeaders.add("Content-disposition", "attachment; filename=" + downloadFilename); httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM); return new ResponseEntity<>(isr, httpHeaders, HttpStatus.OK); } catch (Exception e) { logger.error(" Failed to download Auxiliary File."); e.printStackTrace(); return new ResponseEntity<>("{\"code\":\"unauthorized\"}", HttpStatus.UNAUTHORIZED); } }
From source file:com.spotify.helios.system.APITest.java
private HttpURLConnection post(final String path, final byte[] body) throws IOException { final URL url = new URL(masterEndpoint() + path); final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); connection.setDoInput(true);//from w w w .j a va 2 s . c o m connection.setDoOutput(true); connection.getOutputStream().write(body); return connection; }
From source file:com.playhaven.android.req.UrlRequest.java
@Override public String call() throws MalformedURLException, IOException, PlayHavenException { HttpURLConnection connection = (HttpURLConnection) new URL(mInitialUrl).openConnection(); connection.setInstanceFollowRedirects(true); connection.setRequestProperty(CoreProtocolPNames.USER_AGENT, UserAgent.USER_AGENT); connection.getContent(); // .getHeaderFields() will return null if headers not accessed once before if (connection.getHeaderFields().containsKey(LOCATION_HEADER)) { return connection.getHeaderField(LOCATION_HEADER); } else {/*from w w w .ja v a 2s . c o m*/ throw new PlayHavenException(); } }
From source file:net.ae97.pokebot.extensions.scrolls.BadgeRanks.java
private synchronized void sync() { if (lastUpdate + (1000 * 60 * 60 * 24) > System.currentTimeMillis()) { return;/*from w ww .j a v a2 s . c om*/ } try { URL url = new URL(syncURL); List<String> lines = new LinkedList<>(); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("User-Agent", "PokeBot - " + PokeBot.VERSION); conn.connect(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()))) { String line; while ((line = reader.readLine()) != null) { lines.add(line); } } JsonParser parser = new JsonParser(); JsonElement element = parser.parse(StringUtils.join(lines, "\n")); JsonObject obj = element.getAsJsonObject(); String result = obj.get("msg").getAsString(); if (!result.equalsIgnoreCase("success")) { throw new IOException("API replied with error"); } JsonArray dataObject = obj.get("data").getAsJsonArray(); synchronized (ranks) { ranks.clear(); for (int i = 0; i < dataObject.size(); i++) { JsonObject rank = dataObject.get(i).getAsJsonObject(); ranks.put(rank.get("id").getAsString(), rank.get("name").getAsString()); } ranks.put("-1", "No badge"); } lastUpdate = System.currentTimeMillis(); } catch (IOException | JsonSyntaxException ex) { extension.getLogger().log(Level.SEVERE, "Error on syncing badge ranks", ex); lastUpdate = -1; } }
From source file:acclaim.Acclaim.java
public String doHTTPPostRequest(String url) throws Exception { String rawData = "id=10"; String type = "application/x-www-form-urlencoded"; String encodedData = URLEncoder.encode(rawData); URL u = new URL("http://www.example.com/page.php"); HttpURLConnection conn = (HttpURLConnection) u.openConnection(); conn.setDoOutput(true);// w w w . java 2 s . c o m conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", type); conn.setRequestProperty("Content-Length", String.valueOf(encodedData.length())); OutputStream os = conn.getOutputStream(); os.write(encodedData.getBytes()); return null; }