一、什么是Http请求
客户端连接上服务器后,向服务器请求某个web资源,称之为向服务器发送了一个http请求,一个完整的http请求包括 “一个请求行,若干个消息头,以及内容”。二、什么是HttpUrlConnection
HttpURLConnection是一种多用途、轻量极的HTTP客户端,使用它来进行HTTP操作可以适用于大多数的应用程序。虽然HttpURLConnection的API提供的比较简单,但是同时这也使得我们可以更加容易地去使用和扩展它。
三、如何使用HttpUrlConnection
首先需要获取到 HttpURLConnection的实例,一般只需 new出一个 URL对象,并传入目标的网络地址,然后调用一下 openConnection()方法即可:
//找水源--创建URL URL url = new URL("http://www.csdn.net/"); //开水闸--openConnection HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
四、使用HttpUrlConnection获取Http请求(以访问csdn网站为例,附代码)
package com.example.administrator.handlerdemo; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; public class Main3Activity extends AppCompatActivity { private Button getwebBtn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main3); bindID(); getwebBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new Thread(new Runnable() { @Override public void run() { getWebInfo(); } }); } }); } private void getWebInfo() { try { //找水源--创建URL URL url = new URL("http://www.csdn.net/"); //开水闸--openConnection 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("MAIN",stringBuffer.toString()); }catch (MalformedURLException e){ e.printStackTrace(); }catch (IOException e){ e.printStackTrace(); } } private void bindID() { getwebBtn=findViewById(R.id.getweb_btn); } }