hk8lo 发表于 2015-9-1 09:40:21

Java利用Tomcat作为服务器与Android的Http通信

在android手机端写了个程序,功能是完成一个两位数的运算。这个运算过程是在java后台完成的,android端利用Http通信把相关的参数传过去,后台经过计算把结果返回给客户端。

    贴出客户端部分代码

//点击按钮,把参数打包成json格式发送到后台

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public void send(View v){
    String str1 = tv1.getText().toString();
    String str2 = tv2.getText().toString();
    if(str1.equals("") || str2.equals("")){
      Toast.makeText(MainActivity.this, "参数不能为空!", Toast.LENGTH_LONG).show();
      return;
    }
    final int a = Integer.parseInt(str1);
    final int b = Integer.parseInt(str2);
    new Thread(new Runnable() {
    @Override
      public void run() {
            JSONObject jsonObject = new JSONObject();
            JSONArray jsonArray = new JSONArray();
      try {
            jsonObject.put("parm1", a + "");
            jsonObject.put("parm2", b + "");
            jsonArray.put(jsonObject);
      } catch (JSONException e) {
            e.printStackTrace();
      }
result = new HttpUtils().getDataFromServer(Consant.url, jsonArray.toString(), method, a, b);
mHandler.sendEmptyMessage(0x0001);
}
}).start();
}





//在这里我同时进行两种方式的参数传递
//一个是setRequestProperty(key, value);
//另一个是常用的输出流

/**
* 根据手机号从服务器获取相关信息
* 从服务器上获取指定的内容-POST
*
*/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
public String getDataFromServer(String svrUrl, String ParamStr, String type, int a, int b) {
try {
    // 转成指定格式
    byte[] requestData = ParamStr.getBytes("UTF-8");
    HttpURLConnection conn = null;
    DataOutputStream outStream = null;
    String MULTIPART_FORM_DATA = "multipart/form-data";
    // 构造一个post请求的http头
    URL url = new URL(svrUrl); // 服务器地址
    conn = (HttpURLConnection) url.openConnection();
    conn.setDoInput(true); // 允许输入
    conn.setDoOutput(true); // 允许输出
    conn.setUseCaches(false); // 不使用caches
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Connection", "Keep-Alive");
    conn.setRequestProperty("Content-Type", MULTIPART_FORM_DATA);
    conn.setRequestProperty("Content-Length", Long.toString(requestData.length));
    conn.setRequestProperty("method", type);
    conn.setRequestProperty("one", a + "");
    conn.setRequestProperty("two", b + "");
    // 请求参数内容, 获取输出到网络的连接流对象
    outStream = new DataOutputStream(conn.getOutputStream());
    outStream.write(requestData, 0, requestData.length);
    outStream.flush();
    outStream.close();
    ByteArrayOutputStream outStream2 = new ByteArrayOutputStream();
    int cah = conn.getResponseCode();
    if (cah != 200) {
      Log.v("data", "服务器响应错误代码:" + cah);
      return "0";
    }else if(cah == 200){
      Log.v("data", "服务器响应成功:" + cah);
    }
    InputStream inputStream = conn.getInputStream();
    int len = 0;
    byte[] data = new byte;
    while ((len = inputStream.read(data)) != -1) {
      outStream2.write(data, 0, len);
    }
    outStream2.close();
    inputStream.close();
    String responseStr = new String(outStream2.toByteArray());
    Log.v("data", "data = " + responseStr);
    return responseStr;
} catch (Exception e) {
    return "";
}
}






接下来看看java服务端处理
//在java web项目中创建了一个Servlet用来接收客户端发送的数据
//因为客户端用的是Post方法,所以我们在Servlet的Post方法中对数据进行处理
//客户端用了两种方式传参数,在后台我们仍然用两种方式取参数

//第一种 String method = request.getHeader("method").toString();
//第二种则是输出流来取值了

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    System.out.println("---------00000000----");
    int a;
    int b;
    int res = 0;
    double res2 = 0;
    String result;
    String method = request.getHeader("method").toString();
    String str1 = request.getHeader("one").toString();
    String str2 = request.getHeader("two").toString();
    System.out.println(method + "/" + str1 + "/" + str2);
    try{
      a = Integer.parseInt(str1);
      b = Integer.parseInt(str2);
    }catch(Exception e){
      response.getWriter().append(e.getMessage() + "");
      return;
    }
    if(method.equals("+")){
      res = new Utils().plus(a, b);
    }else if(method.equals("-")){
      res = new Utils().minus(a, b);
    }else if(method.equals("*")){
      res = new Utils().multy(a, b);
    }else if(method.equals("/")){
      res2 = new Utils().trad(a, b);
    }
    if(method.equals("/")){
      result = res2 + "";
    }else{
      result = res + "";
    }
      response.setCharacterEncoding("utf-8");
      response.getWriter().append(result + "");
      getData(request);
}





1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public String getData(HttpServletRequest req){
    String result = null;
    try {
      //包装request的输入流
      BufferedReader br = new BufferedReader(
      new InputStreamReader((ServletInputStream) req.getInputStream(), "utf-8"));
      //缓冲字符
      StringBuffer sb=new StringBuffer("");
      String line;
      while((line=br.readLine())!=null){
            sb.append(line);
      }
      br.close();//关闭缓冲流
      result=sb.toString();//转换成字符
      System.out.println("result = " + result);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return result;
}




另外注意编码格式问题,在客户端用的是utf-8编码,我们在服务端仍然要用utf-8编码,否则出现中文乱码现象。

//电脑的ip地址
//手机和电脑处于同一个局域网内,所以可以通过ip访问内网Tomcat
public static String url = "http://192.168.1.122:8080/MathTest/action?";




百度云附件:客户端与后台源码.rar   


页: [1]
查看完整版本: Java利用Tomcat作为服务器与Android的Http通信