[Android实例] Android 实例SOCKET发送HTTP请求


       目的:客户端用socket连接web服务器发送http请求,访问一个Servlet /service .并接收servlet的相应数据。
       我客户端代码可以访问到servlet可是servlet用request.getPrameter(“data”) 取不到请求内容.
       请指点:代码如下

java代码:
  1. public class Client {
  2. public static void main(String[] arg) {
  3. Socket socket;
  4. try {
  5. socket = new Socket(“10.20.64.203″, 7001);
  6. OutputStream os = socket.getOutputStream();
  7. InputStream ins = socket.getInputStream();
  8. String data= getXmlString();
  9. StringBuffer sb = new StringBuffer();
  10. sb.append(“POST /service HTTP/1.1\r\n”);// 注意\r\n为回车换行
  11. sb.append(“Accept-Language: zh-cn\r\n”);
  12. sb.append(“Connection: Keep-Alive\r\n”);
  13. sb.append(“Host:localhost\r\n”);
  14. sb.append(“Content-Length:11\r\n”);
  15. sb.append(“\r\n”);
  16. sb.append(“data=abc\r\n”);
  17. sb.append(“\r\n”); 

  18. // 接收Web服务器返回HTTP响应包
  19. os.write(sb.toString().getBytes());
  20. os.flush();
  21. byte[] b = new byte[1000];
  22. ins.read(b); //读取http头
  23. InputStreamReader ireader = new InputStreamReader(ins);
  24. java.io.BufferedReader reader = new java.io.BufferedReader(ireader);
  25. String s = reader.readLine(); //读取内容
  26. System.out.println(“response:”+s);
  27. System.out.println(reader.readLine());
  28. System.out.println(reader.readLine());
  29. System.out.println(reader.readLine());
  30. System.out.println(reader.readLine());
  31. System.out.println(reader.readLine());
  32. System.out.println(reader.readLine()); 

  33. } catch (UnknownHostException e) {
  34. e.printStackTrace();
  35. } catch (IOException e) {
  36. e.printStackTrace();
  37. }
  38. }
复制代码

你可能感兴趣的:(android,servlet,socket,String,byte,web服务)