1.什么是Http请求
Http请求是客户端和服务端之间发送请求和返回应答的标准(TCP)
客户端发出一个Http请求后就和服务器建立了TCP连接,服务端接受到请求并进行了处理后,返回给客户端相应数据。
2.什么是HTTPURLConnection
HTTPURLConnection是java的标准指定的网站发送GET请求,POST请求类,HTTPURLConnection继承自URLConnection可用与指定网站发送GET请求,post请求类,HTTPURLConnection在使用相对简单,并且易于推展,推荐使用。
3.如何使用HTTPURLConnection
创建URL对象
通过URL对象调用openConnection()方法获得HTTPURLConnection对象
HTTPURLConnection对象设置其他连接属性
HTTPURLConnection对象调用getinputstream()方法想服务器发送http请求并获取到服务器返回的输入流
获取输入流,转换成String字符串
注意:在Android中访问网络必须添加网络权限
在Android中访问网络必须放在子线程中(耗时操作)执行
使用HttpURLConnection获取请求
代码如下
`public class Main2Activity extends AppCompatActivity {
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
blid();
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new Thread(new Runnable() {
@Override
public void run() {
getweb();
}
}).start();
}
});
}
private void getweb() {
try {
URL url = new URL("https://www.csdn.net/");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
Log.e("MAIN",httpURLConnection.getResponseCode()+"**************************");
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();
}
}
private void blid() {
button=findViewById(R.id.web_btn);
}
}
`