当前位置:编程学习 > JAVA >>

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

//需要请求的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);// 输入参数<pre class="java" name="code">//读取请求返回值  
InputStream inStream=conn.getInputStream();  
inStream.read(bypes, 0, inStream.available());  
System.out.println(new String(bypes, "gbk"));</pre>  

 

补充:软件开发 , Java ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,