Search in sources :

Example 81 with HttpURLConnection

use of java.net.HttpURLConnection in project actor-platform by actorapp.

the class PlaceFetchingTask method doInBackground.

@Override
protected Object doInBackground(Void... voids) {
    ArrayList<MapItem> resultList = null;
    HttpURLConnection conn = null;
    StringBuilder jsonResults = new StringBuilder();
    try {
        StringBuilder sb = new StringBuilder(PLACES_API_BASE + METHOD_NAME + OUT_JSON);
        sb.append("?key=" + API_KEY);
        // sb.append("&radius="+radius);
        sb.append("&rankby=distance");
        sb.append("&location=" + latitude + "," + longitude);
        if (query != null)
            sb.append("&keyword=" + URLEncoder.encode(query, "utf8"));
        else
            sb.append("&types=cafe");
        URL url = new URL(sb.toString());
        conn = (HttpURLConnection) url.openConnection();
        InputStreamReader 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);
        }
        Log.i(LOG_TAG, "Response: " + jsonResults.toString());
    } catch (MalformedURLException e) {
        if (conn != null) {
            conn.disconnect();
        }
        Log.e(LOG_TAG, "Error processing Places API URL", e);
        return e;
    } catch (IOException e) {
        if (conn != null) {
            conn.disconnect();
        }
        Log.e(LOG_TAG, "Error connecting to Places API", e);
        return e;
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
    try {
        // Create a JSON object hierarchy from the results
        JSONObject jsonResult = new JSONObject(jsonResults.toString());
        JSONArray jsonResultItems = jsonResult.getJSONArray("results");
        // Extract the Place descriptions from the results
        resultList = new ArrayList<MapItem>(jsonResultItems.length());
        for (int i = 0; i < jsonResultItems.length(); i++) {
            // todo json parser
            final JSONObject jsonResultItem = jsonResultItems.getJSONObject(i);
            MapItem item = new MapItem() {

                {
                    id = jsonResultItem.optString("id", null);
                    name = jsonResultItem.optString("name", null);
                    vicinity = jsonResultItem.optString("vicinity", null);
                    icon = jsonResultItem.optString("icon", null);
                    if (jsonResultItem.has("geometry")) {
                        geometry = new Geometry();
                        geometry.location = new Location() {

                            {
                                lat = jsonResultItem.optJSONObject("geometry").optJSONObject("location").optDouble("lat", 0.0);
                                lng = jsonResultItem.optJSONObject("geometry").optJSONObject("location").optDouble("lng", 0.0);
                            }
                        };
                    }
                }
            };
            resultList.add(item);
        }
    } catch (JSONException e) {
        Log.e(LOG_TAG, "Cannot process JSON results", e);
        return e;
    }
    return resultList;
}
Also used : MalformedURLException(java.net.MalformedURLException) InputStreamReader(java.io.InputStreamReader) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) IOException(java.io.IOException) URL(java.net.URL) HttpURLConnection(java.net.HttpURLConnection) JSONObject(org.json.JSONObject) MapItem(im.actor.map.MapItem)

Example 82 with HttpURLConnection

use of java.net.HttpURLConnection in project GT by Tencent.

the class GTDemoActivity method getInputStream.

