List of usage examples for java.net HttpURLConnection disconnect
public abstract void disconnect();
From source file:com.appsimobile.appsii.module.weather.loader.YahooWeatherApiClient.java
public static LocationInfo getLocationInfo(Location location) throws CantGetWeatherException { LocationInfo li = new LocationInfo(); // first=tagname (admin1, locality3) second=woeid HttpURLConnection connection = null; try {//w w w . j av a2 s .co m connection = Utils.openUrlConnection(buildPlaceSearchUrl(location)); InputStream inputStream = connection.getInputStream(); return parseLocationInfo(li, inputStream); } catch (IOException | XmlPullParserException e) { throw new CantGetWeatherException(true, R.string.no_weather_data, "Error parsing place search XML", e); } finally { if (connection != null) { connection.disconnect(); } } }
From source file:com.evrythng.java.wrapper.util.FileUtils.java
private static void validateConnectionAfterUpload(final HttpURLConnection connection) throws IOException { int responseCode = connection.getResponseCode(); if (responseCode == 200) { try (final InputStream is = connection.getInputStream()) { while (is.read() > 0) { // consume }// w w w . ja v a 2 s. c o m } } else { try (final InputStream is = connection.getErrorStream()) { final String error = IOUtils.toString(is); throw new IOException(String.format("Unable to upload file. Got error %d %s: %s", responseCode, connection.getResponseMessage(), error)); } } connection.disconnect(); }
From source file:net.doubledoordev.cmd.CurseModpackDownloader.java
public static String getFinalURL(String url) throws IOException { while (true) { HttpURLConnection con = null; try {//from w ww . j a v a2 s. co m con = (HttpURLConnection) new URL(url).openConnection(); con.setInstanceFollowRedirects(false); con.connect(); if (con.getHeaderField("Location") == null) return url; url = con.getHeaderField("Location"); } catch (IOException e) { return url; } finally { if (con != null) con.disconnect(); } } }
From source file:com.meetingninja.csse.database.TaskDatabaseAdapter.java
public static void getTask(Task t) throws JsonParseException, JsonMappingException, IOException { // Server URL setup String _url = getBaseUri().appendPath(t.getID()).build().toString(); URL url = new URL(_url); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // add request header conn.setRequestMethod(IRequest.GET); addRequestHeader(conn, false);//www .j ava 2s .c o m // Get server response int responseCode = conn.getResponseCode(); String response = getServerResponse(conn); // Initialize ObjectMapper // List<Task> taskList = new ArrayList<Task>(); final JsonNode taskNode = MAPPER.readTree(response); // if(taskArray.isArray()){ // for(final JsonNode taskNode : taskArray){ parseTask(taskNode, t); // if(t!=null){ // taskList.add(t); // } // } // } conn.disconnect(); // return void; }
From source file:com.google.android.gcm.demo.app.ServerUtilities.java
/** * Issue a POST request to the server./* w w w .j ava2s . c om*/ * * @param endpoint POST address. * @param params request parameters. * * @throws IOException propagated from POST. */ private static void post(String endpoint, Map<String, String> params) throws IOException { URL url; try { url = new URL(endpoint); } catch (MalformedURLException e) { throw new IllegalArgumentException("invalid url: " + endpoint); } JSONObject jsonObj = new JSONObject(params); String body = jsonObj.toString(); Log.v(TAG, "Posting '" + body + "' to " + url); byte[] bytes = body.getBytes(); HttpURLConnection conn = null; try { conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setUseCaches(false); conn.setFixedLengthStreamingMode(bytes.length); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); // post the request OutputStream out = conn.getOutputStream(); out.write(bytes); out.close(); // handle the response int status = conn.getResponseCode(); if (status != 200) { throw new IOException("Post failed with error code " + status); } } finally { if (conn != null) { conn.disconnect(); } } }
From source file:com.ibuildapp.romanblack.CataloguePlugin.utils.Utils.java
public static String downloadFileAsString(String url) { final int CONNECTION_TIMEOUT = 30000; final int READ_TIMEOUT = 30000; try {//from w ww. j a v a 2 s .co m for (int i = 0; i < 3; i++) { URL fileUrl = new URL(URLDecoder.decode(url)); HttpURLConnection connection = (HttpURLConnection) fileUrl.openConnection(); connection.setConnectTimeout(CONNECTION_TIMEOUT); connection.setReadTimeout(READ_TIMEOUT); connection.connect(); int status = connection.getResponseCode(); if (status >= HttpStatus.SC_BAD_REQUEST) { connection.disconnect(); continue; } BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(connection.getInputStream())); StringBuilder stringBuilder = new StringBuilder(); String line; while ((line = bufferedReader.readLine()) != null) stringBuilder.append(line); bufferedReader.close(); return stringBuilder.toString(); } } catch (Exception e) { e.printStackTrace(); return null; } return null; }
From source file:Main.java
private static void post(String endpoint, Map<String, String> params) throws IOException { URL url;/*from ww w. j av a 2 s. co m*/ try { url = new URL(endpoint); } catch (MalformedURLException e) { throw new IllegalArgumentException("invalid url: " + endpoint); } StringBuilder bodyBuilder = new StringBuilder(); Iterator<Map.Entry<String, String>> iterator = params.entrySet().iterator(); // constructs the POST body using the parameters while (iterator.hasNext()) { Map.Entry<String, String> param = iterator.next(); bodyBuilder.append(param.getKey()).append('=').append(param.getValue()); if (iterator.hasNext()) { bodyBuilder.append('&'); } } String body = bodyBuilder.toString(); Log.v(TAG, "Posting '" + body + "' to " + url); byte[] bytes = body.getBytes(); HttpURLConnection conn = null; try { Log.e("URL", "> " + url); conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setUseCaches(false); conn.setFixedLengthStreamingMode(bytes.length); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); // post the request OutputStream out = conn.getOutputStream(); out.write(bytes); out.close(); // handle the response int status = conn.getResponseCode(); if (status != 200) { throw new IOException("Post failed with error code " + status); } } finally { if (conn != null) { conn.disconnect(); } } }
From source file:outfox.dict.contest.util.FileUtils.java
/** * ??//from w w w. j a va 2 s .c o m * @param downloadUrl * @return */ public static byte[] getbytesFromURL(String downloadUrl) { HttpURLConnection httpUrl = null; ByteArrayOutputStream out = null; byte[] byteArray = null; InputStream in = null; try { // URL url = new URL(downloadUrl); httpUrl = (HttpURLConnection) url.openConnection(); // ? httpUrl.connect(); // ?? in = httpUrl.getInputStream(); out = new ByteArrayOutputStream(); byte[] b = new byte[4096]; int n; while ((n = in.read(b)) != -1) { out.write(b, 0, n); } byteArray = out.toByteArray(); in.close(); out.close(); httpUrl.disconnect(); } catch (Exception e) { LOG.error("FileUtils.getBytesFromURL error...", e); } return byteArray; }
From source file:Main.java
static String downloadHtml(String urlString) { StringBuffer buffer = new StringBuffer(); try {/*from ww w .jav a 2 s. c o m*/ URL url = new URL(urlString); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); HttpURLConnection.setFollowRedirects(true); conn.setRequestProperty("Accept-Encoding", "gzip, deflate"); String encoding = conn.getContentEncoding(); InputStream inStr = null; if (encoding != null && encoding.equalsIgnoreCase("gzip")) { inStr = new GZIPInputStream(conn.getInputStream()); } else if (encoding != null && encoding.equalsIgnoreCase("deflate")) { inStr = new InflaterInputStream(conn.getInputStream(), new Inflater(true)); } else { inStr = conn.getInputStream(); } int ptr = 0; InputStreamReader inStrReader = new InputStreamReader(inStr, Charset.forName("GB2312")); while ((ptr = inStrReader.read()) != -1) { buffer.append((char) ptr); } inStrReader.close(); conn.disconnect(); inStr.close(); } catch (Exception e) { e.printStackTrace(); } return buffer.toString(); }
From source file:com.sungtech.goodTeacher.action.TeacherInfoAction.java
public static String httpUrlRequest(String requestURL, String json) { URL url;// www. j a v a 2 s. c o m String response = ""; HttpURLConnection connection = null; InputStream is = null; try { url = new URL(requestURL); connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.getOutputStream().write(json.getBytes()); connection.getOutputStream().flush(); connection.getOutputStream().close(); int code = connection.getResponseCode(); System.out.println("code" + code); } catch (Exception e) { e.printStackTrace(); } finally { connection.disconnect(); } return response; }