django中json的HTTP请求不包含任何内容

时间:2015-07-12 01:16:50

标签: android python json django

SOS。

我真的厌倦了寻找我的简单问题。请帮帮我。

我有一个Android应用程序,它与我的django服务器建立HTTP连接并发送一个json并请求json接收。我的代码在android和django中。

但问题是我的请求在django中不包含任何内容。没有标题,没有正文,也没有其他内容。当我打印 request.body 时,我看到的只是b ''在原始数据的命令中。

请告诉我哪里出错了。

很多人。

url.py

from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^post/', 'Post.views.post'),
]

view.py

from django.http import HttpResponse


def post(request):
    print(request.body)
    return HttpResponse("This is my response", content_type='text/plain')

setting.py

import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

SECRET_KEY = '-)lnh2s!-hiunefbnu9%65m@mrk4(ztt*cfmq%8zj3-pg2+7l7'

DEBUG = False

ALLOWED_HOSTS = ['*']

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'Post',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware',
)

ROOT_URLCONF = 'Test_Web_Service.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'Test_Web_Service.wsgi.application'

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

STATIC_URL = '/static/'

TEMPLATE_DIRS = (
    os.path.join(BASE_DIR,  'templates'),
)

我的android代码是:

PostClass.java

import android.content.Context;

import com.google.gson.Gson;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import dao.User;


public class PostClass {

public static String Post(Context context) throws IOException {
    Gson gson = new Gson();
    JSONObject object = new JSONObject();//
    String jsonObjecetString;

    User user = new User();
    user.setId(Long.parseLong("123"));
    user.setName("someonesName");
    user.setPassword("secretPass");
    user.setPhone(Long.parseLong("123456789"));

    jsonObjecetString = gson.toJson(user);

    String content = "";
    BufferedReader reader = null;

    try {
        object.put("", jsonObjecetString);


        String url = "http://192.168.1.12:8080/post";

        StringBuilder builder = new StringBuilder();

        HttpClient httpClient = new DefaultHttpClient();

        HttpPost request = new HttpPost(url);

        StringEntity entity;


        entity = new StringEntity(object.toString());

        request.setEntity(entity);
        request.setHeader("Content-Type", "application/json");

        HttpResponse response = httpClient.execute(request);
        int status = response.getStatusLine().getStatusCode();

        if (status == 200) // sucess
        {
            HttpEntity ex = response.getEntity();

            // String data = EntityUtils.toString(e);
            InputStream content2 = ex.getContent();
            reader = new BufferedReader(new InputStreamReader(content2));

            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }

            content = builder.toString();
        } else if (status == 401) {
            return "-Auth Failed Error Code 400";
        } else {
            return "-Error Code: " + status;
        }

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return content;


}
}

1 个答案:

答案 0 :(得分:0)

您的Java正在发送到网址' / post',但Django正在收听' / post /'。附加斜线中间件将从第一个重定向到第二个,但重定向始终是GET,因此正文将丢失。你应该发布到' / post /'首先。