private InputStream getInputStream(String imagePath) {
    URL url;
    try {
        url = new URL(imagePath);
        HttpURLConnection conn;
        // 对每个图片的连接速度进行性能统计
        conn = (HttpURLConnection) url.openConnection();
        // 使用输入参数"超时时间"确定是连接的超时时间
        con_timeOut = GT.getInPara(连接超时, 60000);
        conn.setConnectTimeout(con_timeOut);
        read_timeOut = GT.getInPara(读超时, 60000);
        conn.setReadTimeout(read_timeOut);
        // 使用输入参数"维持长链接"确定是长连接还是短连接
        flag_keepAliave = GT.getInPara(KeepAlive, true);
        if (!flag_keepAliave) {
            conn.setRequestProperty("Connection", "close");
            System.setProperty("http.keepAlive", "false");
        }
        conn.setRequestMethod("GET");
        /*GT start*/
        GT.startTimeInThread(线程内统计, Http响应耗时);
        int resCode = -1;
        try {
            resCode = conn.getResponseCode();
        } catch (Exception e) {
            GT.logE(速度统计, "Http连接异常:" + e.getMessage());
        }
        GT.endTimeInThread(线程内统计, Http响应耗时);
        if (200 == resCode) {
            InputStream inputStream = conn.getInputStream();
            return inputStream;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
Also used : HttpURLConnection(java.net.HttpURLConnection) InputStream(java.io.InputStream) URL(java.net.URL) IOException(java.io.IOException)

Example 83 with HttpURLConnection

use of java.net.HttpURLConnection in project CoCoin by Nightonke.

the class AppUpdateManager method downloadApp.

private void downloadApp() {
    new Thread(new Runnable() {

        @Override
        public void run() {
            URL url = null;
            InputStream in = null;
            FileOutputStream out = null;
            HttpURLConnection conn = null;
            try {
                url = new URL(spec);
                conn = (HttpURLConnection) url.openConnection();
                conn.connect();
                long fileLength = conn.getContentLength();
                in = conn.getInputStream();
                File filePath = new File(FILE_PATH);
                if (!filePath.exists()) {
                    filePath.mkdir();
                }
                out = new FileOutputStream(new File(FILE_NAME));
                byte[] buffer = new byte[1024];
                int len = 0;
                long readedLength = 0l;
                while ((len = in.read(buffer)) != -1) {
                    // 用户点击“取消”按钮,下载中断
                    if (isCancel) {
                        break;
                    }
                    out.write(buffer, 0, len);
                    readedLength += len;
                    curProgress = (int) (((float) readedLength / fileLength) * 100);
                    handler.sendEmptyMessage(UPDARE_TOKEN);
                    if (readedLength >= fileLength) {
                        progressDialog.dismiss();
                        // 下载完毕,通知安装
                        handler.sendEmptyMessage(INSTALL_TOKEN);
                        break;
                    }
                }
                out.flush();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (out != null) {
                    try {
                        out.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (conn != null) {
                    conn.disconnect();
                }
            }
        }
    }).start();
}
Also used : HttpURLConnection(java.net.HttpURLConnection) InputStream(java.io.InputStream) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) File(java.io.File) URL(java.net.URL) IOException(java.io.IOException)

Example 84 with HttpURLConnection

use of java.net.HttpURLConnection in project android_frameworks_base by ParanoidAndroid.

the class BandwidthEnforcementTestService method testUrlConnection.

/**
     * Tests a normal http url connection.
     * @return true if it was able to connect, false otherwise.
     */
public static boolean testUrlConnection() {
    try {
        final HttpURLConnection conn = (HttpURLConnection) new URL("http://www.google.com/").openConnection();
        try {
            conn.connect();
            final String content = Streams.readFully(new InputStreamReader(conn.getInputStream()));
            if (content.contains("Google")) {
                return true;
            }
        } finally {
            conn.disconnect();
        }
    } catch (IOException e) {
        Log.d(TAG, "error: " + e);
    }
    return false;
}
Also used : HttpURLConnection(java.net.HttpURLConnection) InputStreamReader(java.io.InputStreamReader) IOException(java.io.IOException) URL(java.net.URL)

Example 85 with HttpURLConnection

use of java.net.HttpURLConnection in project sonarqube by SonarSource.

the class CoreTestDb method loadOrchestratorSettings.

private void loadOrchestratorSettings(Settings settings) {
    String url = settings.getString("orchestrator.configUrl");
    InputStream input = null;
    try {
        URI uri = new URI(url);
        if (url.startsWith("file:")) {
            File file = new File(uri);
            input = FileUtils.openInputStream(file);
        } else {
            HttpURLConnection connection = (HttpURLConnection) uri.toURL().openConnection();
            int responseCode = connection.getResponseCode();
            if (responseCode >= 400) {
                throw new IllegalStateException("Fail to request: " + uri + ". Status code=" + responseCode);
            }
            input = connection.getInputStream();
        }
        Properties props = new Properties();
        props.load(input);
        settings.addProperties(props);
        for (Map.Entry<String, String> entry : settings.getProperties().entrySet()) {
            String interpolatedValue = StrSubstitutor.replace(entry.getValue(), System.getenv(), "${", "}");
            settings.setProperty(entry.getKey(), interpolatedValue);
        }
    } catch (Exception e) {
        throw new IllegalStateException(e);
    } finally {
        IOUtils.closeQuietly(input);
    }
}
Also used : HttpURLConnection(java.net.HttpURLConnection) InputStream(java.io.InputStream) Properties(java.util.Properties) URI(java.net.URI) File(java.io.File) Map(java.util.Map) AssumptionViolatedException(org.junit.AssumptionViolatedException) SQLException(java.sql.SQLException)

Aggregations

HttpURLConnection (java.net.HttpURLConnection)3831 URL (java.net.URL)2447 IOException (java.io.IOException)1634 InputStream (java.io.InputStream)1082 InputStreamReader (java.io.InputStreamReader)692 Test (org.junit.Test)650 BufferedReader (java.io.BufferedReader)573 OutputStream (java.io.OutputStream)466 MalformedURLException (java.net.MalformedURLException)372 URLConnection (java.net.URLConnection)248 HashMap (java.util.HashMap)216 OutputStreamWriter (java.io.OutputStreamWriter)208 Map (java.util.Map)199 Gson (com.google.gson.Gson)190 ByteArrayOutputStream (java.io.ByteArrayOutputStream)186 ArrayList (java.util.ArrayList)168 ExecutionException (java.util.concurrent.ExecutionException)161 File (java.io.File)159 AsyncTask (android.os.AsyncTask)158 HttpsURLConnection (javax.net.ssl.HttpsURLConnection)157