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         }            
  • 相关阅读:
    CLR via C#
    一些写英文简历的词汇
    组合与组合数
    A lowlevel Look at the ASP.NET Architecture
    \r与\n的区别,\r\n与\n或\r的区别(C语言/C#)
    Canvas lineWidth 属性 【每日一段代码18】
    程序员三大世界观 如何看待HTML5
    Canvas运用样式与颜色fillStyle【每日一段代码15】
    Canvas绘制路径:贝塞尔曲线【每日一段代码12】
    Canvas绘制弧形【每日一段代码10】
  • 原文地址:https://www.cnblogs.com/oldzhang1222/p/8250805.html
Copyright © 2011-2022 走看看