“POST / receiver / HTTP / 1.1”500 137512

时间:2014-01-31 15:16:58

标签: android python json django

服务器端 - 使用Django Framework进行Python编程:

views.py

from django.http import HttpResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
import django.utils.simplejson as json

@csrf_exempt
def rcvr(request):
    if request.method=='POST':  
        objs = request.POST.get['username']
        return render(request, "post.html",{'username': username})
    else:
        return HttpResponse("Failure...")

urls.py

from django.conf.urls import patterns, include, url
from django.contrib import admin
from receiver import views
admin.autodiscover()
urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'woodpecker.views.home', name='home'),
    # url(r'^woodpecker/', include('woodpecker.foo.urls')),
    # Uncomment the admin/doc line below to enable admin documentation:
    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
    # Uncomment the next line to enable the admin:
    url(r'^admin/', include(admin.site.urls)),
    url(r'^receiver/', views.rcvr, name='rcvr'),
)

rcvr.html

<html>
    <head></head>
    <body>        
        <form action="{% url 'woodpecker.receiver.views.rcvr' %}" method="post">{% csrf_token %}
            <input type="text" name="username">
            <input type="submit" id="click1" value="username">
        </form>
    </body>
</html>

客户端 - Android应用程序

package com.example.postjson;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpResponse;
import org.apache.http.client.*;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;

public class MainActivity extends Activity{
    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        HttpClient httpclient = new DefaultHttpClient();         
        try{
            HttpPost post = new HttpPost("http://10.0.2.2:8000/receiver/");
            post.setHeader("Content-type", "application/json");
            post.setHeader("Accept","application/json");
            JSONObject obj=new JSONObject();
            obj.put("username", "abcd");
            obj.put("password","1234");
            post.setEntity(new StringEntity(obj.toString(),"UTF-8"));
            System.out.println("Yo...Yo...!! B-) ");             

            HttpResponse response = httpclient.execute(post);

            }catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }catch (ClientProtocolException e) {
                e.printStackTrace();
            }catch (IOException e) {
                e.printStackTrace();
            }catch(NullPointerException e){
                e.printStackTrace();
            }catch(Exception e){
                e.printStackTrace();
            }
        }

    @Override
    public boolean onCreateOptionsMenu(Menu menu){
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}

每当我从模拟器运行我的应用程序时,我都会收到500错误...

[root@vivek-vaio woodpecker]# python manage.py runserver
Validating models...

0 errors found
January 31, 2014 - 20:04:54
Django version 1.5.4, using settings 'woodpecker.settings'
Development server is running at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
[31/Jan/2014 20:04:57] "GET /receiver/ HTTP/1.1" 200 10
[01/Feb/2014 09:55:21] "POST /receiver/ HTTP/1.1" 500 137512
Internal Server Error: /receiver/
Traceback (most recent call last):
    File "/usr/lib/python2.7/site-packages/django/core/handlers/base.py", line 115, in get_response
    response = callback(request, *callback_args, **callback_kwargs)
    File "/usr/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 77, in  wrapped_view
    return view_func(*args, **kwargs)
    File "/home/vivek/PROJECT/Server_Work/woodpecker/receiver/views.py", line 21, in rcvr
    return render(request, "rcvr.html",{'username': objs})
    File "/usr/lib/python2.7/site-packages/django/shortcuts/__init__.py", line 53, in render
    return HttpResponse(loader.render_to_string(*args, **kwargs),
    File "/usr/lib/python2.7/site-packages/django/template/loader.py", line 177, in render_to_string
    return t.render(context_instance)
    File "/usr/lib/python2.7/site-packages/django/template/base.py", line 140, in render
    return self._render(context)
    File "/usr/lib/python2.7/site-packages/django/template/base.py", line 134, in _render
    return self.nodelist.render(context)
    File "/usr/lib/python2.7/site-packages/django/template/base.py", line 830, in render
    bit = self.render_node(node, context)
    File "/usr/lib/python2.7/site-packages/django/template/debug.py", line 74, in render_node
    return node.render(context)
    File "/usr/lib/python2.7/site-packages/django/template/defaulttags.py", line 404, in render
    raise NoReverseMatch("'url' requires a non-empty first argument. "
    NoReverseMatch: 'url' requires a non-empty first argument. The syntax changed in Django 1.5, see the docs.
[01/Feb/2014 09:55:33] "POST /receiver/ HTTP/1.1" 500 137512

任何人都可以帮帮我吗? 500错误???

2 个答案:

答案 0 :(得分:0)

您在视图中缺少一些步骤来完全启用CSRF。我假设CSRF是问题,因为如果没有正确启用它会抛出403.

https://docs.djangoproject.com/en/dev/ref/contrib/csrf/

答案 1 :(得分:0)

HTTP 500错误表示代码中存在一些运行时错误。 我发现了错误! JSON数据始终位于请求组件的正文中。 这条线没有。 9已更新,错误已成功删除。

from django.http import HttpResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
import django.utils.simplejson as json

@csrf_exempt
def rcvr(request):
    if request.method=='POST':
        data = json.loads(request.body.decode(encoding='UTF-8'))
        if data != None:
            username = data['username']
            return HttpResponse(username)
        else:
            return HttpResponse("Nothing was received!")
    else:
        return HttpResponse("POST Error!")