List of usage examples for java.net HttpURLConnection setRequestProperty
public void setRequestProperty(String key, String value)
From source file:com.yahoo.athenz.example.ntoken.HttpExampleClient.java
public static void main(String[] args) throws MalformedURLException, IOException { // parse our command line to retrieve required input CommandLine cmd = parseCommandLine(args); String domainName = cmd.getOptionValue("domain"); String serviceName = cmd.getOptionValue("service"); String privateKeyPath = cmd.getOptionValue("pkey"); String keyId = cmd.getOptionValue("keyid"); String url = cmd.getOptionValue("url"); // we need to generate our principal credentials (ntoken). In // addition to the domain and service names, we need the // the service's private key and the key identifier - the // service with the corresponding public key must already be // registered in ZMS PrivateKey privateKey = Crypto.loadPrivateKey(new File(privateKeyPath)); ServiceIdentityProvider identityProvider = new SimpleServiceIdentityProvider(domainName, serviceName, privateKey, keyId);/*from www . j a v a2 s . c o m*/ Principal principal = identityProvider.getIdentity(domainName, serviceName); URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // set our Athenz credentials. The authority in the principal provides // the header name that we must use for credentials while the principal // itself provides the credentials (ntoken). con.setRequestProperty(principal.getAuthority().getHeader(), principal.getCredentials()); // now process our request int responseCode = con.getResponseCode(); switch (responseCode) { case HttpURLConnection.HTTP_FORBIDDEN: System.out.println("Request was forbidden - not authorized: " + con.getResponseMessage()); break; case HttpURLConnection.HTTP_OK: System.out.println("Successful response: "); try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) { String inputLine; while ((inputLine = in.readLine()) != null) { System.out.println(inputLine); } } break; default: System.out.println("Request failed - response status code: " + responseCode); } }
From source file:Naive.java
public static void main(String[] args) throws Exception { // Basic access authentication setup String key = "CHANGEME: YOUR_API_KEY"; String secret = "CHANGEME: YOUR_API_SECRET"; String version = "preview1"; // CHANGEME: the API version to use String practiceid = "000000"; // CHANGEME: the practice ID to use // Find the authentication path Map<String, String> auth_prefix = new HashMap<String, String>(); auth_prefix.put("v1", "oauth"); auth_prefix.put("preview1", "oauthpreview"); auth_prefix.put("openpreview1", "oauthopenpreview"); URL authurl = new URL("https://api.athenahealth.com/" + auth_prefix.get(version) + "/token"); HttpURLConnection conn = (HttpURLConnection) authurl.openConnection(); conn.setRequestMethod("POST"); // Set the Authorization request header String auth = Base64.encodeBase64String((key + ':' + secret).getBytes()); conn.setRequestProperty("Authorization", "Basic " + auth); // Since this is a POST, the parameters go in the body conn.setDoOutput(true);//from w w w. java2 s .c om String contents = "grant_type=client_credentials"; DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); wr.writeBytes(contents); wr.flush(); wr.close(); // Read the response BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while ((line = rd.readLine()) != null) { sb.append(line); } rd.close(); // Decode from JSON and save the token for later String response = sb.toString(); JSONObject authorization = new JSONObject(response); String token = authorization.get("access_token").toString(); // GET /departments HashMap<String, String> params = new HashMap<String, String>(); params.put("limit", "1"); // Set up the URL, method, and Authorization header URL url = new URL("https://api.athenahealth.com/" + version + "/" + practiceid + "/departments" + "?" + urlencode(params)); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Authorization", "Bearer " + token); rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); sb = new StringBuilder(); while ((line = rd.readLine()) != null) { sb.append(line); } rd.close(); response = sb.toString(); JSONObject departments = new JSONObject(response); System.out.println(departments.toString()); // POST /appointments/{appointmentid}/notes params = new HashMap<String, String>(); params.put("notetext", "Hello from Java!"); url = new URL("https://api.athenahealth.com/" + version + "/" + practiceid + "/appointments/1/notes"); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Authorization", "Bearer " + token); // POST parameters go in the body conn.setDoOutput(true); contents = urlencode(params); wr = new DataOutputStream(conn.getOutputStream()); wr.writeBytes(contents); wr.flush(); wr.close(); rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); sb = new StringBuilder(); while ((line = rd.readLine()) != null) { sb.append(line); } rd.close(); response = sb.toString(); JSONObject note = new JSONObject(response); System.out.println(note.toString()); }
From source file:OCRRestAPI.java
public static void main(String[] args) throws Exception { /*/*from w w w .ja va 2 s . c om*/ Sample project for OCRWebService.com (REST API). Extract text from scanned images and convert into editable formats. Please create new account with ocrwebservice.com via http://www.ocrwebservice.com/account/signup and get license code */ // Provide your user name and license code String license_code = "88EF173D-CDEA-41B6-8D64-C04578ED8C4D"; String user_name = "FERGOID"; /* You should specify OCR settings. See full description http://www.ocrwebservice.com/service/restguide Input parameters: [language] - Specifies the recognition language. This parameter can contain several language names separated with commas. For example "language=english,german,spanish". Optional parameter. By default:english [pagerange] - Enter page numbers and/or page ranges separated by commas. For example "pagerange=1,3,5-12" or "pagerange=allpages". Optional parameter. By default:allpages [tobw] - Convert image to black and white (recommend for color image and photo). For example "tobw=false" Optional parameter. By default:false [zone] - Specifies the region on the image for zonal OCR. The coordinates in pixels relative to the left top corner in the following format: top:left:height:width. This parameter can contain several zones separated with commas. For example "zone=0:0:100:100,50:50:50:50" Optional parameter. [outputformat] - Specifies the output file format. Can be specified up to two output formats, separated with commas. For example "outputformat=pdf,txt" Optional parameter. By default:doc [gettext] - Specifies that extracted text will be returned. For example "tobw=true" Optional parameter. By default:false [description] - Specifies your task description. Will be returned in response. Optional parameter. !!!! For getting result you must specify "gettext" or "outputformat" !!!! */ // Build your OCR: // Extraction text with English language String ocrURL = "http://www.ocrwebservice.com/restservices/processDocument?gettext=true"; // Extraction text with English and German language using zonal OCR ocrURL = "http://www.ocrwebservice.com/restservices/processDocument?language=english,german&zone=0:0:600:400,500:1000:150:400"; // Convert first 5 pages of multipage document into doc and txt // ocrURL = "http://www.ocrwebservice.com/restservices/processDocument?language=english&pagerange=1-5&outputformat=doc,txt"; // Full path to uploaded document String filePath = "sarah-morgan.jpg"; byte[] fileContent = Files.readAllBytes(Paths.get(filePath)); URL url = new URL(ocrURL); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Authorization", "Basic " + Base64.getEncoder().encodeToString((user_name + ":" + license_code).getBytes())); // Specify Response format to JSON or XML (application/json or application/xml) connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("Content-Length", Integer.toString(fileContent.length)); int httpCode; try (OutputStream stream = connection.getOutputStream()) { // Send POST request stream.write(fileContent); stream.close(); } catch (Exception e) { System.out.println(e.toString()); } httpCode = connection.getResponseCode(); System.out.println("HTTP Response code: " + httpCode); // Success request if (httpCode == HttpURLConnection.HTTP_OK) { // Get response stream String jsonResponse = GetResponseToString(connection.getInputStream()); // Parse and print response from OCR server PrintOCRResponse(jsonResponse); } else if (httpCode == HttpURLConnection.HTTP_UNAUTHORIZED) { System.out.println("OCR Error Message: Unauthorizied request"); } else { // Error occurred String jsonResponse = GetResponseToString(connection.getErrorStream()); JSONParser parser = new JSONParser(); JSONObject jsonObj = (JSONObject) parser.parse(jsonResponse); // Error message System.out.println("Error Message: " + jsonObj.get("ErrorMessage")); } connection.disconnect(); }
From source file:com.yahoo.athenz.example.ztoken.HttpExampleClient.java
public static void main(String[] args) throws MalformedURLException, IOException { // parse our command line to retrieve required input CommandLine cmd = parseCommandLine(args); String domainName = cmd.getOptionValue("domain"); String serviceName = cmd.getOptionValue("service"); String privateKeyPath = cmd.getOptionValue("pkey"); String keyId = cmd.getOptionValue("keyid"); String url = cmd.getOptionValue("url"); String ztsUrl = cmd.getOptionValue("ztsurl"); String providerDomain = cmd.getOptionValue("provider-domain"); String providerRole = cmd.getOptionValue("provider-role"); // we need to generate our principal credentials (ntoken). In // addition to the domain and service names, we need the // the service's private key and the key identifier - the // service with the corresponding public key must already be // registered in ZMS PrivateKey privateKey = Crypto.loadPrivateKey(new File(privateKeyPath)); ServiceIdentityProvider identityProvider = new SimpleServiceIdentityProvider(domainName, serviceName, privateKey, keyId);/*from w w w . j ava 2s.c o m*/ // now we need to retrieve a role token (ztoken) for accessing // the provider Athenz enabled service RoleToken roleToken = null; try (ZTSClient ztsClient = new ZTSClient(ztsUrl, domainName, serviceName, identityProvider)) { roleToken = ztsClient.getRoleToken(providerDomain, providerRole); } if (roleToken == null) { System.out.println( "Unable to retrieve role token for: " + providerRole + " in domain: " + providerDomain); System.exit(1); } URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // set our Athenz credentials. The ZTSClient provides the header // name that we must use for authorization token while the role // token itself provides the token string (ztoken). System.out.println("Using RoleToken: " + roleToken.getToken()); con.setRequestProperty(ZTSClient.getHeader(), roleToken.getToken()); // now process our request int responseCode = con.getResponseCode(); switch (responseCode) { case HttpURLConnection.HTTP_FORBIDDEN: System.out.println("Request was forbidden - not authorized: " + con.getResponseMessage()); break; case HttpURLConnection.HTTP_OK: System.out.println("Successful response: "); try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) { String inputLine; while ((inputLine = in.readLine()) != null) { System.out.println(inputLine); } } break; default: System.out.println("Request failed - response status code: " + responseCode); } }
From source file:ru.apertum.qsystem.client.forms.FAdmin.java
/** * @param args the command line arguments * @throws Exception/*from w w w. j a va 2 s. c om*/ */ public static void main(String args[]) throws Exception { QLog.initial(args, 3); Locale.setDefault(Locales.getInstance().getLangCurrent()); //? ? , ? final Thread tPager = new Thread(() -> { FAbout.loadVersionSt(); String result = ""; try { final URL url = new URL(PAGER_URL + "/qskyapi/getpagerdata?qsysver=" + FAbout.VERSION_); final HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("User-Agent", "Java bot"); conn.connect(); final int code = conn.getResponseCode(); if (code == 200) { try (BufferedReader in = new BufferedReader( new InputStreamReader(conn.getInputStream(), "utf8"))) { String inputLine; while ((inputLine = in.readLine()) != null) { result += inputLine; } } } conn.disconnect(); } catch (Exception e) { System.err.println("Pager not enabled. " + e); return; } final Gson gson = GsonPool.getInstance().borrowGson(); try { final Answer answer = gson.fromJson(result, Answer.class); forPager = answer; if (answer.getData().size() > 0) { forPager.start(); } } catch (Exception e) { System.err.println("Pager not enabled but working. " + e); } finally { GsonPool.getInstance().returnGson(gson); } }); tPager.setDaemon(true); tPager.start(); Uses.startSplash(); // plugins Uses.loadPlugins("./plugins/"); // ?. FLogin.logining(QUserList.getInstance(), null, true, 3, FLogin.LEVEL_ADMIN); Uses.showSplash(); java.awt.EventQueue.invokeLater(() -> { try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager .getInstalledLookAndFeels()) { System.out.println(info.getName()); /*Metal Nimbus CDE/Motif Windows Windows Classic //GTK+*/ if ("Windows".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } if ("/".equals(File.separator)) { final FontUIResource f = new FontUIResource(new Font("Serif", Font.PLAIN, 10)); final Enumeration<Object> keys = UIManager.getDefaults().keys(); while (keys.hasMoreElements()) { final Object key = keys.nextElement(); final Object value = UIManager.get(key); if (value instanceof FontUIResource) { final FontUIResource orig = (FontUIResource) value; final Font font1 = new Font(f.getFontName(), orig.getStyle(), f.getSize()); UIManager.put(key, new FontUIResource(font1)); } } } } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { } try { form = new FAdmin(); if (forPager != null) { forPager.showData(false); } else { form.panelPager.setVisible(false); } form.setVisible(true); } catch (Exception ex) { QLog.l().logger().error(" ? ?? . ", ex); } finally { Uses.closeSplash(); } }); }
From source file:Main.java
public static boolean download(String uri, String filePath) { try {//from ww w .j a v a 2s .c o m URL url = new URL(uri); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("User-Agent", AGENT); readStreamToFile(conn.getInputStream(), filePath); } catch (Exception e) { e.printStackTrace(); return false; } return true; }
From source file:Main.java
public static String execUrl(String uri) { String res = ""; try {// w ww . j a va2 s . c o m URL url = new URL(uri); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("User-Agent", AGENT); res = readStream(conn.getInputStream()); } catch (Exception e) { e.printStackTrace(); res = ""; } return res; }
From source file:Main.java
public static boolean isAvailable(String urlString) throws IOException { try {/* w w w . j a v a 2s. c o m*/ StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); URL url = new URL(urlString); HttpURLConnection urlc = (HttpURLConnection) url.openConnection(); urlc.setRequestProperty("Connection", "close"); urlc.setConnectTimeout(1000); urlc.connect(); if (urlc.getResponseCode() == 200) { return true; } else { return false; } } catch (Exception e) { e.printStackTrace(); } return false; }
From source file:Main.java
public static HttpURLConnection buildConnection(String url) throws IOException { HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection(); /*set request*/ con.setRequestProperty("Accept-Language", "UTF-8"); return con;//from w w w .j a va 2s . c om }
From source file:Main.java
public static String getResponse(String urlParam) { try {/*www .ja v a2 s. co m*/ URL url = new URL(urlParam); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE6.0; Windows NT 5.1; SV1)"); conn.setConnectTimeout(5000); conn.setRequestMethod("GET"); if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) { InputStream inputStream = conn.getInputStream(); return inputStream2String(inputStream); } } catch (IOException e) { e.printStackTrace(); return null; } return null; }