效果如下:
代码结构:
MainActivity.java
package com.example.newworktest;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.URL;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity {
TextView responseText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = findViewById(R.id.send_request);
responseText = findViewById(R.id.response_text);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(v.getId()==R.id.send_request){
sendRequestWithOkHttp();
}
}
});
}
private void sendRequestWithOkHttp() {
//开启新线程做耗时操作
new Thread(new Runnable() {
@Override
public void run() {
try {
OkHttpClient client = new OkHttpClient();//创建一个OkHttpClient实例
Request request = new Request.Builder()
.url("http://192.168.191.1:8080/1/get_data.json")//设置目标网络地址
.build();//创建一个Request对象
Response response = client.newCall(request).execute();//发送请求获取服务器返回对象
String responseData = response.body().string();
//解析JSON
parseJSONWithJSONObject(responseData);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
private void showResponse(final String response) {
runOnUiThread(new Runnable() {
@Override
public void run() {
//开线程进行UI操作,将结果显示到界面上
responseText.setText(response);
}
});
}
private void parseJSONWithJSONObject(String jsonData){
StringBuilder builder = new StringBuilder();
try{
JSONArray jsonArray=new JSONArray(jsonData);
for(int i=0;i<jsonArray.length();i++){
JSONObject jsonObject=jsonArray.getJSONObject(i);
String id=jsonObject.getString("id");
String name=jsonObject.getString("name");
String version=jsonObject.getString("version");
Log.d("MainActivity","id is "+id);
Log.d("MainActivity","name is "+name);
Log.d("MainActivity","version is "+version);
builder.append("id:" + id + "\n")
.append("name:" + name + "\n")
.append("version:" + version + "\n")
.append("-----------------------------\n");
}
showResponse(builder.toString());
}catch(Exception e){
e.printStackTrace();
}
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<Button
android:id="@+id/send_request"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="发送数据"/>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/response_text"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</ScrollView>
</LinearLayout>
AndroidManifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.newworktest">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
build.gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion 29
buildToolsVersion "29.0.2"
defaultConfig {
applicationId "com.example.newworktest"
minSdkVersion 14
targetSdkVersion 27
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
implementation 'com.squareup.okhttp3:okhttp:3.4.1'
}
在Apache的webapps中创建文件夹1,里面放一个get_data.json
[{"id":"5","version":"5.5","name":"Clash of Clans"},
{"id":"6","version":"7.0","name":"Boom Beach"},
{"id":"5","version":"3.5","name":"Clash Royale"}]
注意本地的ip可以用本地apache地址端口加后面的位置,192.168.191.1:8080/1/get_data.json
也可以用10.0.2.2,这个是安卓模拟器的接口
在我电脑上两个都可以
如果是用genymotion模拟器,则本机地址是http://10.0.3.2:8080/1/get_data.json
192.168.191.1:8080/1/get_data.json当然也可以
注意:127.0.0.1:8080/1/get_data.json表示的是本机地址,所以用浏览器是可以浏览的,但是在模拟器中是不行的。