IP地址和端口号java
Java的网络编程由Java.net包中的类进行处理android
属于应用层的面向对象的协议,适用于分布式超媒体信息系统git
主要特色github
一、支持C/S模式编程
二、简单快速:只需传送请求方法和路径,请求方法经常使用的有:GET、HEAD、POST等数组
三、灵活:容许传输任意类型的数据对象,用Content-Type进行标记缓存
四、无链接:限制每次链接只处理一个请求安全
五、无状态:对事务处理没有记忆功能服务器
HTTP的URL的格式:网络
一、http://host[:port][/path]
二、http表示要经过HTTP协议来定位网络资源;host表示合法的Internet主机域名或者IP地址;port指定一个端口号,为空则使用默认端口80;path指定请求资源的URI
HTTP请求报文
HTTP相应报文
常见的状态码
https请求
一、HTTP通讯方式
HttpURLConnection
HttpClient
二、Socket通讯方式
Android p要求默认使用加密链接,禁止APP使用任何未加密的链接,所以须要使用TLS传输层安全协议,也就是Https
Android P使用HttpUrlConnection进行http的get请求会出现如下异常
解决方案
更改网络安全配置
在res新增xml目录,建立network_security_config.xml,开启http请求
<network-security-config>
<base-config cleartextTrafficPermitted="true"/>
</network-security-config>
复制代码
在AndroidMainfest.xml中的application标签增长如下属性
android:networkSecurityConfig="@xml/network"
复制代码
自定义X509TrustManager
自定义HostnameVerifier
一、统一资源定位符(URL)是对能够从互联网上获得的资源的位置和访问方法的一种简洁的表示,是互联网上标准资源的地址
二、互联网上的每一个文件都有一个惟一的URL
三、URL类提供了多个构造器用于建立URL对象
四、URL类提供多个方法访问URL对应的资源:
一、Android HTTP URL接口的基本操做包括:
二、HttpURLConnection的属性设置
connection.setConnectTimeout(15000);
connection.setReadTimeout(15000);
connection.setRequestMethod(method);
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) " +
"AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36");
connection.setDoInput(true);
if("POST".equals(method)){
connection.setDoOutput(true);
}
复制代码
三、HttpURLConnection访问HTTP资源的步骤:
(1)根据URL地址建立URL对象
(2)使用URL对象的openConnection()方法获取HttpURLConnection对象
(3)设置链接的属性,包括GET/POST请求方式
(4)输入、输出数据
(5)关闭输入、输出流
(6)在AndroidManifest配置文件中设置访问INTERNET的权限
四、GET方式
// 一、将url字符串转为URL对象
URL url = new URL(urlPath);
// 二、得到HttpURLConnection对象
connection = (HttpURLConnection) url.openConnection();
// 三、设置链接的相关参数
connection.setRequestMethod("GET");
connection.setUseCaches(false);
connection.setConnectTimeout(15000);
connection.setReadTimeout(15000);
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) " +
"AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36");
connection.setDoInput(true);
// 四、配置https的证书
if ("https".equalsIgnoreCase(url.getProtocol())) {
((HttpsURLConnection) connection).setSSLSocketFactory(
HttpsUtil.getSSLSocketFactory());
}
// 五、进行数据的读取,首先判断响应码是否为200
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
// 得到输入流
is = connection.getInputStream();
// 包装字节流为字符流
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
// 读取数据
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
// 六、关闭资源
is.close();
connection.disconnect();
// 七、返回结果
return response.toString();
复制代码
五、POST方式
String body=getParamString(params);
byte[] data=body.getBytes();
URL url=new URL(urlPath);
connection= (HttpsURLConnection) url.openConnection();
// 三、设置链接的相关参数
connection.setRequestMethod("POST");
connection.setUseCaches(false);
connection.setConnectTimeout(15000);
connection.setReadTimeout(15000);
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) " +
"AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36");
connection.setDoInput(true);
connection.setDoOutput(true);
// 四、配置https的证书
if ("https".equalsIgnoreCase(url.getProtocol())) {
((HttpsURLConnection) connection).setSSLSocketFactory(
HttpsUtil.getSSLSocketFactory());
}
connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length",String.valueOf(data.length));
OutputStream os=connection.getOutputStream();
os.write(data);
os.flush();
if(connection.getResponseCode()==HttpURLConnection.HTTP_OK){
is=connection.getInputStream();
BufferedReader reader=new BufferedReader(new InputStreamReader(is));
// 读取数据
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
// 六、关闭资源
is.close();
connection.disconnect();
// 七、返回结果
return response.toString();
}
复制代码
六、HttpURLConnection使用的注意事项
配置:
OKHttp是Android 2.3及其以上版本,Java要求JDK1.7以上
添加依赖:
implementation 'com.squareup.okhttp3:okhttp:4.2.1'
复制代码
添加权限:
<uses-permission android:name="android.permission.INTERNET"/>
复制代码
特色:
OkHttp开发基本思路
Get同步请求
Get异步请求
post异步请求
1.经过RequestBody构建请求数据
private void postForm(String url){
RequestBody formBody = new FormBody.Builder().add("city","南京").build();
Request request = new Request. Builder().url(url).post(formBody).build();
mClient.newCall(request).enqueue(new Callback(){
@Override
public void onResponse(Call call, Response response) throws IOException {
final String str = response .body().string();
Log.d(TAG, str);
runOnUiThread(new Runnable() {
@Override
public void run() {
textView. setText(str);
});
}
@Override
public void onFailure(Call call, IOException e) {
});
}
复制代码
图片加载框架Glide
添加依赖:
implementation 'com.github.bumptech.glide:glide:4.10.0'
annotationProcessor 'com. github.bumptech.glide:compiler:4.10.0'
//https图片处理
implementation "com.github.bumptech.glide:okhttp3-integration:4.10.0"
复制代码
添加网络权限:
<uses-permission android: name= "android. permi ssion . INTERNET" />
复制代码
使用:
Glide.with(this).load("http://goo.gl/gEgYUd").into(imageView);
复制代码
加载图片的通常方法:
Glide.with(Context context).load(String url).into(ImageView imageView);
复制代码
Glide加载https图片
建立支持https的OkHttpClient对象:
public static 0kHttpClient handleSSLHandshakeBy0kHttp() {
return new 0kHttpClient.Builder()
.connectTimeout(10,TimeUnit. SECONDS)
.writeTimeout(10,TimeUnit. SECONDS)
.readTimeout(10,TimeUnit . SECONDS)
//支持HTTPS请求,跳过证书验i证
.sslSocketFactory(getSSLSocketFactory(),(X509TrustManager) getTrustManager()[0])
.hostnameVerifier(new TrustAllHostnameVerifier())
.build();
}
复制代码
建立继承AppGlidModule类的自定义类,重写registerComponents( )方法:
@GlideModule
public class OkHttpGlideModule extends AppGlideModule {
@Override
public void registerComponents( @NonNull Context context,
@NonNull Glide glide,@NonNull Registry registry) {
OkHttpClient client = HttpsUtil.handl esSLHandshakeByokHttp();
registry.replace(GlideUrl.class,InputStream.class,
new 0kHttpUrlLoader.Factory(client));
}
}
复制代码