一、python HttpPost
以json格式数据通信为例
1、python Server端:
#__author__ = 'Administrator'
# -*- coding: utf-8 -*-
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
from os import curdir, sep
import cgi
import logging
import time
from SocketServer import ThreadingMixIn
import GPs
import json
import linearRegression
class Handler(BaseHTTPRequestHandler):
def _writeheaders(self):
self.send_response(200)
self.send_header('Content-type','text/html')
self.end_headers()
def do_POST(self):
self._writeheaders()
length = self.headers.getheader('content-length');
nbytes = int(length)
# print nbytes
data = self.rfile.read(nbytes)
# self.send_response(200)
jdata = json.loads(data,encoding="GBK") #jdata即为json 数据,可以类似操纵字典进行操作,如<span style="font-family: Arial, Helvetica, sans-serif;">dateList = jdata.keys()</span>
# 以下是返回json的内容
topWords = {}
topWords['words'] = topNWords
topWords['weight'] = weight
response = {}
response['nextDayHot'] = predictValue
response['topWords'] = topWords
message = json.dumps(response)
self.wfile.write(message)
class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
"""Handle requests in a separate thread."""
pass
if __name__ == '__main__':
server = ThreadedHTTPServer(('localhost', 10001), Handler)
server.serve_forever()
2、python Client端请求
#__author__ = 'Administrator'
# -*- coding: utf-8 -*-
import urllib
import urllib2
import json
sendData ={
'2016-07-21':{
'hotList':[112,232,57],
'titleList':[u'标题1',u'标题2',u'标题3']
},
'2016-07-22':{
'hotList':[191,456,234],
'titleList':<span style="font-family: Arial, Helvetica, sans-serif;">[u'标题1',u'标题2',u'标题3']</span>
},
'2016-07-23':{
'hotList':[231,341,29],
'titleList':<span style="font-family: Arial, Helvetica, sans-serif;">[u'标题1',u'标题2',u'标题3']</span>
},
'2016-07-24':{
'hotList':[654,125,343],
'titleList':<span style="font-family: Arial, Helvetica, sans-serif;">[u'标题1',u'标题2',u'标题3']</span>
},
'2016-07-25':{
'hotList':[122,434,231],
'titleList':<span style="font-family: Arial, Helvetica, sans-serif;">[u'标题1',u'标题2',u'标题3']</span>
}
}
message = json.dumps(sendData)
response = urllib2.urlopen('http://localhost:10001/',unicode(message))
data = response.read()
# print type(response
jdata = json.loads(data,encoding="GBK") #jdata即为获取的json数据
print jdata.keys()
3、java Client端请求
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import org.json.JSONException;
import org.json.JSONObject;
public class JavaPost {
public static final String ADD_URL = "http://101.200.146.57:10001/";
public static void appadd() throws JSONException {
try {
//创建连接
URL url = new URL(ADD_URL);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.connect();
//POST请求
DataOutputStream out = new DataOutputStream(
connection.getOutputStream());
HashMap<String,HashMap> sendData = new HashMap<String,HashMap>();
String[] date = {"2016-07-24","2016-07-25","2016-07-26","2016-07-27","2016-07-28"};
for (int i = 0; i < date.length; i++ ){
HashMap<String,Object> item = new HashMap<String,Object>();
int [] hot = {654,125,343};
item.put("hotList", hot);
String [] titleList = {"标题1","标题2","标题3"};
item.put("titleList",titleList);
sendData.put(date[i],item);
}
JSONObject json = new JSONObject(sendData);
String jsonString = json.toString();
byte[] jsonByte = jsonString.getBytes();
out.write(jsonByte);
out.flush();
out.close();
//读取响应
DataInputStream inputStream = null;
String strInputStream ="";
inputStream = new DataInputStream(new BufferedInputStream(connection.getInputStream()));
byte[] by = new byte[20480];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int nbyte;
while((nbyte=inputStream.read(by))!=-1){
baos.write(by,0,nbyte);
}
strInputStream = new String(baos.toByteArray());
JSONObject js = new JSONObject(strInputStream);
System.out.println(js.toString());
// 断开连接
connection.disconnect();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) throws JSONException {
appadd();
}
}