JAVA模拟各种请求方式访问RESTFUL

2014-11-24 09:04:17 · 作者: · 浏览: 0
//需要请求的restful地址  
URL url = new URL("http://localhost:8080/JerseyTest/rest/hello");  
              
//打开restful链接  
HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
              
// 提交模式  
conn.setRequestMethod("PUT");//POST GET PUT DELETE  
              
//设置访问提交模式,表单提交  
conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");  
              
conn.setConnectTimeout(10000);//连接超时 单位毫秒  
conn.setReadTimeout(2000);//读取超时 单位毫秒  
              
conn.setDoOutput(true);// 是否输入参数  
  
StringBuffer params = new StringBuffer();  
// 表单参数与get形式一样  
params.append("customer").append("=").append(1);  
byte[] bypes = params.toString().getBytes();  
conn.getOutputStream().write(bypes);// 输入参数
//读取请求返回值 InputStream inStream=conn.getInputStream(); inStream.read(bypes, 0, inStream.available()); System.out.println(new String(bypes, "gbk"));