我应该在android端.java文件的URL中提供什么来连接我的django REST API和django的代码以通过POST获取数据?
答案 0 :(得分:0)
:
项目/项目/ setting.py:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'xxx',
'USER': 'your_account',
'PASSWORD': 'your_password',
'HOST': '127.0.0.1',
'POST': '3306',
}
}
项目/项目/ __ init.py
(你需要安装pymysql模型:pip install pymysql)
import pymysql
pymysql.install_as_MySQLdb()
项目/ you_app / view.py
class ProductViewSet(viewsets.ModelViewSet):
queryset = Product.objects.all()
serializer_class = ProductSerializer
permission_classes = (IsAuthenticated,)
def create(self, request, *args, **kwargs):
serializer = ProductSerializer(data=request.data)
if serializer.is_valid():
product= serializer.create(serializer.validated_data)
return Response(data='success', status=status.HTTP_200_OK)
@list_route(methods=['POST'])
def search(self, request):
key = request.data['key']
queryset = Product.objects.filter(name__icontains=key)
serializer = ProductSerializer(queryset, many=True)
return Response(serializer.data)
项目/项目/ url.py
from rest_framework import routers
from user.views import UserViewSet
router = routers.DefaultRouter()
router.register(r'product', ProductViewSet)
urlpatterns = [
url(r'^admin/', admin.site.urls),
]
urlpatterns += router.urls
在Android Okhttp3演示中:
RequestBody requestBody = new FormBody.Builder()
.add("key", ProductName)
.build();
Request request = new Request.Builder()
.post(requestBody)
.url(Constants.ProductSearch)
.build();
HttpClientUtil.getClient().newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {}
@Override
public void onResponse(Call call, final Response response) throws IOException {
final String data = response.body().string();
Log.e("Http",data);
}
});