java WebService接口调用,传JSON参数

  1. 转自:http://zheyiw.iteye.com/blog/1571222



  2. import java.io.IOException;  
  3. import java.io.InputStream;  
  4. import java.io.OutputStreamWriter;  
  5. import java.net.HttpURLConnection;  
  6. import java.net.URL;  
  7.   
  8. public class Copy_2_of_PostDemo {  
  9.   
  10.     final static String url = "";  
  11.     final static String params = "{\"id\":\"12345\"}";  
  12.   
  13.     /** 
  14.      * 发送HttpPost请求 
  15.      *  
  16.      * @param strURL 
  17.      *            服务地址 
  18.      * @param params 
  19.      *            json字符串,例如: "{ \"id\":\"12345\" }" ;其中属性名必须带双引号<br/> 
  20.      * @return 成功:返回json字符串<br/> 
  21.      */  
  22.     public static String post(String strURL, String params) {  
  23.         System.out.println(strURL);  
  24.         System.out.println(params);  
  25.         try {  
  26.             URL url = new URL(strURL);// 创建连接  
  27.             HttpURLConnection connection = (HttpURLConnection) url  
  28.                     .openConnection();  
  29.             connection.setDoOutput(true);  
  30.             connection.setDoInput(true);  
  31.             connection.setUseCaches(false);  
  32.             connection.setInstanceFollowRedirects(true);  
  33.             connection.setRequestMethod("POST"); // 设置请求方式  
  34.             connection.setRequestProperty("Accept""application/json"); // 设置接收数据的格式  
  35.             connection.setRequestProperty("Content-Type""application/json"); // 设置发送数据的格式  
  36.             connection.connect();  
  37.             OutputStreamWriter out = new OutputStreamWriter(  
  38.                     connection.getOutputStream(), "UTF-8"); // utf-8编码  
  39.             out.append(params);  
  40.             out.flush();  
  41.             out.close();  
  42.             // 读取响应  
  43.             int length = (int) connection.getContentLength();// 获取长度  
  44.             InputStream is = connection.getInputStream();  
  45.             if (length != -1) {  
  46.                 byte[] data = new byte[length];  
  47.                 byte[] temp = new byte[512];  
  48.                 int readLen = 0;  
  49.                 int destPos = 0;  
  50.                 while ((readLen = is.read(temp)) > 0) {  
  51.                     System.arraycopy(temp, 0, data, destPos, readLen);  
  52.                     destPos += readLen;  
  53.                 }  
  54.                 String result = new String(data, "UTF-8"); // utf-8编码  
  55.                 System.out.println(result);  
  56.                 return result;  
  57.             }  
  58.         } catch (IOException e) {  
  59.             // TODO Auto-generated catch block  
  60.             e.printStackTrace();  
  61.         }  
  62.         return "error"// 自定义错误信息  
  63.     }  
  64.   
  65.     public static void main(String[] args) {  
  66.         post(url, params);  
  67.     }  
  68.   
  69. }