重点
常用的GET、POST、PUT、DELETE四种请求方式
这里先只写GET的用法
GET
向服务器请求数据,获取资源,在大部分网络请求中,GET方法非常常见,并且它具有幂等性。
GET请求没有请求体,对于GET请求的请求参数在URL后面加上一个"?"的后面,参数以 key=value 的形式。参数与参数之间使用"&"进行连接。 GET请求是通过 URL 传输参数的,所以
GET请求可以传输的参数是有限的。
在进行网络通信时有着最关键的一步就是,获取权限
在AndroidManifest.xml中添加
<uses-permission android:name="android.permission.INTERNET" />
实现网络通信
HttpURLConnection简介
在JDK的 java.net 包中已经提供了访问HTTP协议的基本功能的类:HttpURLConnection。 HttpURLConnection是Java的标准类,它继承自URLConnection,可用于向指定网站发送GET请求、 POST请求。
使用HttpURLConnection
1.首先设置工具类封装使用GET的方式访问Http的代码
public static String doGet(String address){
String result = "";
try {
URL url=new URL(address);
HttpURLConnection connection= (HttpURLConnection) url.openConnection();
//是否发送数据
connection.setDoOutput(false);
//是否获取数据
connection.setDoInput(true);
//设置连接方式
connection.setRequestMethod("GET");
//是否允许重定向
connection.setInstanceFollowRedirects(true);
//设置网页最大反应时间
connection.setConnectTimeout(3*1000);
connection.connect();
int code=connection.getResponseCode();
if (code==200){
BufferedReader reader=new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
if ((line=reader.readLine())!=null){
result +=line;
}
reader.close();
}
connection.disconnect();
} catch (MalformedURLException e) {
e.