一、什么是HTTP请求
01、HTTP请求是客户端和服务器端之间,发送请求和返回应答的标准。
02、客户端发出一个HTTP请求后,就与服务器建立起了TCP连接,服务端接收到请求并进行处理后返回给客户端响应数据。
二、什么是HttpURLonnection
HttpURLConnection是java的标准指定网站发送GET请求、POST请求类,HttpURLConnection继承自URLConnection,可用于向指定网站发送GET请求、POST请求。
三、如何使用HttpURLConnection
01、创建URL对象
02、通过URL对象调用openConnection()方法获得HttpURLConnection对象
03、HttpURLConnection对象设置其他连接属性
05、读取输入流,转换成String字符串
注意点:
1、在Android中访问网络必须添加网络权限
在AndroidManifest中添加
<uses-permission android:name="android.permission.INTERNET"/>
2、在Android中访问网络必须放在子线程中执行
三、使用HttpURLConnection获取http请求(以访问csdn网站为例)
public class MainActivity extends AppCompatActivity {
private Button getwebBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bindID();
getwebBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new Thread(new Runnable() {
@Override
public void run() {
getWebInfo();
}
}).start();
}
});
}
private void bindID() {
getwebBtn=findViewById(R.id.main_btn);
}
private void getWebInfo() {
try {
URL url=new URL("http://www.csdn.net/");
HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();
InputStream inputStream=httpURLConnection.getInputStream();
InputStreamReader reader=new InputStreamReader(inputStream,"UTF-8");
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();
}
}
}