我有一些 Java 代码试图将 POST 数据发送到 Django 应用程序。但是,视图根本不会被调用。如果我将 java 代码命中的相同 URL 粘贴到我的浏览器中,则会调用 Django 视图。我不知道我错过了什么,但 Java 编写一定有问题。
这是执行写入的 Java 函数:
public void executeWrite(String requestUrl, JsonObject jsonObject)
{
DataInputStream input = null;
try
{
URL url;
HttpURLConnection urlConn;
DataOutputStream printout;
System.out.println(requestUrl);
// URL of CGI-Bin script.
url = new URL (requestUrl);
// URL connection channel.
urlConn = (HttpURLConnection)url.openConnection();
// Let the run-time system (RTS) know that we want input.
urlConn.setDoInput (true);
// Let the RTS know that we want to do output.
urlConn.setDoOutput (true);
// No caching, we want the real thing.
urlConn.setUseCaches (false);
// Specify the content type.
urlConn.setRequestMethod("POST");
urlConn.setRequestProperty("content-type","application/json; charset=utf-8");
OutputStreamWriter wr = new OutputStreamWriter(urlConn.getOutputStream());
wr.write(jsonObject.toString());
wr.flush();
wr.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
现在传入函数的 requestURL 直接对应于 Django 视图的请求URL。请求网址是:
http://127.0.0.1:8000/events/rest/33456/create
这是 Django Urlconfig:
(r'^events/rest/(?P<key>\d+)/create', 'events.views.restCreateEvent'),
最后,这是 Java 代码永远不会调用的视图
@csrf_exempt
def restCreateEvent(request, key):
#doesn't really matter what is in here it never runs
那么,Django服务器从未收到过POST请求,我做错了什么?我花了大约 2 个小时试图弄清楚,我找不到 Java 代码的任何问题。显然有些地方出了问题。