http形式的webservice

  1 import java.io.ByteArrayOutputStream;
  2 import java.io.IOException;
  3 import java.io.InputStream;
  4 import java.io.OutputStream;
  5 import java.io.UnsupportedEncodingException;
  6 import java.net.HttpURLConnection;
  7 import java.net.MalformedURLException;
  8 import java.net.URL;
  9 import java.net.URLEncoder;
 10 import java.util.HashMap;
 11 import java.util.Map;
 12 
 13 import com.google.gson.Gson;
 14 /**
 15  * http格式的webservice主要工具类
 16  * @author Administrator
 17  *
 18  */
 19 public class HttpWebServiceUtils {
 20 
 21     /*
 22      * params 填写的URL的参数 encode 字节编码
 23      */
 24     public static String sendPostMessage(Map<String, String> params,String encode,String path) {
 25         URL url = null;
 26         try {
 27             url = new URL(path);
 28         } catch (MalformedURLException e1) {
 29             e1.printStackTrace();
 30             return "";
 31         };
 32 
 33         StringBuffer stringBuffer = new StringBuffer();
 34 
 35         if (params != null && !params.isEmpty()) {
 36             for (Map.Entry<String, String> entry : params.entrySet()) {
 37                 try {
 38                     stringBuffer
 39                             .append(entry.getKey())
 40                             .append("=")
 41                             .append(URLEncoder.encode(entry.getValue(), encode))
 42                             .append("&");
 43                 } catch (UnsupportedEncodingException e) {
 44                     e.printStackTrace();
 45                     return "";
 46                 }
 47             }
 48             //删掉最后一个 & 字符
 49             stringBuffer.deleteCharAt(stringBuffer.length() - 1);
 50             System.out.println("传递的所有参数信息:" + stringBuffer.toString());
 51             HttpURLConnection httpURLConnection = null;
 52             try {
 53                 httpURLConnection = (HttpURLConnection) url.openConnection();
 54                 httpURLConnection.setConnectTimeout(3000);
 55                 httpURLConnection.setDoInput(true);// 从服务器获取数据
 56                 httpURLConnection.setDoOutput(true);// 向服务器写入数据
 57 
 58                 //获得上传信息的字节大小及长度
 59                 byte[] mydata = stringBuffer.toString().getBytes();
 60                 //设置请求体的类型
 61                 httpURLConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
 62                 httpURLConnection.setRequestProperty("Content-Lenth",String.valueOf(mydata.length));
 63 
 64                 //获得输出流,向服务器输出数据
 65                 OutputStream outputStream = (OutputStream) httpURLConnection.getOutputStream();
 66                 outputStream.write(mydata);
 67                 outputStream.flush();// 强制把缓冲区的数据写入到文件并清空缓冲区
 68                 outputStream.close();// 关闭连接
 69                 //获得服务器响应的结果和状态码
 70                 int responseCode = httpURLConnection.getResponseCode();
 71                 if (responseCode == 200) {
 72                     //获得输入流,从服务器端获得数据
 73                     InputStream inputStream = (InputStream) httpURLConnection.getInputStream();
 74                     return (changeInputStream(inputStream, encode));
 75                 }
 76             } catch (IOException e) {
 77                 e.printStackTrace();
 78                 return "";
 79             } finally {
 80                 if (httpURLConnection != null) {
 81                     httpURLConnection.disconnect();
 82                 }
 83             }
 84         }
 85         return "";
 86     }
 87 
 88     /*
 89      *把从输入流InputStream按指定编码格式encode变成字符串String
 90      */
 91     public static String changeInputStream(InputStream inputStream,String encode) {
 92 
 93         // ByteArrayOutputStream 一般叫做内存流
 94         ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
 95         byte[] data = new byte[1024];
 96         int len = 0;
 97         String result = "";
 98         if (inputStream != null) {
 99 
100             try {
101                 while ((len = inputStream.read(data)) != -1) {
102                     byteArrayOutputStream.write(data, 0, len);
103                 }
104                 result = new String(byteArrayOutputStream.toByteArray(), encode);
105 
106             } catch (IOException e) {
107                 e.printStackTrace();
108             }
109         }
110         return result;
111     }
112 
113     public static void main(String[] args) {
114         //http://localhost:8088/online.video/account/account!httpAddAccount.do
115         //?account.userId=123&account.password=2&account.name=2&account.sex=1&account.type=0&account.phone=2
116         //params是请求的参数的map形式
117         Map<String, String> params = new HashMap<String, String>();
118         params.put("account.userId", "1234");
119         params.put("account.password", "123");
120         params.put("account.name", "张三");
121         params.put("account.sex", "0");
122         params.put("account.type", "0");
123         params.put("account.phone", "13888888888");
124         //发送请求,得到响应结果
125         String result = HttpWebServiceUtils.sendPostMessage(params, "UTF-8", 
126                 "http://localhost:8088/online.video/account/account!httpAddAccount.do");
127         System.out.println(result);
128         Gson gson = new Gson();
129         
130         /*
131          * 下面是对json格式的结果做json解析,用的是gson
132          */
133         
134         /*GsonResult gsonResult = gson.fromJson(result, GsonResult.class);
135         System.out.println(gsonResult.getSuccess());*/
136     }
137 }

仿main方法的调用就可以了,接口方法就是在Controller里写一个这个请求的方法

posted @ 2018-01-29 14:51  admin_jh  阅读(421)  评论(0编辑  收藏  举报