List of usage examples for java.net HttpURLConnection setRequestProperty
public void setRequestProperty(String key, String value)
From source file:net.daporkchop.porkbot.util.HTTPUtils.java
/** * Performs a POST request to the specified URL and returns the result. * <p/>/*from w w w. j a va 2 s . c o m*/ * The POST data will be encoded in UTF-8 as the specified contentType. The response will be parsed as UTF-8. * If the server returns an error but still provides a body, the body will be returned as normal. * If the server returns an error without any body, a relevant {@link java.io.IOException} will be thrown. * * @param url URL to submit the POST request to * @param post POST data in the correct format to be submitted * @param contentType Content type of the POST data * @return Raw text response from the server * @throws IOException The request was not successful */ public static String performPostRequestWithAuth(@NonNull URL url, @NonNull String post, @NonNull String contentType, @NonNull String auth) throws IOException { final HttpURLConnection connection = createUrlConnection(url); final byte[] postAsBytes = post.getBytes(Charsets.UTF_8); connection.setRequestProperty("Authorization", auth); connection.setRequestProperty("Content-Type", contentType + "; charset=utf-8"); connection.setRequestProperty("Content-Length", "" + postAsBytes.length); connection.setDoOutput(true); OutputStream outputStream = null; try { outputStream = connection.getOutputStream(); IOUtils.write(postAsBytes, outputStream); } finally { IOUtils.closeQuietly(outputStream); } return sendRequest(connection); }
From source file:com.binil.pushnotification.ServerUtil.java
/** * Issue a POST request to the server./*from www .jav a 2 s.c om*/ * * @param endpoint POST address. * @param params request parameters. * @throws java.io.IOException propagated from POST. */ private static void post(String endpoint, Map<String, Object> params) throws IOException, JSONException { URL url = new URL(endpoint); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("POST"); urlConnection.setRequestProperty("Cache-Control", "no-cache"); urlConnection.setRequestProperty("Content-Type", "application/json;charset=utf-8"); urlConnection.setRequestProperty("Accept-Encoding", "gzip,deflate"); urlConnection.setRequestProperty("Accept", "*/*"); urlConnection.setDoOutput(true); JSONObject json = new JSONObject(params); String body = json.toString(); urlConnection.setFixedLengthStreamingMode(body.length()); try { OutputStream os = urlConnection.getOutputStream(); os.write(body.getBytes("UTF-8")); os.close(); } catch (Exception e) { e.printStackTrace(); } finally { int status = urlConnection.getResponseCode(); String connectionMsg = urlConnection.getResponseMessage(); urlConnection.disconnect(); if (status != HttpURLConnection.HTTP_OK) { Log.wtf(TAG, connectionMsg); throw new IOException("Post failed with error code " + status); } } }
From source file:es.tid.cep.esperanza.Utils.java
public static boolean DoHTTPPost(String urlStr, String content) { try {/*from ww w. j av a 2 s. c o m*/ URL url = new URL(urlStr); HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); urlConn.setDoOutput(true); urlConn.setRequestProperty("Content-Type", "application/json; charset=utf-8"); OutputStreamWriter printout = new OutputStreamWriter(urlConn.getOutputStream(), Charset.forName("UTF-8")); printout.write(content); printout.flush(); printout.close(); int code = urlConn.getResponseCode(); String message = urlConn.getResponseMessage(); logger.debug("action http response " + code + " " + message); if (code / 100 == 2) { InputStream input = urlConn.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(input)); for (String line; (line = reader.readLine()) != null;) { logger.debug("action response body: " + line); } input.close(); return true; } else { logger.error("action response is not OK: " + code + " " + message); InputStream error = urlConn.getErrorStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(error)); for (String line; (line = reader.readLine()) != null;) { logger.error("action error response body: " + line); } error.close(); return false; } } catch (MalformedURLException me) { logger.error("exception MalformedURLException: " + me.getMessage()); return false; } catch (IOException ioe) { logger.error("exception IOException: " + ioe.getMessage()); return false; } }
From source file:com.arellomobile.android.push.utils.NetworkUtils.java
public static NetworkResult makeRequest(Map<String, Object> data, String methodName) throws Exception { NetworkResult result = new NetworkResult(500, null); OutputStream connectionOutput = null; InputStream inputStream = null; try {/*from w ww . jav a 2s. co m*/ String urlString = NetworkUtils.BASE_URL + methodName; if (useSSL) urlString = NetworkUtils.BASE_URL_SECURE + methodName; URL url = new URL(urlString); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json; charset=utf-8"); connection.setDoOutput(true); JSONObject innerRequestJson = new JSONObject(); for (String key : data.keySet()) { innerRequestJson.put(key, data.get(key)); } JSONObject requestJson = new JSONObject(); requestJson.put("request", innerRequestJson); connection.setRequestProperty("Content-Length", String.valueOf(requestJson.toString().getBytes().length)); connectionOutput = connection.getOutputStream(); connectionOutput.write(requestJson.toString().getBytes()); connectionOutput.flush(); connectionOutput.close(); inputStream = new BufferedInputStream(connection.getInputStream()); ByteArrayOutputStream dataCache = new ByteArrayOutputStream(); // Fully read data byte[] buff = new byte[1024]; int len; while ((len = inputStream.read(buff)) >= 0) { dataCache.write(buff, 0, len); } // Close streams dataCache.close(); String jsonString = new String(dataCache.toByteArray()).trim(); Log.w(TAG, "PushWooshResult: " + jsonString); JSONObject resultJSON = new JSONObject(jsonString); result.setData(resultJSON); result.setCode(resultJSON.getInt("status_code")); } finally { if (null != inputStream) { inputStream.close(); } if (null != connectionOutput) { connectionOutput.close(); } } return result; }
From source file:bluevia.SendSMS.java
public static void sendBlueViaSMS(String user_email, String phone_number, String sms_message) { try {// w w w . ja v a2s. c o m Properties blueviaAccount = Util.getNetworkAccount(user_email, "BlueViaAccount"); if (blueviaAccount != null) { String consumer_key = blueviaAccount.getProperty("BlueViaAccount.consumer_key"); String consumer_secret = blueviaAccount.getProperty("BlueViaAccount.consumer_secret"); String access_key = blueviaAccount.getProperty("BlueViaAccount.access_key"); String access_secret = blueviaAccount.getProperty("BlueViaAccount.access_secret"); com.google.appengine.api.urlfetch.FetchOptions.Builder.doNotValidateCertificate(); OAuthConsumer consumer = (OAuthConsumer) new DefaultOAuthConsumer(consumer_key, consumer_secret); consumer.setMessageSigner(new HmacSha1MessageSigner()); consumer.setTokenWithSecret(access_key, access_secret); URL apiURI = new URL("https://api.bluevia.com/services/REST/SMS/outbound/requests?version=v1"); HttpURLConnection request = (HttpURLConnection) apiURI.openConnection(); request.setRequestProperty("Content-Type", "application/json"); request.setRequestMethod("POST"); request.setDoOutput(true); consumer.sign(request); request.connect(); String smsTemplate = "{\"smsText\": {\n \"address\": {\"phoneNumber\": \"%s\"},\n \"message\": \"%s\",\n \"originAddress\": {\"alias\": \"%s\"},\n}}"; String smsMsg = String.format(smsTemplate, phone_number, sms_message, access_key); OutputStream os = request.getOutputStream(); os.write(smsMsg.getBytes()); os.flush(); int rc = request.getResponseCode(); if (rc == HttpURLConnection.HTTP_CREATED) log.info(String.format("SMS sent to %s. Text: %s", phone_number, sms_message)); else log.severe(String.format("Error %d sending SMS:%s\n", rc, request.getResponseMessage())); } else log.warning("BlueVia Account seems to be not configured!"); } catch (Exception e) { log.severe(String.format("Exception sending SMS: %s", e.getMessage())); } }
From source file:com.hichinaschool.flashcards.anki.web.HttpFetcher.java
public static String downloadFileToSdCardMethod(String UrlToFile, Context context, String prefix, String method) {// w w w . j a v a2 s.c o m try { URL url = new URL(UrlToFile); String extension = UrlToFile.substring(UrlToFile.length() - 4); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod(method); urlConnection.setRequestProperty("Referer", "com.hichinaschool.flashcards.anki"); urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 ( compatible ) "); urlConnection.setRequestProperty("Accept", "*/*"); urlConnection.connect(); File file = File.createTempFile(prefix, extension, DiskUtil.getStoringDirectory()); FileOutputStream fileOutput = new FileOutputStream(file); InputStream inputStream = urlConnection.getInputStream(); byte[] buffer = new byte[1024]; int bufferLength = 0; while ((bufferLength = inputStream.read(buffer)) > 0) { fileOutput.write(buffer, 0, bufferLength); } fileOutput.close(); return file.getAbsolutePath(); } catch (Exception e) { return "FAILED " + e.getMessage(); } }
From source file:cc.vileda.sipgatesync.api.SipgateApi.java
@NonNull private static String getUrl(final String apiUrl, final String token) throws IOException { final HttpURLConnection urlConnection = getConnection(apiUrl); urlConnection.setDoInput(true);/*from ww w. j av a2s.co m*/ urlConnection.setRequestMethod("GET"); if (token != null) { urlConnection.setRequestProperty("Authorization", "Bearer " + token); } StringBuilder sb = new StringBuilder(); int HttpResult = urlConnection.getResponseCode(); if (HttpResult == HttpURLConnection.HTTP_OK) { BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "utf-8")); String line; while ((line = br.readLine()) != null) { sb.append(line).append("\n"); } br.close(); return sb.toString(); } else { System.out.println(urlConnection.getResponseMessage()); } return ""; }
From source file:com.ant.myteam.gcm.POST2GCM.java
public static void post(String apiKey, Content content) { try {//from w w w . j a v a 2 s . c o m // 1. URL URL url = new URL("https://android.googleapis.com/gcm/send"); // 2. Open connection HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 3. Specify POST method conn.setRequestMethod("POST"); // 4. Set the headers conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Authorization", "key=" + apiKey); conn.setDoOutput(true); // 5. Add JSON data into POST request body //`5.1 Use Jackson object mapper to convert Contnet object into JSON ObjectMapper mapper = new ObjectMapper(); // 5.2 Get connection output stream DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); // 5.3 Copy Content "JSON" into mapper.writeValue(wr, content); // 5.4 Send the request wr.flush(); // 5.5 close wr.close(); // 6. Get the response int responseCode = conn.getResponseCode(); System.out.println("\nSending 'POST' request to URL : " + url); System.out.println("Response Code : " + responseCode); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); // 7. Print result System.out.println(response.toString()); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:de.cubeisland.engine.core.util.McUUID.java
private static HttpURLConnection postQuery(ArrayNode node, int page) throws IOException { HttpURLConnection con = (HttpURLConnection) new URL(MOJANG_API_URL_NAME_UUID + page).openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("Content-Type", "application/json"); con.setUseCaches(false);//from w ww. j a va 2 s . c o m con.setDoInput(true); con.setDoOutput(true); DataOutputStream writer = new DataOutputStream(con.getOutputStream()); writer.write(node.toString().getBytes()); writer.close(); return con; }
From source file:pushandroid.POST2GCM.java
public static void post(Content content) { try {//from w ww .ja va2 s. c o m // 1. URL URL url = new URL(URL); // 2. Open connection HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 3. Specify POST method conn.setRequestMethod("POST"); // 4. Set the headers conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Authorization", "key=" + apiKey); conn.setDoOutput(true); // 5. Add JSON data into POST request body //`5.1 Use Jackson object mapper to convert Contnet object into JSON ObjectMapper mapper = new ObjectMapper(); // 5.2 Get connection output stream DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); // 5.3 Copy Content "JSON" into mapper.writeValue(wr, content); // 5.4 Send the request wr.flush(); // 5.5 close wr.close(); // 6. Get the response int responseCode = conn.getResponseCode(); System.out.println("\nSending 'POST' request to URL : " + url); System.out.println("Response Code : " + responseCode); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); // 7. Print result System.out.println(response.toString()); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }