これが私の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());
}
}
それはすべて簡単に思えますが、サーバーに正常に投稿できません。2 つのエラーのうちの 1 つが表示されます。
サーバーはリクエストを取得しない (python の出力は行われない) か、リクエストを取得 (出力) するが値を変更しない (変更した場合は .
元の python サーバー チュートリアルには、値を直接更新するためのフォームを含む 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」です。
これがコードのすべてです。何かおかしくないですか?