List of usage examples for java.net HttpURLConnection setRequestMethod
public void setRequestMethod(String method) throws ProtocolException
From source file:Main.java
/** * Given a string url, connects and returns response code * * @param urlString string to fetch * @param network network/*from w ww.ja va 2 s.co m*/ * @param readTimeOutMs read time out * @param connectionTimeOutMs connection time out * @param urlRedirect should use urlRedirect * @param useCaches should use cache * @return httpResponseCode http response code * @throws IOException */ @TargetApi(LOLLIPOP) public static int checkUrlWithOptionsOverNetwork(String urlString, Network network, int readTimeOutMs, int connectionTimeOutMs, boolean urlRedirect, boolean useCaches) throws IOException { if (network == null) { return -1; } URL url = new URL(urlString); HttpURLConnection connection = (HttpURLConnection) network.openConnection(url); connection.setReadTimeout(readTimeOutMs /* milliseconds */); connection.setConnectTimeout(connectionTimeOutMs /* milliseconds */); connection.setRequestMethod("GET"); connection.setInstanceFollowRedirects(urlRedirect); connection.setUseCaches(useCaches); // Starts the query connection.connect(); int responseCode = connection.getResponseCode(); connection.disconnect(); return responseCode; }
From source file:com.adrguides.utils.HTTPUtils.java
public static InputStream openAddress(Context context, URL url) throws IOException { if ("file".equals(url.getProtocol()) && url.getPath().startsWith("/android_asset/")) { return context.getAssets().open(url.getPath().substring(15)); // "/android_asset/".length() == 15 } else {//from w w w.j a v a 2 s. c om URLConnection urlconn = url.openConnection(); urlconn.setReadTimeout(10000 /* milliseconds */); urlconn.setConnectTimeout(15000 /* milliseconds */); urlconn.setAllowUserInteraction(false); urlconn.setDoInput(true); urlconn.setDoOutput(false); if (urlconn instanceof HttpURLConnection) { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); int responsecode = connection.getResponseCode(); if (responsecode != HttpURLConnection.HTTP_OK) { throw new IOException("Http response code returned:" + responsecode); } } return urlconn.getInputStream(); } }
From source file:io.github.retz.scheduler.MesosHTTPFetcher.java
private static Optional<String> fetchDirectory(String slave, String frameworkId, String executorId) { try {/* ww w . j a v a2 s .c om*/ URL url = new URL("http://" + slave + "/state"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setDoOutput(true); return extractDirectory(conn.getInputStream(), frameworkId, executorId); } catch (MalformedURLException e) { // REVIEW: catch(MalformedURLException) clause can be removed because it <: IOException return Optional.empty(); } catch (IOException e) { return Optional.empty(); } }
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:com.meetingninja.csse.database.ContactDatabaseAdapter.java
public static List<Contact> addContact(String contactUserID) throws IOException { String _url = getBaseUri().build().toString(); URL url = new URL(_url); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod(IRequest.PUT); addRequestHeader(conn, false);/*from ww w . j av a 2 s . c o m*/ SessionManager session = SessionManager.getInstance(); String userID = session.getUserID(); ByteArrayOutputStream json = new ByteArrayOutputStream(); // this type of print stream allows us to get a string easily PrintStream ps = new PrintStream(json); // Create a generator to build the JSON string JsonGenerator jgen = JFACTORY.createGenerator(ps, JsonEncoding.UTF8); // Build JSON Object for Title jgen.writeStartObject(); jgen.writeStringField(Keys.User.ID, userID); jgen.writeArrayFieldStart(Keys.User.CONTACTS); jgen.writeStartObject(); jgen.writeStringField(Keys.User.CONTACTID, contactUserID); jgen.writeEndObject(); jgen.writeEndArray(); jgen.writeEndObject(); jgen.close(); String payload = json.toString("UTF8"); ps.close(); sendPostPayload(conn, payload); String response = getServerResponse(conn); // TODO: put add useful check here // User userContact=null; // String relationID=null; // String result = new String(); // if (!response.isEmpty()) { // JsonNode contactNode = MAPPER.readTree(response); // if (!contactNode.has(Keys.User.ID)) { // result = "invalid"; // } else { // result = contactNode.get(Keys.User.ID).asText(); // userContact = getUserInfo(result); // relationID = contactNode.get(Keys.User.RELATIONID).asText(); // } // } // if (!result.equalsIgnoreCase("invalid")) // g.setID(result); conn.disconnect(); // Contact contact = new Contact(userContact,relationID); List<Contact> contacts = new ArrayList<Contact>(); contacts = getContacts(userID); return contacts; }
From source file:yodlee.ysl.api.io.HTTP.java
public static String doPost(String url, String requestBody) throws IOException { String mn = "doIO(POST : " + url + ", " + requestBody + " )"; System.out.println(fqcn + " :: " + mn); URL restURL = new URL(url); HttpURLConnection conn = (HttpURLConnection) restURL.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("User-Agent", userAgent); //conn.setRequestProperty("Content-Type", contentTypeURLENCODED); conn.setRequestProperty("Content-Type", contentTypeJSON); conn.setDoOutput(true);/*from ww w .j a v a2s .c o m*/ DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); wr.writeBytes(requestBody); wr.flush(); wr.close(); int responseCode = conn.getResponseCode(); System.out.println(fqcn + " :: " + mn + " : " + "Sending 'HTTP POST' request"); 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) { 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);/* www. java 2 s . c om*/ 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); }
From source file:Main.java
private static String httpPost(String address, String params) { InputStream inputStream = null; HttpURLConnection urlConnection = null; try {// w w w.j a va 2s . c o m URL url = new URL(address); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setDoOutput(true); urlConnection.setRequestMethod("POST"); urlConnection.getOutputStream().write(params.getBytes()); urlConnection.getOutputStream().flush(); urlConnection.connect(); if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) { inputStream = urlConnection.getInputStream(); int len = 0; byte[] buffer = new byte[1024]; StringBuffer stringBuffer = new StringBuffer(); while ((len = inputStream.read(buffer)) != -1) { stringBuffer.append(new String(buffer, 0, len)); } return stringBuffer.toString(); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { close(inputStream); if (urlConnection != null) { urlConnection.disconnect(); } } return null; }
From source file:flow.visibility.tapping.OpenDaylightHelper.java
/** The function for inserting the flow */ public static boolean installFlow(JSONObject postData, String user, String password, String baseURL) { StringBuffer result = new StringBuffer(); /** Check the connection to ODP REST API page */ try {//from w w w .j a va 2 s. c o m if (!baseURL.contains("http")) { baseURL = "http://" + baseURL; } baseURL = baseURL + "/controller/nb/v2/flowprogrammer/default/node/OF/" + postData.getJSONObject("node").get("id") + "/staticFlow/" + postData.get("name"); /** Create URL = base URL + container */ URL url = new URL(baseURL); /** Create authentication string and encode it to Base64*/ String authStr = user + ":" + password; String encodedAuthStr = Base64.encodeBase64String(authStr.getBytes()); /** Create Http connection */ HttpURLConnection connection = (HttpURLConnection) url.openConnection(); /** Set connection properties */ connection.setRequestMethod("PUT"); connection.setRequestProperty("Authorization", "Basic " + encodedAuthStr); connection.setRequestProperty("Content-Type", "application/json"); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); /** Set JSON Post Data */ OutputStream os = connection.getOutputStream(); os.write(postData.toString().getBytes()); os.close(); /** Get the response from connection's inputStream */ InputStream content = (InputStream) connection.getInputStream(); BufferedReader in = new BufferedReader(new InputStreamReader(content)); String line = ""; while ((line = in.readLine()) != null) { result.append(line); } } catch (Exception e) { e.printStackTrace(); } /** checking the result of REST API connection */ if ("success".equalsIgnoreCase(result.toString())) { return true; } else { return false; } }
From source file:io.helixservice.feature.configuration.cloudconfig.CloudConfigDecrypt.java
/** * Decrypt an encrypted string// ww w .j a v a 2 s . c o m * <p> * This method blocks on a HTTP request. * * @param name property or filename for reference/logging * @param encryptedValue Encrypted string * @param cloudConfigUri URI of the Cloud Config server * @param httpBasicHeader HTTP Basic header containing username and password for Cloud Config server * @return */ public static String decrypt(String name, String encryptedValue, String cloudConfigUri, String httpBasicHeader) { String result = encryptedValue; // Remove prefix if needed if (encryptedValue.startsWith(CIPHER_PREFIX)) { encryptedValue = encryptedValue.substring(CIPHER_PREFIX.length()); } String decryptUrl = cloudConfigUri + "/decrypt"; try { HttpURLConnection connection = (HttpURLConnection) new URL(decryptUrl).openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("POST"); connection.addRequestProperty(AUTHORIZATION_HEADER, httpBasicHeader); connection.setRequestProperty("Content-Type", "text/plain"); connection.setRequestProperty("Content-Length", Integer.toString(encryptedValue.getBytes().length)); connection.setRequestProperty("Accept", "*/*"); // Write body OutputStream outputStream = connection.getOutputStream(); outputStream.write(encryptedValue.getBytes()); outputStream.close(); if (connection.getResponseCode() == 200) { InputStream inputStream = connection.getInputStream(); result = IOUtils.toString(inputStream); inputStream.close(); } else { LOG.error("Unable to Decrypt name=" + name + " due to httpStatusCode=" + connection.getResponseCode() + " for decryptUrl=" + decryptUrl); } } catch (IOException e) { LOG.error("Unable to connect to Cloud Config server at decryptUrl=" + decryptUrl, e); } return result; }