zoukankan      html  css  js  c++  java
  • HttpUrlConnection访问Servlet进行数据传输

    建立一个URL url = new URL("location");

    建立 httpurlconnection :HttpUrlConnection httpConn = (HttpUrlConnection)url.openConnection();//强制类型转换

    String requestString = "什么gui";
    设置连接属性:
    httpConn.setDoOutPut(true); //使用URL进行输出
    httpConn.setDoInPut(true); //使用URL进行输入
    httpConn.setUseCaches(false); //忽略使用缓存
    httpConn.setRequestMethod("Post"); //默认情况是Get方法

    设置请求属性:
    byte[] requestStringBytes = requestString.getBytes("UTF-8");
    httpConn.setRequestProperty("Content-length", "" + requestStringBytes.length);
    httpConn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
    httpConn.setRequestProperty("Connection", "Keep-Alive");// 维持长连接
    httpConn.setRequestProperty("Charset", "UTF-8");

    建立输出流,写入数据:
    httpConn.connect();
    DataOutputStream outputStream = new DataOutputStream(httpConn.getOutputStream());
    String content = "name="+ URLEncoder.encode(requestString,"utf-8");
    outputStream.writeBytes(content);
    outputStream.flush();
    outputStream.close();

    那么在Servlet端 获取数据的方式,
    String name = request.getParameter("name"); //这样就能获取到requestString 的字符串

  • 相关阅读:
    MyBatis学习记录02篇
    Mybatis学习记录01篇
    项目路径问题
    项目01-JavaWeb网上书城01之工具类
    面试篇01
    创建多线程的方式
    关于web.xml
    快捷键----快速生成未实现的方法
    自动化学习-Day03
    自动化学习-Day02
  • 原文地址:https://www.cnblogs.com/FakerWang/p/faker.html
Copyright © 2011-2022 走看看