HttpURLConnection:POST请求中没有数据

时间:2015-07-09 01:44:23

标签: java django-rest-framework httpurlconnection androidhttpclient

我创建了一个Django Rest服务器。我正在尝试使用HttpURLConnection在java中发布JSON内容。但是,当我在java中注册OutputStream时,服务器获得一个没有JSON内容的POST请求。因此服务器使用HTTP响应代码400拒绝请求。我在注册OutputSream之后就写了JSON数据。可能是在写入OutputStream之前已经发出了POST。以下是JAVA中的代码。

    public static void post(HttpURLConnection urlConnection1)
        throws IOException, InterruptedException {
    // urlConnection.setRequestMethod("POST");

    URL url = new URL("http://127.0.0.1:8000/message/");
    byte[] authStr=Base64.encodeBase64("sp:password".getBytes());
    String enc=new String(authStr);

    HttpURLConnection urlConnection = (HttpURLConnection) url
            .openConnection();
    urlConnection.setRequestProperty("Authorization", "Basic "+ enc);
    try {

        urlConnection.setDoOutput(true);
        urlConnection.setChunkedStreamingMode(0);
        urlConnection
                .setRequestProperty("Content-Type", "application/json");
        urlConnection.setRequestMethod("POST");
        urlConnection.setInstanceFollowRedirects(false);


        OutputStream out = urlConnection.getOutputStream();
        //Thread.sleep(5000);
        writeStream(out);
        out.flush();

        InputStream in = urlConnection.getInputStream();
        readStream(in);
    } finally {
        urlConnection.disconnect();
    }

}

private static void writeStream(OutputStream out) {
    // TODO Auto-generated method stub
    try {
        JSONObject grp = new JSONObject();
        JSONObject gp = new JSONObject();
        gp.put("id", "g3bj25");
        gp.put("from", "someone");

        out.write(gp.toString().getBytes());

        System.out.println(gp.toString());
    } catch (IOException | JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

我是否必须在服务器端进行任何更改才能等待内容?

0 个答案:

没有答案
相关问题