List of usage examples for java.net HttpURLConnection getInputStream
public InputStream getInputStream() throws IOException
From source file:Main.java
public static String getHtml(String getUrl, int outtime, String charsetName) { String html = ""; URL url;//from ww w .j av a2 s . c om try { url = new URL(getUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; InfoPath.1; CIBA)"); // connection.setRequestProperty("Connection", "Keep-Alive"); // connection.setRequestProperty("Cache-Control", "no-cache"); connection.setConnectTimeout(outtime); connection.connect(); InputStream inStrm = connection.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(inStrm, charsetName)); String temp = ""; while ((temp = br.readLine()) != null) { html = html + (temp + '\n'); } try { br.close(); } catch (Exception e) { // TODO: handle exception } try { connection.disconnect(); } catch (Exception e) { // TODO: handle exception } } catch (Exception e) { e.printStackTrace(); } return html; }
From source file:Yak_Hax.Yak_Hax_Mimerme.PostRequest.java
public static String PostBodyRequest(String URL, String JSONRaw, String UserAgent) throws IOException { String type = "application/json"; URL u = new URL(URL); HttpURLConnection conn = (HttpURLConnection) u.openConnection(); conn.setDoOutput(true);// w w w. j a va 2 s.com conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", type); conn.setRequestProperty("User-Agent", UserAgent); OutputStream os = conn.getOutputStream(); os.write(JSONRaw.getBytes()); os.flush(); os.close(); String response = null; DataInputStream input = new DataInputStream(conn.getInputStream()); while (null != ((response = input.readLine()))) { input.close(); return response; } return null; }
From source file:common.net.volley.toolbox.HurlStack.java
/** * Initializes an {@link org.apache.http.HttpEntity} from the given {@link java.net.HttpURLConnection}. * @param connection/*from w w w . j a v a 2 s. c o m*/ * @return an HttpEntity populated with data from <code>connection</code>. */ private static HttpEntity entityFromConnection(HttpURLConnection connection) throws IOException { BasicHttpEntity entity = new BasicHttpEntity(); ByteArrayOutputStream out = new ByteArrayOutputStream(); InputStream rawStream = null; try { rawStream = connection.getInputStream(); rawStream = stethoManager.interpretResponseStream(rawStream); InputStream decompressedStream = applyDecompressionIfApplicable(connection, rawStream); if (decompressedStream != null) { copy(decompressedStream, out, new byte[1024]); } entity.setContent(new ByteArrayInputStream(out.toByteArray())); } catch (IOException ioe) { rawStream = connection.getErrorStream(); entity.setContent(rawStream); } finally { // if(rawStream != null) { // rawStream.close(); // } } entity.setContentLength(connection.getContentLength()); entity.setContentEncoding(connection.getContentEncoding()); entity.setContentType(connection.getContentType()); return entity; }
From source file:com.versobit.weatherdoge.WeatherUtil.java
private static WeatherResult getWeatherFromOWM(double latitude, double longitude, String location) { try {/*from w ww .j av a 2s .c o m*/ String query; if (latitude == Double.MIN_VALUE && longitude == Double.MIN_VALUE) { if (location == null) { return new WeatherResult(null, WeatherResult.ERROR_THROWABLE, "No valid location parameters.", new IllegalArgumentException()); } query = "q=" + URLEncoder.encode(location, "UTF-8"); } else { query = "lat=" + URLEncoder.encode(String.valueOf(latitude), "UTF-8") + "&lon=" + URLEncoder.encode(String.valueOf(longitude), "UTF-8"); } query += "&APPID=" + URLEncoder.encode(BuildConfig.OWM_APPID, "UTF-8"); URL url = new URL("http://api.openweathermap.org/data/2.5/weather?" + query); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); try { JSONObject response = new JSONObject(IOUtils.toString(connection.getInputStream())); if (response.getInt("cod") != HttpURLConnection.HTTP_OK) { // OWM has HTTP error codes that are passed through an API field, the actual HTTP // error code is always 200... return new WeatherResult(null, WeatherResult.ERROR_API, response.getString("cod") + ": " + response.getString("message"), null); } JSONObject weather = response.getJSONArray("weather").getJSONObject(0); JSONObject main = response.getJSONObject("main"); double temp = main.getDouble("temp") - 273.15d; String condition = WordUtils.capitalize(weather.getString("description").trim()); String image = weather.getString("icon"); if (location == null || location.isEmpty()) { location = response.getString("name"); } return new WeatherResult(new WeatherData(temp, condition, image, latitude, longitude, location, new Date(), Source.OPEN_WEATHER_MAP), WeatherResult.ERROR_NONE, null, null); } finally { connection.disconnect(); } } catch (Exception ex) { return new WeatherResult(null, WeatherResult.ERROR_THROWABLE, ex.getMessage(), ex); } }
From source file:org.grameenfoundation.consulteca.utils.HttpHelpers.java
private static InputStream getInputStream(HttpURLConnection httpUrlConnection) throws IOException { InputStream inputStream = httpUrlConnection.getInputStream(); String contentEncoding = httpUrlConnection.getHeaderField("Content-Encoding"); if (contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip")) { inputStream = new GZIPInputStream(inputStream); }/*from w ww .j a v a 2 s . c o m*/ return inputStream; }
From source file:com.webarch.common.net.http.HttpService.java
/** * ?//from w w w .j av a2 s.com * * @param protocol ??http?https?ftp?file?jar * @param host ? * @param file * @return */ public static String getRemoteFile(String protocol, String host, String file) { String content = null; try { URL url = new URL(protocol, host, file); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); DataInputStream input = new DataInputStream(conn.getInputStream()); byte[] buffer = new byte[8192]; int count = input.read(buffer); if (count > 0) { byte[] strBuffer = new byte[count]; System.arraycopy(buffer, 0, strBuffer, 0, count); content = new String(strBuffer, "UTF-8"); } input.close(); } catch (Exception e) { e.printStackTrace(); } //? return StringSeriesTools.replaceAllMatch(content, "\\s*|\t|\r|\n", ""); }
From source file:dictinsight.utils.io.HttpUtils.java
public static String getDataFromOtherServer(String url) { String rec = null;/*from w ww. j av a 2 s. c o m*/ BufferedReader reader = null; HttpURLConnection connection = null; try { URL srcUrl = new URL(url); connection = (HttpURLConnection) srcUrl.openConnection(); connection.setConnectTimeout(1000 * 10); connection.connect(); reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); rec = reader.readLine(); } catch (Exception e) { System.out.println("get date from " + url + " error!"); e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (connection != null) connection.disconnect(); } return rec; }
From source file:com.google.api.GoogleAPI.java
/** * Forms an HTTP request, sends it using POST method and returns the result of the request as a JSONObject. * //ww w.ja v a 2s. c om * @param url The URL to query for a JSONObject. * @param parameters Additional POST parameters * @return The translated String. * @throws Exception on error. */ protected static JSONObject retrieveJSON(final URL url, final String parameters) throws Exception { try { final HttpURLConnection uc = (HttpURLConnection) url.openConnection(); uc.setRequestProperty("referer", referrer); uc.setRequestMethod("POST"); uc.setDoOutput(true); final PrintWriter pw = new PrintWriter(uc.getOutputStream()); pw.write(parameters); pw.flush(); try { final String result = inputStreamToString(uc.getInputStream()); return new JSONObject(result); } finally { // http://java.sun.com/j2se/1.5.0/docs/guide/net/http-keepalive.html uc.getInputStream().close(); if (uc.getErrorStream() != null) { uc.getErrorStream().close(); } pw.close(); } } catch (Exception ex) { throw new Exception("[google-api-translate-java] Error retrieving translation.", ex); } }
From source file:com.gallatinsystems.common.util.S3Util.java
public static String getObjectAcl(String bucketName, String objectKey, String awsAccessId, String awsSecretKey) throws IOException { final String date = getDate(); final URL url = new URL(String.format(S3_URL, bucketName, objectKey) + "?acl"); final String payload = String.format(GET_PAYLOAD_ACL, date, bucketName, objectKey); final String signature = MD5Util.generateHMAC(payload, awsSecretKey); InputStream in = null;//ww w . j a v a 2s . c om HttpURLConnection conn = null; try { conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("Date", date); conn.setRequestProperty("Authorization", "AWS " + awsAccessId + ":" + signature); in = new BufferedInputStream(conn.getInputStream()); return IOUtils.toString(in); } catch (Exception e) { log.log(Level.SEVERE, "Error getting ACL for : " + url.toString(), e); return null; } finally { if (conn != null) { conn.disconnect(); } IOUtils.closeQuietly(in); } }
From source file:Main.java
public static String deleteUrl(String url, Bundle params) throws MalformedURLException, IOException { System.setProperty("http.keepAlive", "false"); HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent") + " agent"); conn.setRequestMethod("DELETE"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setDoOutput(false);//from www . j a v a2 s . c o m conn.setDoInput(true); //conn.setRequestProperty("Connection", "Keep-Alive"); conn.connect(); 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; }