网络——使用HTTP 协议访问网络


发送HTTP 请求的方式:HttpURLConnection HttpClient

HTTP 请求所使用的方法:GET POST。GET 表示希望从服务器那里获取数据,POST 表示希望提交数据给服务器。

使用HttpURLConnection

1. new 出一个URL 对象,并传入目标的网络地址;

URL url = new URL("https://www.baidu.com"); //此处的"/"必须是两个

2. 调用openConnection()方法,获取HttpURLConnection对象;

HttpURLConnection connection = (HttpURLConnection) url.openConnection();

3. 设置HTTP 请求所使用的方法等属性;

connection.setRequestMethod("GET");

4. 调用getInputStream()方法获取到服务器返回的输入流;

InputStream in = connection.getInputStream();

5. 读取输入流;

InputStream in = connection.getInputStream();

6. 调用disconnect()方法将这个HTTP 连接关闭; 

connection.disconnect();


例子:使用HttpURLConnection获取网页的html源代码

布局:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.a.MainActivity">

    <Button
        android:id="@+id/btn_send"
        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/tv"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </ScrollView>
</LinearLayout>

MainActivity.java

第一种方式:

public class MainActivity extends AppCompatActivity {
    Button btnSend;
    TextView textView;
    private int SHOW_RESPONSE = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnSend = (Button) findViewById(R.id.btn_send);
        textView = (TextView) findViewById(R.id.tv);
        btnSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendRequestWithHttpURLConnection();
                btnSend.setVisibility(View.GONE);    //点击之后,移除Button
            }
        });
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == SHOW_RESPONSE) {
                String response = (String) msg.obj;
                textView.setText(response); //对UI进行操作,将结果显示在界面上
            }
        }
    };

    private void sendRequestWithHttpURLConnection() {
        new Thread(new Runnable() { //开启子线程发起网络请求
            @Override
            public void run() {
                HttpURLConnection connection = null;
                try {
                    URL url = new URL("http://www.qq.com"); //此处必须是2个"/"
                    connection = (HttpURLConnection) url.openConnection();  //获取HttpURLConnection实例
                    connection.setRequestMethod("GET");   //设置HTTP请求所用的方法 GET为从服务器获取数据,POST为提交数据到服务器
                    connection.setConnectTimeout(8000);   //设置连接超时的毫秒数
                    connection.setReadTimeout(8000);      //设置读取超时的毫秒数
                    InputStream inputStream = connection.getInputStream();   //获取输入流
                    InputStreamReader isr = new InputStreamReader(inputStream);  //读取输入流
                    BufferedReader reader = new BufferedReader(isr);    //使用BufferedReader读取返回的流
                    StringBuilder responseStringBuilder = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        responseStringBuilder.append(line);
                    }
                    Message message = new Message();    //将读取的流的结果存放到Message对象,使用Handler发送,因为子线程无法操作UI
                    message.what = SHOW_RESPONSE;
                    message.obj = responseStringBuilder.toString(); //将服务器返回的结果放到Message
                    handler.sendMessage(message);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (connection != null) {
                        connection.disconnect(); //关闭HTTP连接
                    }
                }
            }
        }).start();
    }
}


第二种方式(比第一种简单):

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    Button btn;
    TextView tv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn = (Button) findViewById(R.id.btn);
        tv = (TextView) findViewById(R.id.tv);
        btn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        new Thread(new Runnable() { //网络请求在子线程
            @Override
            public void run() {
                try {
                    URL url = new URL("http://www.qq.com");
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    InputStream is = connection.getInputStream();
                    //字节流
                    int len;
                    byte[] buf = new byte[1024];
                    final StringBuffer sb = new StringBuffer();
                    while ((len = is.read(buf)) != -1) {
                        sb.append(new String(buf, 0, len));
                    }
                    runOnUiThread(new Runnable() {    //在子线程中嵌入主线程,以更新UI
                        @Override
                        public void run() {
                            tv.setText(sb.toString());
                            btn.setVisibility(View.GONE);
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}

第三种方式(异步任务):

 

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    TextView tv;
    Button btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn = (Button) findViewById(R.id.btn);
        tv = (TextView) findViewById(R.id.tv);
        btn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        new MyAsyncTask().execute("http://www.qq.com");
    }

    private class MyAsyncTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... params) {
            try {
                URL url = new URL(params[0]);//?? 
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setDoOutput(true);
                InputStream is = url.openStream();
                ByteArrayOutputStream os = new ByteArrayOutputStream();
                int len; //字节流 
                byte[] buf = new byte[1024];
                while ((len = is.read(buf)) != -1) {
                    os.write(buf, 0, len);
                }
                String result = new String(os.toByteArray(), "utf-8");
                return result;
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            tv.setText(s);
        }
    }
}

若要提交数据给服务器:将HTTP 请求的方法改成POST,并在获取输入流之前把要提交的数据写出即可每条数据都以键值对的形式存在,数据与数据之间用 & 符号隔开例如说向服务器提交用户名和密码:

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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值