Android 之 HttpURLConnection 访问网络

HttpURLConnection类位于 java.net 包中,用于发送 Http 请求和获取 Http 响应。由于该类是抽象类,不能直接实例化对象,需要使用 URL 的 openConnection() 方法来获得。

通过openConnection() 方法创建的HttpURLConnection对象,并没有真正的执行连接操作,只是创建了一个新的实例,在进行连接前,还可以设置一些属性,例如,连接超时的时间和请求方式等。

创建HttpURLConnection对象后,就可以使用该对象发送 http 请求了。

1.发送 GET 请求

使用HttpURLConnection对象发送请求时,默认的就是 GET 请求。传递的参数通过“?参数名=参数值”进行传递,多个参数用英文状态下的逗号隔开。

举例说明:

<1>修改 main.xml 布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.zjqian.myapplication.MainActivity"
    android:orientation="vertical"
    android:gravity="center_horizontal">

    <EditText
        android:id="@+id/content"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="button"/>

    <ScrollView
        android:id="@+id/scrollView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1">

        <LinearLayout
            android:id="@+id/linearLayout1"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <TextView
                android:id="@+id/result"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"/>

        </LinearLayout>

    </ScrollView>


</LinearLayout>

<2>创建成员变量

在 Activity 文件中:

 private EditText content;
    private Button button;
    private Handler handler;
    private String result = "";
    private TextView resultTV;

<3>编写一个请求方法

编写一个无返回值得方法,用于建立一个 Http 连接,并将输入的内容发送到服务器,在获取服务器的处理结果。

private void send() {

        String target = "";
        target = "http://192.168.1.66:8081/blog/index.jsp?content="+base64(content.getText().toString().trim());
        URL url;
        try {

            url = new URL(target);
            //创建一个 Http 连接
            HttpURLConnection connection = (HttpURLConnection)url.openConnection();

            //获得读取的内容
            InputStreamReader inputStreamReader = new InputStreamReader(connection.getInputStream());

            //获取输入流对象
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

            String inputLine = null;

            while ((inputLine = bufferedReader.readLine()) != null ){

                result += inputLine+"\n";
            }
            //关闭字符输入流对象
            inputStreamReader.close();
            //断开连接
            connection.disconnect();

        }catch (MalformedURLException e){

            e.printStackTrace();
        }catch (IOException e){

            e.printStackTrace();
        }
    }

//在进行 GET方法传递中文的参数时,会产生乱码,可以进行 Base64编码解决乱码问题
    private String base64(String content) {
        try {

            content = Base64.encodeToString(content.getBytes("utf-8"),Base64.DEFAULT);
            content = URLEncoder.encode(content);

        }catch (UnsupportedEncodingException e){

            e.printStackTrace();
        }
        return content;
    }

<4>发送请求

 @Override
    public void onClick(View v) {
        if (content.getText().toString().trim().equals("")){

            Toast.makeText(MainActivity.this,"请输入内容",Toast.LENGTH_LONG).show();
            return;
        }

        new Thread(new Runnable() {
            @Override
            public void run() {

                send();//调用请求方法发送请求到服务器,并读取
                Message message = handler.obtainMessage();
                handler.sendMessage(message);//发送消息

            }
        }).start();//开启线程
    }

<5>刷新 UI

创建一个 Handler 对象,在重写的 handleMessage() 方法中,将获取的数据赋给控件。

handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {

                if (result != null){

                    resultTV.setText(result);
                    content.setText("");
                }
                super.handleMessage(msg);
            }
        };

<6>设置权限

由于需要访问网络,所以需要在 AndroidManifest.xml文件中指定允许访问网络的权限。

至此,一个完整的 HttpURLConnection 的 GET 请求就完成了。

2.发送 POST 请求

这里只写一些请求部分,其他的和 GET 都一样。

private void send() {


        String target = "http://192.168.1.66:8081/blog/dealPost.jsp";
        URL url;
        try {

            url = new URL(target);
            HttpURLConnection connection = (HttpURLConnection)url.openConnection();

            //设置请求方法
            connection.setRequestMethod("POST");
            //向连接中写入数据
            connection.setDoInput(true);
            //从连接中读取数据
            connection.setDoOutput(true);
            //禁止缓存
            connection.setUseCaches(false);
            //自动执行 http 重定向
            connection.setInstanceFollowRedirects(true);
            //设置内容类型
            connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");

            //获取输出流
            DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());

            //请求参数
            String param = "nickname="
                    +URLEncoder.encode("昵称","utf-8")
                    +"&content="
                    +URLEncoder.encode("内容","utf-8");
            //将要传递的数据写入数据输出流
            outputStream.writeBytes(param);
            //输出缓存
            outputStream.flush();
            //关闭数据输出流
            outputStream.close();

            //判断是否响应成功
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK){

                //获取读取的内容
                InputStreamReader in = new InputStreamReader(connection.getInputStream());
                //获取输入流对象
                BufferedReader bufferedReader = new BufferedReader(in);

                String inputLine = null;
                while ((inputLine = bufferedReader.readLine()) != null){

                    result = inputLine+"\n";
                }

                //关闭字符输入流
                in.close();

            }

            //断开连接
            connection.disconnect();


        }catch (MalformedURLException e){

            e.printStackTrace();
        }catch (IOException e){

            e.printStackTrace();
        }
    }

在设置要提交的数据时,如果包含多个参数,则各个参数之间使用“&”连接。

这就是 HttpURLConnection 的 GET 和 POST 请求。

如有不对之处,还请多多指教!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值