【问题标题】:HTTP Request for a json in django does not contain anythingdjango中对json的HTTP请求不包含任何内容
【发布时间】:2015-09-30 12:58:51
【问题描述】:

求救。

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

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

但问题是我在 django 中的 request 不包含任何内容。没有标题,没有正文,没有其他内容。当我打印 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'),
)

我的安卓代码是:

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;


}
}

【问题讨论】:

    标签: android python json django


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2016-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多