0
這裏是我的Python服務器代碼...的Java帖子到Python HTTP服務器無法正常工作
#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());
}
}
這一切似乎都很簡單,但我無法成功發佈到服務器。我得到兩個錯誤之一。
服務器或者從未收到請求(蟒紋出不會發生),或者,它就會請求(打印),但不改變值(當它它打印的變化。
原來蟒蛇服務器的教程來了與直接更新值形式的HTML頁面。這個表單頁面完美的作品,但我需要能夠從Java到POST。
我用下面的代碼的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」。
這是所有的代碼。你看到有什麼問題嗎?
的服務器地址變量特定的其他機器的地址的值。代替cgi.parse_multipart爲X WWW的窗體-urlencoded數據 – viperld002
使用'urlparse.parse_qs()'。 – jfs
我會試試這個,讓你知道它是怎麼回事(ty爲你的迴應)。 – viperld002