【发布时间】:2021-05-10 01:56:24
【问题描述】:
我正在尝试从 Java 中获取一个 json,并在 Django 中开发一个 rest api。问题是它显然以 html 格式返回。从邮递员测试api正确返回json,所以我不知道这是Java还是Django中的错误。我测试了指向例如jsonplaceholder的java,它正确地返回了json,这就是为什么我倾向于问题出在Django。
这是我的 Django 视图:
from django.shortcuts import render
from .models import *
from rest_framework import viewsets
from .serializers import *
# Create your views here.
class EmpleadoViewSet(viewsets.ModelViewSet):
serializer_class = EmpleadoSerializer
queryset = Empleado.objects.all()
序列化器:
from rest_framework import serializers
from .models import *
class EmpleadoSerializer(serializers.ModelSerializer):
class Meta:
model = Empleado
fields = '__all__'
urls.py
from django.contrib import admin
from django.urls import path
from rest_framework.routers import DefaultRouter
from api_rest.views import *
router = DefaultRouter()
router.register(r'empleados',EmpleadoViewSet)
urlpatterns = router.urls
urlpatterns += [
path('admin/', admin.site.urls),
]
Java 代码:
public boolean chequearDatos(String usuario,String contrasenia){
boolean chequeo = false;
try {
InputStream is = conexion.getInputStream();
StringBuffer sb = new StringBuffer();
BufferedReader bf = new BufferedReader(new InputStreamReader(is));
String linea = bf.readLine();
while (linea!=null){
System.out.println(linea);
linea = bf.readLine();
}
}catch (IOException e){
e.printStackTrace();
}
return chequeo;
}
调用 http://localhost:8000/empleados/ 打印一个 html 文件,而不是指向例如 https://jsonplaceholder.typicode.com/photos 打印一个 json。
谢谢,对不起我的语言
编辑 1
在我的连接(java)中,我得到了这个:
public class ConexionAPI {
URL url;
HttpURLConnection conexion;
StringBuilder resultado;
public ConexionAPI(String cadenaConexion){
try {
url = new URL(cadenaConexion);
conexion = (HttpURLConnection) url.openConnection();
conexion.setRequestProperty("Accept","application/json");
//conexion.setRequestProperty("Accept: application/json");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public boolean conectarAPI(){
boolean conexionOK = false;
try {
conexion.setRequestMethod("GET");
if(conexion.getResponseCode()==200){
conexionOK = true;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return conexionOK;
}
这是打印的html的一部分:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta name="robots" content="NONE,NOARCHIVE" />
<title>Empleado List – Django REST framework</title>
<link rel="stylesheet" type="text/css" href="/static/rest_framework/css/bootstrap.min.css"/>
<link rel="stylesheet" type="text/css" href="/static/rest_framework/css/bootstrap-tweaks.css"/>
<link rel="stylesheet" type="text/css" href="/static/rest_framework/css/prettify.css"/>
<link rel="stylesheet" type="text/css" href="/static/rest_framework/css/default.css"/>
</head>
【问题讨论】:
-
解决了!谢谢大家。阅读这篇文章:stackoverflow.com/questions/51800895/…
标签: java json api rest django-rest-framework