如何在Django RESTful API上使用Retrofit @POST解决404问题?

时间:2016-09-21 12:04:26

标签: java android django-rest-framework retrofit

我可以使用改造和REST api从数据库中获取数据,但在发布数据时遇到错误。发布使用postman但不通过retrofit。我无法找到错误。我尝试更改端点,即"休息"和"休息/"但仍然没有找到错误。

Django RESTful api中的Post的ApiView:view.py

def post(self,request):
    serializer =table_restSerializer(data=request.data)
    if serializer.is_valid():
        serializer.save()
        return Response({'results':serializer.data},status=201)
    return Response(serializer.errors, status=404)

urls.py

    urlpatterns = [
        url(r'^admin/', admin.site.urls),
        url(r'^rest',views.restSerializer.as_view())
    ]
urlpatterns = format_suffix_patterns(urlpatterns)

serializer.py:

class table_restSerializer(serializers.ModelSerializer):

    class Meta:
        model = table_rest
        fields = '__all__'

我的Android代码: 接口

public interface ApiInterface {

    @GET("rest")
    Call<CustomViewResponse> getJsonFromSid();

    @POST("rest")
    Call<CustomViewResponse> createTask(@Body CustomViewHolder task);
}

CustomViewHolder类:

public class CustomViewHolder {

    @SerializedName("id")
    private Integer id;

    @SerializedName("tt")
    private String tt;

    @SerializedName("varr")
    private Integer varr;

    @SerializedName("edi")
    private String edi;
    public CustomViewHolder(String tt, Integer varr, String edi){
        this.tt = tt;
        this.varr = varr;
        this.edi = edi;
    }

    public Integer getid(){
        return id;
    }
    /*public void setid(Integer id){
        this.id = id;
    }*/

    public String gettt()
    {
        return tt;
    }
    public void settt(String tt){
        this.tt = tt;
    }

    public Integer getvarr(){
        return varr;
    }

    public void setvarr(Integer varr){
        this.varr = varr;
    }

    public String getedi(){
        return edi;
    }

    public void setedi(String edi){
        this.edi = edi;
    }
}

CustomViewResponse class
public class CustomViewResponse {

    @SerializedName("results")
    private List<CustomViewHolder> results;

    public List<CustomViewHolder> getResults(){
        return results;
    }
}

MainActivity:

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final RecyclerView recyclerView = (RecyclerView) findViewById(R.id.sid_recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
        ApiInterface apiService1 = ApiClient.getClient().create(ApiInterface.class);
        Call<CustomViewResponse> call = apiService.getJsonFromSid();

         CustomViewHolder cc = new CustomViewHolder("my task title",22,"a string");

        call.enqueue(new Callback<CustomViewResponse>() {
            @Override
            public void onResponse(Call<CustomViewResponse> call, Response<CustomViewResponse> response) {
                int statuscode = response.code();
                List<CustomViewHolder> customViewHolders = response.body().getResults();

                recyclerView.setAdapter(new AdapterSid(customViewHolders, R.layout.list_item_sid, getApplicationContext()));
            }

            @Override
            public void onFailure(Call<CustomViewResponse> call, Throwable t) {
                Log.e("TAG main", t.toString());
            }
        });
        call1.enqueue(new Callback<CustomViewResponse>() {
            @Override
            public void onResponse(Call<CustomViewResponse> call1, Response<CustomViewResponse> respo) {
                int statuscode = respo.code();
                Log.d("Message", "code..."+respo.code() + " message..." + respo.message());

                CustomViewResponse respon = respo.body();

                if (respon == null){
                    Log.e("Error",""+statuscode+ "......"+ respo.message()+"....null body");
                    }

            }

            @Override
            public void onFailure(Call<CustomViewResponse> call1, Throwable t) {

                Log.e(TAG, t.toString());
            }
        });
    }

以下是我的表结构:

class table_rest(models.Model):

    tt = models.CharField(max_length=10,default = 12)
    varr = models.IntegerField(default=30)
    edi = models.CharField(max_length=1000,default='44')

    def __str__(self):
        return self.tt

使用postman我成功保存的Json身体是:

{
    "tt": "hello",
    "varr": 911,
    "edi": "emergency. Can't find solution"
}

2 个答案:

答案 0 :(得分:0)

请添加额外的网址。

urlpatterns = [
    url(r'^admin/', admin.site.urls), # Any URL starting with admin(ex: http://testdomainname.com/admin/xyz)
    url(r'^rest/$',views.restSerializer.as_view()), # Any URL starting with only rest(ex: http://testdomainname.com/rest/)
    url(r'^$',views.restSerializer.as_view()), # Any empty URL with '' (ex: http://testdomainname.com/)
]

答案 1 :(得分:0)

首先,我按照Dinesh Mandepudi的建议添加了网址模式。然后我在改造中改变了我的正则表达式。这是我在使用邮递员时没有遇到的网址问题。我刚刚添加了&#39; /&#39;在我的帖子正则表达式的开头。

public interface ApiInterface {

    @GET("/rest")
    Call<CustomViewResponse> getJsonFromSid();

    @POST("/rest/")
    Call<CustomViewResponse> createTask(@Body CustomViewHolder task);
}

同样一个愚蠢的错误是我试图在数据库列中添加一个13长度的字符串,而我已将限制设置为10.