List of usage examples for java.net HttpURLConnection getInputStream
public InputStream getInputStream() throws IOException
From source file:com.cyphermessenger.client.SyncRequest.java
public static void userLogout(CypherSession session) throws IOException, APIErrorException { HttpURLConnection conn = doRequest("logout", session, null); if (conn.getResponseCode() != 200) { throw new IOException("Server error"); }//w w w . ja v a2 s . c o m InputStream in = conn.getInputStream(); JsonNode node = MAPPER.readTree(in); conn.disconnect(); int statusCode = node.get("status").asInt(); if (statusCode != StatusCode.OK) { throw new APIErrorException(statusCode); } }
From source file:com.mycompany.craftdemo.utility.java
public static JSONObject getAPIData(String apiURL) { try {//from w ww .j a v a2 s . c om URL url = new URL(apiURL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "application/json"); if (conn.getResponseCode() != 200) { throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); } BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); StringBuilder sb = new StringBuilder(); String output; while ((output = br.readLine()) != null) sb.append(output); String res = sb.toString(); JSONParser parser = new JSONParser(); JSONObject json = null; try { json = (JSONObject) parser.parse(res); } catch (ParseException ex) { ex.printStackTrace(); } //resturn api data in json format return json; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }
From source file:Main.java
/** * Connect to an HTTP URL and return the response as a string. * //from w ww .j ava2 s .c om * Note that the HTTP method override is used on non-GET requests. (i.e. * requests are made as "POST" with method specified in the body). * * @param url - the resource to open: must be a welformed URL * @param method - the HTTP method to use ("GET", "POST", etc.) * @param params - the query parameter for the URL (e.g. access_token=foo) * @return the URL contents as a String * @throws MalformedURLException - if the URL format is invalid * @throws IOException - if a network problem occurs */ public static String openUrl(String url, String method, Bundle params) throws MalformedURLException, IOException { if (method.equals("GET")) { url = url + "?" + encodeUrl(params); } HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent") + " FacebookAndroidSDK"); if (!method.equals("GET")) { // use method override params.putString("method", method); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.getOutputStream().write(encodeUrl(params).getBytes("UTF-8")); } String response = ""; try { response = read(conn.getInputStream()); } catch (FileNotFoundException e) { // Error Stream contains JSON that we can parse to a FB error response = read(conn.getErrorStream()); } return response; }
From source file:dk.nsi.minlog.test.utils.TestHelper.java
public static String sendRequest(String url, String action, String docXml, boolean failOnError) throws IOException, ServiceException { URL u = new URL(url); HttpURLConnection uc = (HttpURLConnection) u.openConnection(); uc.setDoOutput(true);//from w w w . ja va 2s .c om uc.setDoInput(true); uc.setRequestMethod("POST"); uc.setRequestProperty("SOAPAction", "\"" + action + "\""); uc.setRequestProperty("Content-Type", "text/xml; charset=utf-8;"); OutputStream os = uc.getOutputStream(); IOUtils.write(docXml, os, "UTF-8"); os.flush(); os.close(); InputStream is; if (uc.getResponseCode() != 200) { is = uc.getErrorStream(); } else { is = uc.getInputStream(); } String res = IOUtils.toString(is); is.close(); if (uc.getResponseCode() != 200 && (uc.getResponseCode() != 500 || failOnError)) { throw new ServiceException(res); } uc.disconnect(); return res; }
From source file:io.github.retz.executor.FileManager.java
private static void fetchHTTPFile(String file, String dest) throws IOException { URL url = new URL(file); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setDoOutput(true);//from w w w . j av a2 s .c o m java.nio.file.Path path = Paths.get(file).getFileName(); if (path == null) { throw new FileNotFoundException(file); } String filename = path.toString(); InputStream input = null; try (FileOutputStream output = new FileOutputStream(dest + "/" + filename)) { input = conn.getInputStream(); byte[] buffer = new byte[65536]; int bytesRead = 0; while ((bytesRead = input.read(buffer)) != -1) { output.write(buffer, 0, bytesRead); } } catch (IOException e) { LOG.debug(e.getMessage()); throw e; } finally { if (input != null) input.close(); } conn.disconnect(); LOG.info("Download finished: {}", file); }
From source file:com.dycody.android.idealnote.utils.GeocodeHelper.java
public static List<String> autocomplete(String input) { String MAPS_API_KEY = BuildConfig.MAPS_API_KEY; if (TextUtils.isEmpty(MAPS_API_KEY)) { return Collections.emptyList(); }//ww w. j a va 2s. co m ArrayList<String> resultList = null; HttpURLConnection conn = null; InputStreamReader in = null; StringBuilder jsonResults = new StringBuilder(); try { URL url = new URL(PLACES_API_BASE + TYPE_AUTOCOMPLETE + OUT_JSON + "?key=" + MAPS_API_KEY + "&input=" + URLEncoder.encode(input, "utf8")); conn = (HttpURLConnection) url.openConnection(); in = new InputStreamReader(conn.getInputStream()); // Load the results into a StringBuilder int read; char[] buff = new char[1024]; while ((read = in.read(buff)) != -1) { jsonResults.append(buff, 0, read); } } catch (MalformedURLException e) { Log.e(Constants.TAG, "Error processing Places API URL"); return null; } catch (IOException e) { Log.e(Constants.TAG, "Error connecting to Places API"); return null; } finally { if (conn != null) { conn.disconnect(); } if (in != null) { try { in.close(); } catch (IOException e) { Log.e(Constants.TAG, "Error closing address autocompletion InputStream"); } } } try { // Create a JSON object hierarchy from the results JSONObject jsonObj = new JSONObject(jsonResults.toString()); JSONArray predsJsonArray = jsonObj.getJSONArray("predictions"); // Extract the Place descriptions from the results resultList = new ArrayList<>(predsJsonArray.length()); for (int i = 0; i < predsJsonArray.length(); i++) { resultList.add(predsJsonArray.getJSONObject(i).getString("description")); } } catch (JSONException e) { Log.e(Constants.TAG, "Cannot process JSON results", e); } finally { if (conn != null) { conn.disconnect(); } SystemHelper.closeCloseable(in); } return resultList; }
From source file:com.dmsl.anyplace.utils.NetworkUtils.java
public static InputStream downloadHttp(String urlS) throws URISyntaxException, IOException { InputStream is = null;/*from w w w .java2s .c o m*/ URL url = new URL(encodeURL(urlS)); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(10000); conn.setConnectTimeout(15000); conn.setRequestMethod("GET"); conn.setDoInput(true); conn.connect(); int response = conn.getResponseCode(); if (response == 200) { is = conn.getInputStream(); } return is; }
From source file:com.cyphermessenger.client.SyncRequest.java
private static JsonNode pullUpdate(CypherSession session, CypherUser contact, String action, Boolean since, Long time) throws IOException, APIErrorException { String timeBoundary = "since"; if (since != null && since == UNTIL) { timeBoundary = "until"; }//from w ww . j ava2s . c o m HashMap<String, String> pairs = new HashMap<>(3); pairs.put("action", action); if (contact != null) { pairs.put("contactID", contact.getUserID().toString()); } if (time != null) { pairs.put(timeBoundary, time.toString()); } HttpURLConnection conn = doRequest("pull", session, pairs); if (conn.getResponseCode() != 200) { throw new IOException("Server error"); } InputStream in = conn.getInputStream(); JsonNode node = MAPPER.readTree(in); conn.disconnect(); int statusCode = node.get("status").asInt(); if (statusCode == StatusCode.OK) { return node; } else { throw new APIErrorException(statusCode); } }
From source file:com.appdynamics.common.RESTClient.java
public static void sendGet(String urlString, String apiKey) { try {//from w ww . jav a 2s . c o m URL url = new URL(urlString); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "application/json"); conn.setRequestProperty("Authorization", "Basic " + new String(Base64.encodeBase64((apiKey).getBytes()))); if (conn.getResponseCode() != 200) { throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); } BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); String output; logger.info("Output from Server .... \n"); while ((output = br.readLine()) != null) { logger.info(output); } conn.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:net.andylizi.colormotd.anim.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. jav a 2s. c o m try { String urlNameString = url + "?" + param; URL realUrl = new URL(urlNameString); HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection(); conn.setRequestProperty("User-Agent", Main.getInstance().getDescription().getFullName()); 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(); }