使用HttpURLConnection进行网络访问

阅读:https://blog.csdn.net/wei_zhi/article/details/52997246
https://blog.csdn.net/rocoloco/article/details/78057384

一、概述

在Android 上发送HTTP 请求的方式一般有两种:HttpURLConnection 和HttpClient。因为在Android 5.0之后,HttpClient被HttpURLConnecetion替代,后来在Android 6.0完全被舍弃,所以本文重点讲解HttpURLConnecetion。

二、HttpURLConnecetion的使用步骤

(1)首先需要获取到HttpURLConnection 的实例,一般只需new 出一个URL 对象,并传入目标的网络地址,然后调用一下openConnection()方法即可,如下所示:

URL url = new URL("http://www.baidu.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
 
 
  • 1
  • 2

(2)得到了HttpURLConnection 的实例之后,我们可以设置一下HTTP 请求所使用的方法。常用的方法主要有两个,GET 和POST。GET 表示希望从服务器那里获取数据,而POST 则表示希望提交数据给服务器。写法如下:

connection.setRequestMethod("GET");
 
 
  • 1

(3)接下来就可以进行一些自由的定制了,比如设置连接超时、读取超时的毫秒数,以及服务器希望得到的一些消息头等。这部分内容根据自己的实际情况进行编写,示例写法如下:

 connection.setRequestMethod("GET");//设置HTTP请求方式为GET
 connection.setConnectTimeout(8000);//设置连接超时的毫秒数
 connection.setReadTimeout(8000);//设置读取超时的毫秒数

(4)之后再调用getInputStream()方法就可以获取到服务器返回的输入流了,剩下的任务就是对输入流进行读取,如下所示:

InputStream in = connection.getInputStream();
//下面对获取到的输入流进行读取
BufferedReader reader=new BufferedReader(new InputStreamReader(in));
StringBuilder response=new StringBuilder();
String line;
while ((line=reader.readLine())!=null){
         response.append(line);
}

(5)最后可以调用disconnect()方法将这个HTTP 连接关闭掉,如下所示:

connection.disconnect();
 
 
  • 1

注:
1.不要忘记加权限

<uses-permission android:name="android.permission.INTERNET"/>

2.post请求

发送post请求时,只需要将HTTP请求的方式改成POST,并在获取输入流之前把要提交的数据写出即可。
注意每条数据都要以键值对的形式存在,数据与数据之间用“&”符号隔开,比如向服务器提交用户名和密码

connection.setRequestMethod("POST");
DataOutputStream out=new DataOutputStream(connection.getOutputStream());
out.writeBytes("username=admin&password=123456");

三、HttpURLConnecetion的使用范例

点击一个按钮之后在TextView中显示请求百度返回的数据

编写xml代码:

<?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.lk.networktest.MainActivity">
 
    <Button
        android:id="@+id/send_request"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Send Request" />
 
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">
 
        <TextView
            android:id="@+id/response_text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </ScrollView>
</LinearLayout>

编写activity中的代码:
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
 TextView responseText;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button sendRequest= (Button) findViewById(R.id.send_request);
        responseText= (TextView) findViewById(R.id.response_text);
        sendRequest.setOnClickListener(this);
    }
 
    @Override
    public void onClick(View v) {
        if(v.getId()==R.id.send_request){
            sendRequestWithHttpURLConnection();
        }
 
    }
 
    private void sendRequestWithHttpURLConnection() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection=null;
                BufferedReader reader=null;
                try {
                    URL url=new URL("https://www.baidu.com");
                    connection= (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");//设置HTTP请求方式为GET
                    connection.setConnectTimeout(8000);//设置连接超时的毫秒数
                    connection.setReadTimeout(8000);//设置读取超时的毫秒数
                    InputStream in=connection.getInputStream();
                    //下面对获取到的输入流进行读取
                    reader=new BufferedReader(new InputStreamReader(in));
 
                    StringBuilder response=new StringBuilder();
                    String line;
                    while ((line=reader.readLine())!=null){
                        response.append(line);
                    }
                    showResponse(response.toString());
 
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }finally {
                    if(reader!=null){
                        try {
                            reader.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (connection!=null){
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }
 
    private void showResponse(final String s) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //在这里进行UI操作,将结果显示到界面上
                responseText.setText(s);
 
            }
        });
    }
}

3.声明权限
<uses-permission android:name="android.permission.INTERNET"/>


post示例:
package com.qf.demo5;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * post请求方式,返回响应信息
 * @author Administrator
 *
 */
public class Test3 {

    public static void main(String[] args) {
        BufferedReader reader = null;
        try {
            URL url = new URL("http://localhost:8080/Day28_03/LoginServlet");
            // 2
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // 3 
            connection.setRequestMethod("POST");
            // 是否允许修改 地址 (是否允许在地址中追加 参数)
            connection.setDoOutput(true);// false  默认不允许修改
            connection.setDoInput(true);// true  默认就是允许读取的 (修改以后要读取)

            // 4 修改  追加 参数
            OutputStream os = connection.getOutputStream();// 从这个流  向  conntion中取添加参数
            os.write("useName=zhangasan&pwd=123".getBytes());
            os.flush();

            // 5 连接(可以写 可以不写  不写 默认帮助执行  连接操作)
            //connection.connect();

            // 6 读取响应内容
            if(connection.getResponseCode()==200){
                reader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"utf-8"));
                String result = reader.readLine();
                System.out.println("服务器回复的数据="+result);
            }

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            if(reader!=null){
                try {
                    reader.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
}
  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值