用于发布请求的java applet和django服务器之间的http连接

时间:2012-08-29 10:22:40

标签: java django http applet http-post

我正在尝试将文档扫描小程序中的日志记录数据发送到django支持的Web服务器。

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

这是我applet中的代码 -

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错误的更多信息都将不胜感激!

UPDATE 来自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

1 个答案:

答案 0 :(得分:2)

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

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

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

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();}
    }   
}

Using java.net.URLConnection to fire and handle HTTP requests非常有用。

希望这对其他人有帮助。