zoukankan      html  css  js  c++  java
  • 用HttpURLConnection来完成HTTP发送报文接收报文!

     1 public  String sendMsg(String url, byte[] PostData) {
     2         String content = null;
     3         URL urls = null;
     4         try {
     5         urls = new URL(url);
     6         HttpURLConnection httpURLConnection = (HttpURLConnection) urls .openConnection();
     7          // 设置连接时间
     8         httpURLConnection.setConnectTimeout(3000);
     9         // 打开输入流,以便从服务器获取数据
    10         httpURLConnection.setDoInput(true);
    11         // 打开输出流,以便向服务器提交数据
    12         httpURLConnection.setDoOutput(true);
    13          // 设置以POST方式提交数据
    14         httpURLConnection.setRequestMethod("POST");
    15         // 使用POST不能使用缓存
    16         httpURLConnection.setUseCaches(false);
    17         // 设置请求的类型是文本类型
    18         httpURLConnection.setRequestProperty("Content-Type",
    19         "application/x-www-form-urlencoded");
    20         // 设置请求体的长度
    21         httpURLConnection.setRequestProperty("Content-Length",
    22         String.valueOf(PostData.length));
    23         // 获得输出流,向指定的Url写入数据
    24         OutputStream outputStream = httpURLConnection.getOutputStream();
    25         outputStream.write(PostData);
    26         int response = httpURLConnection.getResponseCode(); 
    27                 // 获得服务器响应码
    28         if (response == HttpURLConnection.HTTP_OK) {
    29         InputStream inputStream= httpURLConnection.getInputStream();
    30         BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "gbk"));
    31                         StringBuilder builder = new StringBuilder();
    32                         String line = null;
    33                         while ((line = reader.readLine()) != null) {
    34                             builder.append(line).append("
    ");
    35                         }
    36                         content = builder.toString();
    37                     }
    38         }catch (IOException e) {
    39         e.printStackTrace();
    40         }
    41         return content;
    42         }            
  • 相关阅读:
    获取web应用路径 // "/" 表示class 根目录
    C++ Knowledge series Inheritance & RTTI & Exception Handling
    ATL
    GCC & Maker
    NoSQL(Not Only SQL)
    ECMAScript Regex
    C++ Knowledge series Conversion & Constructor & Destructor
    Cloud Computing
    C++ Knowledge series STL & Const
    Java Knowledge series 7
  • 原文地址:https://www.cnblogs.com/oldzhang1222/p/8250805.html
Copyright © 2011-2022 走看看