通过HttpURLConnection使用Get和Post方法发送数据
Get方法发送数据
在Get类中
HttpURLConnection conn=(HttpURLConnection)new URL(path).openConnection(); conn.setConnectTimeout(15000); conn.setRequestMethod("GET");
测试方法
new Get("http://XXXXX/WebService/index/indexindex.action?id=1&name="+URLEncoder.encode("您好","utf-8")).setGetRequest()
服务器端接收数据
HttpServletRequest request=ServletActionContext.getRequest(); System.out.println(id); System.out.println(new String(name.getBytes("ISO-8859-1"),"utf-8"));
Post方法发送数据
byte [] entity=("id=1&name="+URLEncoder.encode("您好","utf-8")).getBytes(); HttpURLConnection conn=(HttpURLConnection)new URL(path).openConnection(); conn.setConnectTimeout(5000); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");//用于指导实体数据的内容类型 conn.setRequestProperty("Content-Length",String.valueOf(entity.length));//entity为要传输的数据格式为 title=hello&time=20//可以对该数据编码 OutputStream outStream=conn.getOutputStream(); outStream.write(entity);
测试方法
new Post("http://XXXXXX/WebService/index/indexreceivePost.action").setPostRequest()
服务器端接收数据
HttpServletRequest request=ServletActionContext.getRequest(); System.out.println(id); request.setCharacterEncoding("utf-8"); System.out.println(name);
向服务器端传输xml数据
byte [] entity="<strings><id>1</id><name>hello</name></strings>".getBytes(); HttpURLConnection conn=(HttpURLConnection)new URL(path).openConnection(); conn.setConnectTimeout(5000); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setRequestProperty("Content-Type","text/xml; charset=UTF-8");//用于指导实体数据的内容类型 conn.setRequestProperty("Content-Length",String.valueOf(entity.length)); OutputStream outStream=conn.getOutputStream(); outStream.write(entity);
服务器端接收数据
HttpServletRequest request=ServletActionContext.getRequest(); InputStream is=request.getInputStream();
Notice:Get方式发送数据一般小于2K,如果大于2K,最好用Post方式
相关推荐
86193952 2020-10-27
小木兮子 2020-11-11
HeyShHeyou 2020-11-17
seanzed 2020-10-15
huangliuyu00 2020-09-24
libaoshan 2020-09-11
zhangpan 2020-09-10
chongxiaocheng 2020-08-16
xcguoyu 2020-08-15
Qizonghui 2020-08-02
ldcwang 2020-07-26
mqfcu 2020-07-21
jeason 2020-07-20
sunzhihaofuture 2020-07-19
knightwatch 2020-07-19
点滴技术生活 2020-07-19
Reiki 2020-07-06