1

我正在尝试将记录数据从文档扫描小程序发送到 django 驱动的 Web 服务器。

我正在使用 django 自己的网络服务器进行测试。我用 java 构造了一个简单的 POST 请求,但是 django 服务器抛出 500 错误。我无法获得有关该错误的任何信息。我似乎无法使用 pydevd 来中断我的 django 视图中的代码(我的 url 设置正确 - 如果我使用浏览器访问 url,我可以单步执行代码)。我的小程序上没有任何调试设置,但我确实有很多信息可以发送到控制台。我知道 django 会发送大量 html 信息以及 500 错误,但我的 java 小程序在读取消息之前抛出异常(以响应 500 错误)。

这是我的小程序中的代码 -

private boolean log(String scanURL) {

    try {
        String data = "log=" + buffer.toString();
        URL url = new URL(scanURL);
        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
        writer.write(data);
        writer.flush();

        // Handle the response
        int responseCode = ((HttpURLConnection) conn).getResponseCode();
        addItem("Http response code " + new Integer(responseCode).toString());
        addItem("creating BufferedReader");
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;
        addItem("reading response");
        while ((line = reader.readLine()) != null) {
            addItem(line);
        }
        addItem("Closing Writer");
        writer.close();
        addItem("Closing Reader");
        reader.close();

        if (responseCode == 200) {
            return true;
            }
        else {
            return false;
        }

    } catch (Exception e) {
        addItem("Error - writing to log failed. " + e);
        return false;
    }

}

而我的 Django 视图目前是 -

from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
from cache.shortcuts import permission_required

@login_required
@permission_required('documents.add_documentindex', raise_exception=True)
def save_log(request):
    import pydevd;pydevd.settrace()
    log_text = request.POST['log']
    with open("scanning.log", "a") as f:
        f.write(log_text)
    return HttpResponse('ok')

我怀疑我需要对 http 标头做一些工作,但是如果没有来自 django 的更多信息,我对 http 的了解是一个很大的障碍。

任何有关使其正常工作的建议,或者甚至获得有关 django 的服务器 500 错误的更多信息,将不胜感激!

更新来自java异常的堆栈跟踪如下

java.io.IOException: Server returned HTTP response code: 500 for URL: http://10.0.0.68:8000/scanning_log
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection$6.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.net.www.protocol.http.HttpURLConnection.getChainedException(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
    at co.altcom.cache.scanner.CacheScan.log(CacheScan.java:408)
    at co.altcom.cache.scanner.CacheScan.createLog(CacheScan.java:385)
    at co.altcom.cache.scanner.CacheScan.destroy(CacheScan.java:70)
    at sun.plugin2.applet.Plugin2Manager$AppletExecutionRunnable.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: java.io.IOException: Server returned HTTP response code: 500 for URL: http://10.0.0.68:8000/scanning_log
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
    at java.net.HttpURLConnection.getResponseCode(Unknown Source)
    at co.altcom.cache.scanner.CacheScan.log(CacheScan.java:405)
    ... 4 more
4

1 回答 1

2

我最初的问题要求从 django 服务器获取更多信息的建议。我想我需要的答案是在java.io.IOException: Server returned HTTP response code: 500中找到的。

getInputStream当服务器返回错误代码(如 500)时,Java 的URLConnection 对象方法会抛出异常。解决方案是改用 getErrorStream 。这让我可以访问 django 的服务器生成的 html 错误信息。

我的小程序的日志记录方法的最终工作代码是 -

public boolean log(String logURL) {

    String charset = "UTF-8";
    String logData = logBuffer.toString();
    OutputStream output = null;
    HttpURLConnection conn = null;
    BufferedReader reader = null;
    InputStream in = null;

    try {
        String query = String.format("log=%s", URLEncoder.encode(logData, charset));
        conn = (HttpURLConnection) new URL(logURL).openConnection();
        conn.setDoOutput(true);
        conn.setRequestProperty("Accept-Charset", charset);
        conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded;charset=" + charset);
        output = conn.getOutputStream();
        output.write(query.getBytes(charset));

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        return false;
    } catch (MalformedURLException e) {
        e.printStackTrace();
        return false;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    } finally {
         if (output != null) try { output.close(); } catch (IOException e) {e.printStackTrace();}
    }

    // Handle the response
    try {
        int responseCode = conn.getResponseCode();
        if (responseCode == 200) {
            in = conn.getInputStream();
        } else {
            in = conn.getErrorStream();
        }
        reader = new BufferedReader(new InputStreamReader(in));
        String line;
        logNote("reading response");
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
        reader.close();         
        if (responseCode == 200) {
            return true;
            }
        else {
            return false;
        }

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        return false;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    } finally {
        if (reader != null) try { reader.close(); } catch (IOException e) {e.printStackTrace();}
    }   
}

使用 java.net.URLConnection 触发和处理 HTTP 请求非常有用。

希望这对其他人有帮助。

于 2012-08-29T15:10:34.427 回答