通过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方式

url

相关推荐