zoukankan      html  css  js  c++  java
  • [JAVA]HTTP请求应答作输入输出

    请求(需要发送数据给别人):

    URL url = new URL("需要请求的URL连接");

    HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();

    // POSTGET方式通信

    conn.setRequestMethod("POST");

    // 设置连接超时时间

    httpConnection.setConnectTimeout(this.timeOut * 1000);

    // User-Agent

    httpConnection.setRequestProperty("User-Agent",

    "Mozilla/4.0 (compatible; MSIE 6.0; Windows XP)");

    // 不使用缓存

    httpConnection.setUseCaches(false);

    // 允许输入输出

    httpConnection.setDoInput(true);

    httpConnection.setDoOutput(true);

    // Content-Type

    httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    // 取得输出流

    BufferedOutputStream out = new BufferedOutputStream(conn.getOutputStream());

    // 长度以1KB为单位进行写

    final int len = 1024;

    // 将要输出的字符通过流做输出

    String postData = "需要POST出去的数据";

    byte[] outData = postData.getBytes(this.charset);

    int dataLen = outData.length;

    int off = 0;

    // 1KB为单位写

    while (off < dataLen) {

    if (len >= dataLen) {

    out.write(outData, off, dataLen);

    } else {

    out.write(outData, off, len);

    }

    // 刷新缓冲区

    out.flush();

    off += len;

    dataLen -= len;

    }

    // 关闭流

    out.close();

    // 取得应答码

    int respCode = conn.getResponseCode();

    // 取得返回的输入流

    InputStream inputStream = conn.getInputStream();

    接收(接收请求数据并应答):

    // 取得输入流

    InputStream in = request.getInputStream();

    // 使用Reader取得输入流数据

    BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8"));

    // Reader转成字符串

    String temp;

    StringBuffer sb = new StringBuffer();

    while (null != (temp = br.readLine())) {

    sb.append(temp);

    }

    // 取得最终收到的字符串

    String originalReturnData = sb.toString();

         // 应答给请求方的数据

    String responseString = "收到请求之后应答的数据";

    // 取得输出器

    PrintWriter out = response.getWriter();

    // 直接输出

    out.println(responseString);

    // 刷新输出

    out.flush();

    // 关闭输出

    out.close();

  • 相关阅读:
    HTML 块级、内联、内联块级元素(转)
    CSS margin-top父元素下落
    JS 窗口resize避免触发多次
    ASP.NET 自制免费.NET代码生成器KevinCodeBuilder
    Plugin 中国省市选择插件
    Git 常用命令(转)
    JS Regex正则表达式的使用(转)
    Git 详细中文安装教程(转)
    业务逻辑中的测试总结(一)----比值类需求测试分解
    python学习笔记系列----(四)模块
  • 原文地址:https://www.cnblogs.com/garinzhang/p/http_request_response_inputStream_outputStream.html
Copyright © 2011-2022 走看看