0

这是我的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()

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

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”。

这是所有的代码。你看有什么不对吗?

4

1 回答 1

0

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

我决定将服务器重新实现为带有参数的 GET,而不是 Get 和 POST。我导入 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()

这似乎适合我的项目需求。

于 2012-10-18T17:27:57.987 回答