List of usage examples for java.net HttpURLConnection setRequestProperty
public void setRequestProperty(String key, String value)
From source file:common.net.volley.toolbox.HurlStack.java
private static void requestDecompression(HttpURLConnection conn) { conn.setRequestProperty(HEADER_ACCEPT_ENCODING, GZIP_ENCODING); }
From source file:website.openeng.anki.web.HttpFetcher.java
public static String downloadFileToSdCardMethod(String UrlToFile, Context context, String prefix, String method) {/*from www . j a va 2 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", "website.openeng.anki"); urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 ( compatible ) "); urlConnection.setRequestProperty("Accept", "*/*"); urlConnection.setConnectTimeout(10000); urlConnection.setReadTimeout(60000); urlConnection.connect(); File file = File.createTempFile(prefix, extension, context.getCacheDir()); 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:com.jts.rest.profileservice.utils.RestServiceHelper.java
/** * Makes a get request to the given url and returns the json object * @param sessionId/* w w w . j a va2 s. c om*/ * @param url * @return * @throws MalformedURLException * @throws IOException */ public static JSONArray makeGetRequest(String sessionId, String url) throws MalformedURLException, IOException { URL endpoint = new URL(url); HttpURLConnection urlc = (HttpURLConnection) endpoint.openConnection(); urlc.setRequestProperty("Authorization", "OAuth " + sessionId); urlc.setRequestMethod("GET"); urlc.setDoOutput(true); String output = OauthHelperUtils.readInputStream(urlc.getInputStream()); urlc.disconnect(); Object json = JSONValue.parse(output); JSONArray jsonArr = (JSONArray) json; return jsonArr; }
From source file:jfutbol.com.jfutbol.GcmSender.java
public static void SendNotification(int userId, int notificationCounter) { String msg[] = new String[2]; if (notificationCounter > 1) msg = new String[] { "Tienes " + notificationCounter + " nuevas notificaciones.", "/topics/" + userId }; else//from ww w . j a v a2 s .c o m msg = new String[] { "Tienes " + notificationCounter + " nueva notificacion.", "/topics/" + userId }; if (msg.length < 1 || msg.length > 2 || msg[0] == null) { System.err.println("usage: ./gradlew run -Pmsg=\"MESSAGE\" [-Pto=\"DEVICE_TOKEN\"]"); System.err.println(""); System.err.println( "Specify a test message to broadcast via GCM. If a device's GCM registration token is\n" + "specified, the message will only be sent to that device. Otherwise, the message \n" + "will be sent to all devices subscribed to the \"global\" topic."); System.err.println(""); System.err.println( "Example (Broadcast):\n" + "On Windows: .\\gradlew.bat run -Pmsg=\"<Your_Message>\"\n" + "On Linux/Mac: ./gradlew run -Pmsg=\"<Your_Message>\""); System.err.println(""); System.err.println("Example (Unicast):\n" + "On Windows: .\\gradlew.bat run -Pmsg=\"<Your_Message>\" -Pto=\"<Your_Token>\"\n" + "On Linux/Mac: ./gradlew run -Pmsg=\"<Your_Message>\" -Pto=\"<Your_Token>\""); System.exit(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", msg[0].trim()); // Where to send GCM message. if (msg.length > 1 && msg[1] != null) { jGcmData.put("to", msg[1].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); updateNotificationAsSent(userId); 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)."); log.error(e.getMessage()); e.printStackTrace(); } }
From source file:Main.java
public static String executePost(String url, String parameters) throws IOException { URL request = new URL(url); HttpURLConnection connection = (HttpURLConnection) request.openConnection(); connection.setDoOutput(true);/*from www .j a va2 s. c o m*/ connection.setDoInput(true); connection.setInstanceFollowRedirects(false); connection.setRequestMethod("POST"); connection.setRequestProperty("User-Agent", "StripeConnectAndroid"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("charset", "utf-8"); connection.setRequestProperty("Content-Length", "" + Integer.toString(parameters.getBytes().length)); connection.setUseCaches(false); DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(parameters); wr.flush(); wr.close(); String response = streamToString(connection.getInputStream()); connection.disconnect(); return response; }
From source file:com.microsoft.intellij.util.WAHelper.java
public static void sendGet(String sitePath) throws Exception { URL url = new URL(sitePath); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); con.setRequestProperty("User-Agent", "AzureToolkit for Intellij"); int responseCode = con.getResponseCode(); }
From source file:javaphpmysql.JavaPHPMySQL.java
public static void sendGet() { //Creamos un objeto JSON JSONObject jsonObj = new JSONObject(); //Aadimos el nombre, apellidos y email del usuario jsonObj.put("nombre", nombre); jsonObj.put("apellidos", apellidos); jsonObj.put("email", email); //Creamos una lista para almacenar el JSON List l = new LinkedList(); l.addAll(Arrays.asList(jsonObj)); //Generamos el String JSON String jsonString = JSONValue.toJSONString(l); System.out.println("JSON GENERADO:"); System.out.println(jsonString); System.out.println(""); try {//from w w w. j av a2s. c o m //Codificar el json a URL jsonString = URLEncoder.encode(jsonString, "UTF-8"); //Generar la URL String url = SERVER_PATH + "listenGet.php?json=" + jsonString; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // optional default is GET con.setRequestMethod("GET"); //add request header con.setRequestProperty("User-Agent", USER_AGENT); int responseCode = con.getResponseCode(); System.out.println("\nSending 'GET' request to URL : " + url); System.out.println("Response Code : " + responseCode); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); //print result System.out.println(response.toString()); } catch (Exception e) { e.printStackTrace(); } }
From source file:net.andylizi.colormotd.utils.AttributionUtil.java
private static String sendGet(String url, String param, String charset) { StringBuilder result = new StringBuilder(1024); BufferedReader in = null;//from w w w . j ava 2s . c o m try { String urlNameString = url + "?" + param; URL realUrl = new URL(urlNameString); HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection(); conn.setRequestProperty("User-Agent", "ColorMOTD/" + UUID.randomUUID()); conn.setRequestProperty("Accept-Charset", charset); conn.setUseCaches(true); conn.setConnectTimeout(2000); conn.setReadTimeout(3000); conn.connect(); in = new BufferedReader(new InputStreamReader(conn.getInputStream(), Charset.forName(charset)), 1024); String line; while ((line = in.readLine()) != null) { result.append(line); } conn.disconnect(); } catch (Exception e) { } finally { try { if (in != null) { in.close(); } } catch (Exception e2) { } } return result.toString(); }
From source file:yodlee.ysl.api.io.HTTP.java
public static String doGet(String url, Map<String, String> sessionTokens) throws IOException, URISyntaxException { String mn = "doIO(GET :" + url + ", sessionTokens = " + sessionTokens.toString() + " )"; System.out.println(fqcn + " :: " + mn); URL myURL = new URL(url); System.out.println(fqcn + " :: " + mn + ": Request URL=" + url.toString()); HttpURLConnection conn = (HttpURLConnection) myURL.openConnection(); //conn.setRequestMethod("GET"); conn.setRequestProperty("User-Agent", userAgent); //conn.setRequestProperty("Content-Type", contentTypeJSON); //conn.setRequestProperty("Accept",); conn.setRequestProperty("Authorization", sessionTokens.toString()); conn.setDoOutput(true);/*from w w w . ja v a 2s. c om*/ System.out.println(fqcn + " :: " + mn + " : " + "Sending 'HTTP GET' request"); int responseCode = conn.getResponseCode(); System.out.println(fqcn + " :: " + mn + " : " + "Response Code : " + responseCode); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String inputLine; StringBuilder jsonResponse = new StringBuilder(); while ((inputLine = in.readLine()) != null) { System.out.println(inputLine); jsonResponse.append(inputLine); } in.close(); System.out.println(fqcn + " :: " + mn + " : " + jsonResponse.toString()); return new String(jsonResponse); }
From source file:yodlee.ysl.api.io.HTTP.java
public static String doPut(String url, String param, Map<String, String> sessionTokens) throws IOException, URISyntaxException { String mn = "doIO(PUT :" + url + ", sessionTokens = " + sessionTokens.toString() + " )"; System.out.println(fqcn + " :: " + mn); param = param.replace("\"", "%22").replace("{", "%7B").replace("}", "%7D").replace(",", "%2C") .replace("[", "%5B").replace("]", "%5D").replace(":", "%3A").replace(" ", "+"); String processedURL = url + "?MFAChallenge=" + param;//"%7B%22loginForm%22%3A%7B%22formType%22%3A%22token%22%2C%22mfaTimeout%22%3A%2299380%22%2C%22row%22%3A%5B%7B%22id%22%3A%22token_row%22%2C%22label%22%3A%22Security+Key%22%2C%22form%22%3A%220001%22%2C%22fieldRowChoice%22%3A%220001%22%2C%22field%22%3A%5B%7B%22id%22%3A%22token%22%2C%22name%22%3A%22tokenValue%22%2C%22type%22%3A%22text%22%2C%22value%22%3A%22123456%22%2C%22isOptional%22%3Afalse%2C%22valueEditable%22%3Atrue%2C%22maxLength%22%3A%2210%22%7D%5D%7D%5D%7D%7D"; URL myURL = new URL(processedURL); System.out.println(fqcn + " :: " + mn + ": Request URL=" + processedURL.toString()); HttpURLConnection conn = (HttpURLConnection) myURL.openConnection(); conn.setRequestMethod("PUT"); conn.setRequestProperty("Accept-Charset", "UTF-8"); conn.setRequestProperty("Content-Type", contentTypeURLENCODED); conn.setRequestProperty("Authorization", sessionTokens.toString()); conn.setDoOutput(true);//from w ww .j a v a 2 s .c o m System.out.println(fqcn + " :: " + mn + " : " + "Sending 'HTTP PUT' request"); int responseCode = conn.getResponseCode(); System.out.println(fqcn + " :: " + mn + " : " + "Response Code : " + responseCode); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String inputLine; StringBuilder jsonResponse = new StringBuilder(); while ((inputLine = in.readLine()) != null) { System.out.println(inputLine); jsonResponse.append(inputLine); } in.close(); System.out.println(fqcn + " :: " + mn + " : " + jsonResponse.toString()); return new String(jsonResponse); }