在没有任何其他库的情况下执行GET请求的最佳方式

时间:2017-05-20 09:36:21

标签: android apache http lib

看起来Apache客户端已被弃用,是否有其他方法可以在不安装花哨库的情况下执行http请求?

我应该使用Apache客户端吗?如何导入它,我的Android Studio不想导入HttpClient,HttpGet,......

由于

2 个答案:

答案 0 :(得分:1)

您是否尝试过HttpURlConnection?

这是一个示例代码,用于从服务器获取图像并将其显示在图像视图中:

private class SendHttpRequestTask extends AsyncTask<String, Void, Bitmap> {
            @Override
            protected Bitmap doInBackground(String... params) {
                try {
                    URL url = new URL("http://xxx.xxx.xxx/image.jpg");
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setDoInput(true);
                    connection.connect();
                    InputStream input = connection.getInputStream();
                    Bitmap myBitmap = BitmapFactory.decodeStream(input);
                    return myBitmap;
                }catch (Exception e){
                    Log.d(TAG,e.getMessage());
                }
                return null;
            }

            @Override
            protected void onPostExecute(Bitmap result) {
                    ImageView imageView = (ImageView) findViewById(ID OF YOUR IMAGE VIEW);
                    imageView.setImageBitmap(result);
            }
    }

我希望我能提供帮助

答案 1 :(得分:0)

试试这个。

URL url = new URL("your URL in String");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.connect();
int httpResponse = conn.getResponseCode();