post上传数组
‘壹’ post发送JSON数据(字符串、数组、字典、自定义对象)给服务器
post发送JSON数据(字符串、数组、字典、自定义对象)给服务器
触发发送的方法
这次Demo是通过点击屏幕触发发送数据给服务器事件
前提需要开启本地模拟服务器
发送JSON字符串
发送字典给服务器
发送数组给服务器
发送oc对象给服务器
先讲对象转换为字典
通过系统提供的JSON解析类进行序列化
觉得不错请点赞支持,欢迎留言或进我的个人群855801563领取【架构资料专题目合集90期】、【BATJTMD大厂JAVA面试真题1000+】,本群专用于学习交流技术、分享面试机会,拒绝广告,我也会在群内不定期答题、探讨
‘贰’ post请求参数传数组
public String androidPost() { String rs = null; String path = "url/Android_JDBC_SH/AndroidLoginAction"; HttpPost hp = new HttpPost(path); //获取客户端,用来向服务器发出请求 DefaultHttpClient hc = new DefaultHttpClient(); try { //Default Constructor taking a name and a value BasicNameValuePair nm = new BasicNameValuePair("name", name); BasicNameValuePair pa = new BasicNameValuePair("password", password); List list = new ArrayList(); list.add(nm); list.add(pa); //构建向服务器发送的实体 HttpEntity entity = new UrlEncodedFormEntity(list); hp.setEntity(entity); //提交请求,获取服务器的响应 HttpResponse response = hc.execute(hp); if (response.getStatusLine().getStatusCode() == 200) { //获取响应实体 entity = response.getEntity(); rs = EntityUtils.toString(entity); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return rs; }
‘叁’ python的urllib如何POST传递数组参数
1.如果机器上安装了 Python 的 setuptools,可以通过下面的命令来安装 poster:
easy_install poster
# test_client.pyfrom poster.encode import multipart_encodefrom poster.streaminghttp import register_openersimport urllib2# 在 urllib2 上注册 http 流处理句柄register_openers()# 开始对文件 "DSC0001.jpg" 的 multiart/form-data 编码# "image1" 是参数的名字,一般通过 HTML 中的 <input> 标签的 name 参数设置# headers 包含必须的 Content-Type 和 Content-Length# datagen 是一个生成器对象,返回编码过后的参数datagen, headers = multipart_encode({"image1": open("DSC0001.jpg", "rb")})# 创建请求对象request = urllib2.Request("http://localhost:5000/upload_image", datagen, headers)# 实际执行请求并取得返回print urllib2.urlopen(request).read()
很简单,文件就上传完成了。
2.其中那个 register_openers() 相当于以下操作:
from poster.encode import multipart_encodefrom poster.streaminghttp import StreamingHTTPHandler, StreamingHTTPRedirectHandler, StreamingHTTPSHandlerhandlers = [StreamingHTTPHandler, StreamingHTTPRedirectHandler, StreamingHTTPSHandler]opener = urllib2.build_opener(*handlers)urllib2.install_opener(opener)
3.另外,poster 也可以携带 cookie,比如:
opener = poster.streaminghttp.register_openers()opener.add_handler(urllib2.HTTPCookieProcessor(cookielib.CookieJar()))params = {'file': open("test.txt", "rb"), 'name': 'upload test'}datagen, headers = poster.encode.multipart_encode(params)request = urllib2.Request(upload_url, datagen, headers)result = urllib2.urlopen(request)