日期:2014-05-20 浏览次数:20731 次
//客户端通过此方法与Servlet通信 public void inTurnServer(){ try{ String url = "http://localhost:8080/my/Test"; str = tfd.getString(); HttpConnection conn = (HttpConnection)Connector.open(url); // 设置请求类型为POST conn.setRequestMethod(HttpConnection.POST); // 设置一般的请求属性 conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("User-Agent", "Profile/MIDP-1.0 Configuration/CLDC-1.0"); conn.setRequestProperty("Content-Language", "en-US"); conn.setRequestProperty("Accept", "application/octet-stream"); conn.setRequestProperty("Connection", "close"); String info = "str"+str; // 转换显字节流 byte[] data = info.getBytes(); // 设置写入流的长度 conn.setRequestProperty("Content-Length", Integer .toString(data.length)); OutputStream os = conn.openOutputStream(); os.write(data); os.close(); // 得到Http响应代码 int rc = conn.getResponseCode(); // 正常响应 if (rc == HttpConnection.HTTP_OK) { // 构建输入流 DataInputStream dism = new DataInputStream(conn .openInputStream()); // 读取服务器返回的字节流 String result = dism.readUTF(); dism.close(); // 判断 if (result.equals("true")) { System.out.println("OK!"); } if (result.equals("false")) { System.out.println("ERROR!"); } } }catch(Exception ex){ ex.printStackTrace(); } /////////////////////////////////////////////////////////////////////////////////////
@Override//服务端Servlet protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String str = request.getParameter("str"); // 构建输出流 ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(baos); if("A".equals(str)){ dos.writeUTF("true"); }else{ dos.writeUTF("false"); } byte[] data1 = baos.toByteArray(); // 设置服务器响应参数 response.setStatus(HttpServletResponse.SC_OK); response.setContentLength(data1.length); response.setContentType("application/octet-stream"); OutputStream os = response.getOutputStream(); os.write(data1); os.close(); }