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));
}
}
複製代碼