HttpUrlConnection

本文介绍了HTTP请求的基本概念及如何使用Java标准类HttpUrlConnection发送GET和POST请求。通过实例演示了如何利用HttpUrlConnection获取网页内容及加载图片。

1.什么是Http请求?

客户端连接上服务器后,向服务器请求某个web资源,称之为向服务器发送了一个http请求,一个完整的http请求包括 “一个请求行,若干个消息头,以及内容”。

2.什么是HttpUrlConnection?

HttpUrlConnection:HttpUrlConnection是Java的标准指定网站发送GET请求、POST请求类,HttpUrlConnection继承URLConnection,可用于向指定网站发送GET请求、POST请求,HttpUrlConnection在使用上相对简单,并且已于扩展,推荐使用。

3.如何使用HttpUrlConnection?

前提:1.在Android中访问网络必须添加好权限;
    2.访问网络放在子线程中。
 <uses-permission android:name="android.permission.INTERNET" />
 //网络权限代码
  1. 创建URL对象
  2. 通过URL对象调用openConnection()方法获得HttpURLConnection对象
  3. HttpURLConnection对象设置其他链接属性
  4. HttpURLConnection对象调用getInputStream()方法向服务器发送http请求并获取到服务器返回的输入流
  5. 读取输入流,转换为String字符串

4.使用HttpUrlConnection获取Http请求(以访问CSD网站为例)

设置好Activity的布局文件,在里面建立一个Button
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.practice.UrlActivity">
    <Button
        android:id="@+id/bt1"
        android:layout_gravity="center"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="点击就送"
        />

</LinearLayout>
定义好按钮,绑定ID,设置好按钮的监听
  private Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_url);
        BlindID();

    }

    private void BlindID() {
        button=findViewById(R.id.bt1);
        button.setOnClickListener(this);
    }
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.bt1:
                break;
        }

    }
在点击事件中创建子线程,创建 getWebInfo方法
   new Thread(new Runnable() {
                    @Override
                    public void run() {
                        getWebInfo();
                    }
                }).start();
   在方法中使用HttpUrlConnection,创建URl获取网站源;
   创建开关——通过URL对象调用openConnection()方法获得HttpURLConnection对象;
   创建好传输数据流,使用BufferedReader获取数据。
   定义变量值,判断数据是否在传输,当不在传输是Close,使用Log.e打印获得的stringBuffer.toString()。
private void getWebInfo() {
        try {
            //创建URL——找到网站源
            URL url=new URL("https://hao.qq.com/?unc=Af31026&s=o400493_1");
            //创建开关——HttpURLConnection
            HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();
            //创建数据流——Inputstream
            InputStream inputStream=httpURLConnection.getInputStream();
            //创建存放库——InputStreamReader
            InputStreamReader reader=new InputStreamReader(inputStream,"UTF-8");
            //获取数据——BufferedReader
            BufferedReader bufferedReader=new BufferedReader(reader);
            //
            StringBuffer stringBuffer=new StringBuffer();
            String temp=null;

            while ((temp=bufferedReader.readLine())!=null){
                stringBuffer.append(temp);
            }
            bufferedReader.close();
            reader.close();
            inputStream.close();
            Log.e("wang ",stringBuffer.toString());
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

5.使用HttpUrlConnection加载图片

创建Activity,完成xml布局,用ImageView存放要加载的图片。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.practice.PicActivity">
    <Button
        android:id="@+id/btn1"
        android:layout_gravity="center"
        android:text="加载图片"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <ImageView
        android:id="@+id/image"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />


</LinearLayout>
绑定ID和设置按钮监听;
    Button showbutton;
    ImageView webimageView;
    private Bitmap bitmap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pic);
        BlindID();
    }

    private void BlindID() {
        showbutton=findViewById(R.id.btn1);
        webimageView=findViewById(R.id.image);
        showbutton.setOnClickListener(this);
    }
创建内部类来继承AsyncTask,实现重写方法;
在子线程这创建URL,获取图片地址,发送获取请求,创建输入流并将图片数据流通过BitmapFactory解码成图片;
完成后在主线程中设置图片。
 protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Integer doInBackground(String... strings) {
            try {
                //创建URL 获取图片地址
                URL url=new URL(strings[0]);
                //发送请求
                HttpURLConnection connection= (HttpURLConnection) url.openConnection();
                //创建输入流
                InputStream inputStream=connection.getInputStream();
                //将图片数据流通过BitmapFactory解码成图片
                bitmap= BitmapFactory.decodeStream(inputStream);
                //
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return 1;
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
        }

        @Override
        protected void onPostExecute(Integer integer) {
            super.onPostExecute(integer);
            switch (integer) {
                case 1:
                    //设置Image View为图片
                    webimageView.setImageBitmap(bitmap);
                    break;

                default:
                    break;
            }
        }
### Java 中 `HttpURLConnection` 的使用方法 #### 1. 基本概念 `HttpURLConnection` 是 Java 提供的一个用于执行 HTTP 请求的类。它允许开发者通过 URL 对象建立连接并发送 GET、POST 等类型的请求[^3]。 #### 2. 创建连接 要创建一个基于 `HttpURLConnection` 的 HTTP 连接,通常需要以下几个步骤: - 将目标地址封装成 `URL` 对象。 - 调用 `openConnection()` 方法获取到 `HttpURLConnection` 实例。 以下是基本代码示例: ```java import java.net.HttpURLConnection; import java.net.URL; public class HttpExample { public static void main(String[] args) throws Exception { String urlString = "http://example.com"; URL url = new URL(urlString); // 打开连接 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); // 设置请求方式 int responseCode = conn.getResponseCode(); // 获取响应码 System.out.println("Response Code: " + responseCode); conn.disconnect(); // 断开连接 } } ``` 上述代码展示了如何打开一个简单的 HTTP GET 请求,并打印服务器返回的状态码[^1]。 #### 3. 发送 POST 请求 如果需要向服务器提交数据,则可以设置请求头以及写入请求体的内容。下面是一个完整的 POST 请求示例: ```java import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; public class PostRequestExample { public static void main(String[] args) throws Exception { String urlString = "http://example.com/api"; URL url = new URL(urlString); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); // 启用输出流 conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); try(OutputStream os = conn.getOutputStream()) { // 写入 JSON 数据 byte[] input = "{\"key\":\"value\"}".getBytes("utf-8"); os.write(input, 0, input.length); } int responseCode = conn.getResponseCode(); System.out.println("Post Response Code : " + responseCode); conn.disconnect(); } } ``` 此代码片段演示了如何构建带有 JSON 数据的 POST 请求。 #### 4. 处理常见问题 ##### (1)超时设置 为了避免因网络延迟而导致程序卡住的情况,可以通过以下两个参数来设定读取和连接的时间限制: ```java conn.setConnectTimeout(5000); // 单位毫秒 conn.setReadTimeout(5000); ``` ##### (2)Android 版本兼容性 对于 Android 平台而言,在版本 2.3 及以上推荐优先选用 `HttpURLConnection` 替代已废弃的 `Apache HttpClient` 库[^2]。 ##### (3)重定向处理 默认情况下,`HttpURLConnection` 不会自动跟随 HTTP 重定向(状态码 3xx)。若希望支持该功能,需手动启用: ```java conn.setInstanceFollowRedirects(true); ``` #### 总结 综上所述,`HttpURLConnection` 是一种强大而灵活的方式来进行 HTTP 操作。尽管其配置过程可能稍显复杂,但它提供了足够的控制力去满足大多数应用场景的需求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值