Java发布到Python HTTP服务器不起作用

时间:2012-10-18 03:35:49

标签: java python http post webserver

这是我的python服务器代码......

#Copyright Jon Berg , turtlemeat.com

import string,cgi,time
from os import curdir, sep
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
#import pri

class MyHandler(BaseHTTPRequestHandler):

    # our servers current set ip address that clients should look for.
    server_address = "0.0.0.0"

    def do_GET(self):
        try:
            if self.path.endswith(".html"):
                f = open(curdir + sep + self.path)
                self.send_response(200)
                self.send_header('Content-type',    'text/html')
                self.end_headers()

                str = ""
                seq = ("<HTML>", MyHandler.server_address, "</HTML>")
                str = str.join( seq )
                print str
                self.wfile.write( str )
                return
            return

        except IOError:
            self.send_error(404,'File Not Found: %s' % self.path)


    def do_POST(self):
        global rootnode

        try:
            ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))
            if ctype == 'application/x-www-form-urlencoded':
                query=cgi.parse_multipart(self.rfile, pdict)
            self.send_response(301)

            self.end_headers()
            MyHandler.server_address = "".join( query.get('up_address') )
            print "new server address", MyHandler.server_address
            self.wfile.write("<HTML>POST OK.<BR><BR>")

        except :
            pass

def main():
    try:
        server = HTTPServer(('', 80), MyHandler)
        print 'started httpserver...'
        server.serve_forever()
    except KeyboardInterrupt:
        print '^C received, shutting down server'
        server.socket.close()

if __name__ == '__main__':
    main()

这是我的Java代码,将值发布到“up_address”...

static public void post( String address, String post_key, String post_value ){

        try {
            // Construct data
            String data = URLEncoder.encode(post_key, "UTF-8") + "=" + URLEncoder.encode(post_value, "UTF-8");

            // Send data
            URL url = new URL(address);
            HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
            httpCon.setDoOutput(true);
            httpCon.setRequestMethod("POST"); 
            httpCon.setRequestProperty("content-type", "application/x-www-form-urlencoded"); 
            httpCon.setRequestProperty("charset", "utf-8");
            httpCon.setRequestProperty("Content-Length", "" + Integer.toString(address.getBytes().length));
            httpCon.setUseCaches (false);

            OutputStreamWriter wr = new OutputStreamWriter(httpCon.getOutputStream());
            wr.write(data);
            wr.flush();

            // Get the response
            BufferedReader rd = new BufferedReader(new InputStreamReader(httpCon.getInputStream()));
            String line;
            while ((line = rd.readLine()) != null) {
                // Process line...
            }
            wr.close();
            rd.close();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

    }

这一切似乎很简单,但我无法成功发布到服务器。我得到了两个错误之一。

服务器永远不会收到请求(python打印输出不会发生),或者,它获取请求(打印)但不更改值(当它打印更改时。

最初的python服务器教程带有一个html页面,其中包含一个用于直接更新值的表单。此表单页面完美运行。但是我需要能够从Java发布。

我也使用了以下的apache代码,它也不起作用......

HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(address);
        try {
          List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
          nameValuePairs.add(new BasicNameValuePair( post_key, post_value));
          post.setEntity(new UrlEncodedFormEntity(nameValuePairs));

          HttpResponse response = client.execute(post);
          BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
          String line = "";
          while ((line = rd.readLine()) != null) {
            System.out.println(line);
          }

        } catch (IOException e) {
          e.printStackTrace();
        }

我不知道出了什么问题。如果有帮助,我的文字POST键/值是“up_address = 10.0.1.2”。

这是所有代码。你觉得它有什么问题吗?

1 个答案:

答案 0 :(得分:0)

我无法辨别问题。我相信这是python服务器代码。

我决定使用参数而不是Get和POST重新实现服务器作为GET。我导入urlparse以获取附加到url(source)的键。然后我只想找到我想要的w / e键。

这是我的新服务器代码...(预期的参数是'up_address':'10.0.1.2')。

import string,cgi,time, urlparse
from os import curdir, sep
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
#import pri

class MyHandler(BaseHTTPRequestHandler):

    # our servers current set ip address that clients should look for.
    server_address = "0.0.0.0"

    def do_GET(self):
    qs = {}
    path = self.path
    if '?' in path:
        path, tmp = path.split('?', 1)
        qs = urlparse.parse_qs(tmp)
        MyHandler.server_address = qs['up_address']
        print 'new server address: ', MyHandler.server_address


def main():
    try:
        server = HTTPServer(('', 8080), MyHandler)
        print 'started httpserver...'
        server.serve_forever()
    except KeyboardInterrupt:
        print '^C received, shutting down server'
        server.socket.close()

if __name__ == '__main__':
    main()

这似乎对我项目的需求很好。