android客户端和struts框架之间的通信

android客户端和struts框架使用json数据通信很方便。参考了网上的一些资料和博客

struts.xml文件一定要注意小心:今天因为粗心浪费了不少时间。。

<package name="struts2" extends="json-default" namespace="/">一定不要写成

<package name="struts2" extends="struts-default" namespace="/">android客户端得json数据。服务器端:

其中一个action配置如:

<action name="returnGroupList" class="flow.com.cn.action.GroupPurchaseAction" method="returnGroupPurchaseInfoList">
           <result name="success" type="json"> 
           </result>
        </action>

服务器端其他的和一样,返回单个实体对象和实体列表没有区别。

json返回结果类型,那么这个响应结果不需要返回给任何视图层,JSON会将Action里的状态信息序列化为JSON指定格式的数据,并将该数据返回。

<result name="success" type="json">
只要为Action指定类型为json返回结果类型,那么这个响应结果不需要返回给任何视图层,JSON会将Action里的状态信息序列化为JSON指定格式的数据,并将该数据返回
           <param name="includeProperties"> 
                    flowinfo\.id,flowinfo\.monthusedflow,flowinfo\.dayusedflow 
           </param> 

<result>

服务器端接收android客户端传递过来的数据其中一个插入方法

public Boolean insertFeedbackInfo(FeedbackInfo feedback)throws Throwable{
        // TODO Auto-generated method stub
        String sql="insert into feedbackinfo(content,time)values('"+feedback.getContent()+"','"+feedback.getTime()+"')";
        Connection conn=null;
        PreparedStatement ps=null;
        conn=(Connection) DBUtilsC3P0.getInstance().getConnection();
        try {
            ps=conn.prepareStatement(sql);
            if(ps.execute())
                return true;
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            ps.close();
            conn.close();
        }
       
        return false;
    }

struts.xml中配置为:  

  <action name="insertFeedbackInfo" class="flow.com.cn.action.FeedbackInfoAction" method="insertFeedbackInfo">
        <result name="success">/index.jsp</result>
   </action>

android客户端:

@Override
    public Boolean insertFeedbackInfo(String content,String time) {
        //192.168.1.122:8089为本机IP地址,不能用localhost代替
          String path = "http://192.168.1.122:8089/FlowServer/insertFeedbackInfo.action";
//          http://192.168.1.122:8089/Strust2Json/csdn/listNewsGoods.action
          Map<String,String> params = new HashMap<String,String>();
          params.put("content", content);
          params.put("time",time);
          Boolean res=false;
        try {
            res=sendHttpClientPOSTRequest(path,params,"UTF-8");
            System.out.println(res+"..............");
            return res;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
           
        }
    return res;
           
        }

httpclient请求方法

 private  boolean sendHttpClientPOSTRequest(String path,
               Map<String, String> params, String encoding) throws Exception {
              List<NameValuePair> pairs = new ArrayList<NameValuePair>();//存放请求参数
             
              for(Map.Entry<String, String> entry:params.entrySet()){
               pairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
              }
              //防止客户端传递过去的参数发生乱码,需要对此重新编码成UTF-8
              UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs,encoding);
              HttpPost httpPost = new HttpPost(path);
              httpPost.setEntity(entity);
              DefaultHttpClient client = new DefaultHttpClient();
              HttpResponse response = client.execute(httpPost);
              if(response.getStatusLine().getStatusCode()==200){
               return true;
              }
              return false;
             }

/**
      * 发送post请求
      * @param path 请求路径
      * @param params 请求参数
      * @param encoding 编码
      * @return 请求是否成功
      */
     private static boolean sendPOSTRequest(String path,
       Map<String, String> params, String encoding) throws Exception{
      StringBuilder data = new StringBuilder(path);
      for(Map.Entry<String, String> entry:params.entrySet()){
       data.append(entry.getKey()).append("=");
       //防止客户端传递过去的参数发生乱码,需要对此重新编码成UTF-8
       data.append(URLEncoder.encode(entry.getValue(),encoding));
       data.append("&");
      }
     
      data.deleteCharAt(data.length() - 1);
     
      byte[] entity = data.toString().getBytes();//得到实体数据
      HttpURLConnection conn = (HttpURLConnection) new URL(path).openConnection();
      conn.setConnectTimeout(5000);
      conn.setRequestMethod("POST");
     
      conn.setDoOutput(true);//设置为允许对外输出数据
     
      conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
      conn.setRequestProperty("Content-Length", String.valueOf(entity.length));
     
      OutputStream outStream = conn.getOutputStream();
      outStream.write(entity);//写到缓存
     
      if(conn.getResponseCode()==200){//只有取得服务器返回的http协议的任何一个属性时才能把请求发送出去
       return true;
      }
     
      return false;
     }

     /**
      * 发送GET请求
      * @param path 请求路径
      * @param params 请求参数
      * @return 请求是否成功
      * @throws Exception
      */
     private static boolean sendGETRequest(String path,
       Map<String, String> params,String encoding) throws Exception {
      StringBuilder url = new StringBuilder(path);
      url.append("?");
      for(Map.Entry<String, String> entry:params.entrySet()){
       url.append(entry.getKey()).append("=");
       //get方式请求参数时对参数进行utf-8编码,URLEncoder
       //防止客户端传递过去的参数发生乱码,需要对此重新编码成UTF-8
       url.append(URLEncoder.encode(entry.getValue(), encoding));
       url.append("&");
      }
      url.deleteCharAt(url.length()-1);
      HttpURLConnection conn = (HttpURLConnection) new URL(url.toString()).openConnection();
      conn.setConnectTimeout(5000);
      conn.setRequestMethod("GET");
      if(conn.getResponseCode() == 200){
       return true;
      }
      return false;
     }

android客户端要导入gson.jar包。

猜你喜欢

转载自i-feng.iteye.com/blog/1698846
今日推荐