我的笔记本电脑上安装了 Django 版本,我想将 API 连接到我的 Android 应用程序。
我也创建了一个虚拟环境。
我无法连接到我的 Django API,因此请帮助我了解如何连接到 API。提前致谢。
我在互联网上冲浪,但无法得到任何输出。我是第一次在这里发布问题,对于所犯的任何错误表示歉意。
我想将 Django API 连接到我的项目。我希望在移动应用程序中以 json 形式查看信息。
当我连接在 android studio 中制作的 Django API 应用程序时,它显示一个错误,我在上面附加了一个文件。
我正在附加我的 Android 文件。
我使用了一个改造库。我想将 API 连接到我的应用程序。
MainActivity.java
ListView listView;
GridView gridView;
public String cap;
public String cap1;
String[] pid;
String[] ptitle;
String[] pdes;
String[] dt;
String[] lk;
TextView name,descrip;
int capnum;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Retrofit retrofit = new Retrofit.Builder().baseUrl(djangoApi.BASE_URL).addConverterFactory(GsonConverterFactory.create()).build();
djangoApi api = retrofit.create(djangoApi.class);
name= findViewById(R.id.text);
descrip=findViewById(R.id.image);
Call<List<PostTable>> call = api.gettabledata();
call.enqueue(new Callback<List<PostTable>>() {
@Override
public void onResponse(Call<List<PostTable>> call, Response<List<PostTable>> response) {
List<PostTable> pt = response.body();
assert pt != null;
String[] pid = new String[pt.size()];
String[] ptitle = new String[pt.size()];
String[] pdes = new String[pt.size()];
String[] pdt = new String[pt.size()];
String[] plk = new String[pt.size()];
for (int i = 0; i < pt.size(); i++) {
pid[i] = pt.get(i).getid();
ptitle[i] = pt.get(i).gettitle();
pdes[i] = pt.get(i).getdescription();
pdt[i] = pt.get(i).getdatetime();
plk[i] = pt.get(i).getlikes();
}
for (int i = 0; i < pt.size(); i++) {
if (ptitle[i].equalsIgnoreCase("drhsrh")) {
capnum = i;
cap = pdes[capnum];
cap1=ptitle[capnum];
}
}
name.setText(cap1);
descrip.setText(cap);
//Glide.with(getApplicationContext()).load(cap).into(imageView);
//name.setText(cap1);
}
@Override
public void onFailure(Call<List<PostTable>> call, Throwable t) {
Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
这是接口(interface)类的代码
interface djangoApi {
String BASE_URL="http://127.0.0.1:8000/";
@GET("post_table/?format=json")
Call<List<PostTable>> gettabledata();
最佳答案
从 Android 9(API 级别 28)开始,默认禁用明文支持。
请检查此文档。
https://developer.android.com/training/articles/security-config#CleartextTrafficPermitted
如果您想在本地进行测试,请在 AndroidManifest.xml 的应用程序标记中添加此 android:usesCleartextTraffic="true"。
<application
android:name=".App"
android:allowBackup="false"
android:fullBackupContent="false"
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">
关于java - 当我将 django API 连接到 android studio 中的应用程序时,它显示错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59960124/