用到的类:
下面是所有代码
public void LoadJson(View view) {
new Thread ( new Runnable ( ) {
@Override
public void run() {
try {
URL url = new URL ( "这里写http代码" );//api27以上要加其他权限,这里用的是27以下,而且是模拟机
//创建连接方法
HttpURLConnection connection= (HttpURLConnection) url.openConnection ();
//连接时间
connection.setConnectTimeout ( 10000 );
//请求方式
connection.setRequestMethod ( "GET" );
//接收语言
connection.setRequestProperty ( "Accept-Language","zh-CN,zh;q=0.9" );//可能错
//这里是设置压缩
// connection.setRequestProperty ( "Accept-Encoding","gzip,deflate" );
//接收范围:这里是全部
connection.setRequestProperty ( "Accept","*/*" );
//设置连接
connection.connect ();
//返回结果码
final int responseCode = connection.getResponseCode ( );
if (responseCode==200){
//得到头部
final Map <String, List <String>> headerFields = connection.getHeaderFields ( );
//map的遍历
final Set <Map.Entry <String, List <String>>> entries = headerFields.entrySet ( );
for (Map.Entry <String, List <String>> entry : entries) {
Log.d ( TAG,entry.getKey ()+"=="+entry.getValue ());
}
/*Object content = connection.getContent ( );
Log.d ( TAG,"CONTENT-->"+content );*/
final InputStream inputStream = connection.getInputStream ( );
BufferedReader bufferedReader=new BufferedReader ( new InputStreamReader ( inputStream ) );
final String line = bufferedReader.readLine ( );
Log.d ( TAG,"line-->"+line);
}
} catch (Exception e) {
e.printStackTrace ( );
}
}
} ).start ();
下面是xml代码
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="LoadJson"
android:text="loadJson"
android:textAllCaps="false"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
权限
<uses-permission android:name="android.permission.INTERNET"/>
这里是权限的Activity那里
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<action android:name="android.intent.action.VIEW"/>```
```xml
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme"
android:usesCleartextTraffic="true">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
//加了下面的
android:usesCleartextTraffic="true"