RESTful client for java
2011-12-31 13:29
155 查看
package com.hailiang.http; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; public class WeiboRestClient { public final static String METHOD_GET="GET"; public final static String METHOD_PUT="PUT"; public final static String METHOD_DELETE="DELETE"; public final static String METHOD_POST="POST"; public static void rest(String serviceUrl,String parameter,String restMethod){ try { URL url= new URL(serviceUrl); HttpURLConnection con = (HttpURLConnection)url.openConnection(); con.setRequestMethod(restMethod); //如果请求方法为PUT,POST和DELETE设置DoOutput为真 if(!WeiboRestClient.METHOD_GET.equals(restMethod)){ con.setDoOutput(true); if(!WeiboRestClient.METHOD_DELETE.equals(restMethod)){ //请求方法为PUT或POST时执行 OutputStream os = con.getOutputStream(); os.write(parameter.getBytes("UTF-8")); os.close(); } } else{ //请求方法为GET时执行 InputStream in= con.getInputStream(); byte[] b= new byte[1024]; int result= in.read(b); while( result!=-1){ System.out.write(b,0,result); result= in.read(b); } } System.out.println(con.getResponseCode()+":"+con.getResponseMessage()); } catch ( Exception e ) { throw new RuntimeException(e ); } } public static void main(String args[]){ // //GET // rest("http://localhost:8081/sqlrest/PRODUCT/4",null,WeiboRestClient.METHOD_GET); // // //PUT // String put="<?xml version=\"1.0\" encoding=\"UTF-8\" ?><PRODUCT xmlns:xlink=\"http://www.w3.org/1999/xlink\"><NAME>Chair Shoe</NAME>" // +"<PRICE>24.8</PRICE></PRODUCT>"; // rest("http://localhost:8081/sqlrest/PRODUCT/395",put,WeiboRestClient.METHOD_PUT); // // //POST // String post="<?xml version=\"1.0\" encoding=\"UTF-8\" ?><PRODUCT xmlns:xlink=\"http://www.w3.org/1999/xlink\">" // +"<PRICE>98</PRICE></PRODUCT>"; // rest("http://localhost:8081/sqlrest/PRODUCT/395",post,WeiboRestClient.METHOD_POST); // // //DELETE // rest("http://localhost:8081/sqlrest/PRODUCT/395",null,WeiboRestClient.METHOD_DELETE); } }
相关文章推荐
- memcache-client-forjava 源码分析之DefaultCacheImpl分析
- RESTful Java client with RESTEasy client framework
- memcache client for java
- Ganymed SSH-2 for Java系列11之SCPClient
- Retrofit2,A type-safe HTTP client for Android and Java
- RESTful Java client with Apache HttpClient
- Retrofit——A type-safe HTTP client for Android and Java(The first part)
- jax-rs(Java API for RESTful Web Services) 实践教程 之四 —— @Context注入HttpServletRequest 使REST保持状态!
- httpclient for java 测试openstack swift
- IOT command (based on sip)client API设计 for java
- Jest is a Java HTTP Rest client for Elasticsearch
- JAX-RS -- Java API for RESTful Web Services
- elasticsearch for java【教程一Client】
- httpclient for java 测试 openstack swift
- 【转】memcache-client-forjava
- Retrofit A type-safe HTTP client for Android and Java
- Java for Web学习笔记(四五):WebSocket(2)JavaScript Client
- [Java] Memcached Client For Java使用
- jax-rs(Java API for RESTful Web Services) 实践教程 之五 —— 注入全局变量 和 rest的生命周期
- memcached client -- memcached client for java使用