URLConnection类给应用 程序 和web资源之间架设起了通信的桥梁,这些web资源通常是通过url来标记的,本文将讲述如何使用HttpURLConnection来访问web页面(发送数据流)和读取数据流。

在Servlet中对于需要用post方式(get会暴露参数)写入参数的时候就用到了HttpURLConnection.

请求的Servlet,也可以写入main方法中进行测试package com;

import 
JAVA
.io.BufferedReader;


import java.io.IOException;


import java.io.InputStreamReader;


import java.io.OutputStream;


import java.io.OutputStreamWriter;


import java.net.HttpURLConnection;


import java.net.URL;

import javax.servlet.ServletException;


import javax.servlet.http.HttpServlet;


import javax.servlet.http.HttpServletRequest;


import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("serial")


public class IOServlet extends HttpServlet


{


    /**


     * 对于主动请求其它接口的参数流写入(POST方式)


     */


    public void doGet(HttpServletRequest request, HttpServletResponse response)


            throws ServletException, IOException


    {


        System.out.println("begin send");


        String inputParam = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><page><username>爱心天使</usernaem><age>26</age></page>";

URL url = null;


        HttpURLConnection httpConn = null;


        OutputStream output = null;


        OutputStreamWriter outr = null;

url = new URL("http://127.0.0.1:8888/iotest/ReadServlet");


        httpConn = (HttpURLConnection) url.openConnection();


        HttpURLConnection.setFollowRedirects(true);


        httpConn.setDoOutput(true);


        httpConn.setRequestMethod("POST");


        httpConn.setRequestProperty("Content-Type", "text/xml");


        httpConn.connect();


        output = httpConn.getOutputStream();


        outr = new OutputStreamWriter(output);


        // 写入请求参数


        outr.write(inputParam.toString().toCharArray(), 0, inputParam


                .toString().length());


        outr.flush();


        outr.close();


        System.out.println("send ok");


        int code = httpConn.getResponseCode();


        System.out.println("code " + code);


        System.out.println(httpConn.getResponseMessage());


        


        //读取响应内容


        String sCurrentLine = ""; 


        String sTotalString = ""; 


        if (code == 200)


        {


            java.io.InputStream is = httpConn.getInputStream();


            BufferedReader reader = new BufferedReader(


                    new InputStreamReader(is));


            while ((sCurrentLine = reader.readLine()) != null)


                if (sCurrentLine.length() > 0)


                    sTotalString = sTotalString + sCurrentLine.trim();


        } else


        {


            sTotalString = "远程服务器连接失败,错误代码:" + code;

}


        System.out.println("response:" + sTotalString);

}

public void doPost(HttpServletRequest request, HttpServletResponse response)


            throws ServletException, IOException


    {


        this.doGet(request, response);


    }

}

ReadServlet(相当于被请求的服务器):http://www.shengshiyouxi.com


package com;

import java.io.IOException;


import java.io.PrintWriter;


import javax.servlet.ServletException;


import javax.servlet.ServletInputStream;


import javax.servlet.http.HttpServlet;


import javax.servlet.http.HttpServletRequest;


import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("serial")


public class ReadServlet extends HttpServlet


{

public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException


    {


        System.out.println("begin read");


        ServletInputStream inStream = request.getInputStream(); // 取HTTP请求流


        int size = request.getContentLength(); // 取HTTP请求流长度


        byte[] buffer = new byte[size]; // 用于缓存每次读取的数据 


        byte[] in_b = new byte[size]; // 用于存放结果的数组


        int count = 0;


        int rbyte = 0;


        // 循环读取 


        while (count < size)


        { 


            rbyte = inStream.read(buffer); // 每次实际读取长度存于rbyte中 sflj


            for (int i = 0; i < rbyte; i++)


            {


                in_b[count + i] = buffer[i];


            }


            count += rbyte;


        }


        System.out.println("result:" + new String(in_b,0,in_b.length));


        


        response.setContentType("text/
html
");


        //注意响应中文数据时要设置


        response.setCharacterEncoding("GBK");


        PrintWriter out = response.getWriter();


        //回与响应数据


        out.write("您已经请求成功,这是响应数据!");


    }


    


    public void doPost(HttpServletRequest request, HttpServletResponse response)


            throws ServletException, IOException


    {


        this.doGet(request, response);


    }

}

打开页面:http://localhost:8888/iotest/IOServlet

你会在后台看到如下输出说明你已经成功了:begin send


send ok


begin read


result:<?xml version="1.0" encoding="UTF-8"?><page><username>爱心天使</usernaem><age>26</age></page>


code 200


OK


response:您已经请求成功,这是响应数据!

HttpURLConnection请求数据流的写入(write)和读取(read)的更多相关文章

  1. HttpURLConnection请求

    方法调用: //测试 public static void main(String[] args) { Map map = new HashMap(); map.put("type" ...

  2. Android使用HttpUrlConnection请求服务器发送数据详解

    HttpUrlConnection是java内置的api,在java.net包下,那么,它请求网络同样也有get请求和post请求两种方式.最常用的Http请求无非是get和post,get请求可以获 ...

  3. 使用PHP文件锁写一个多个请求同时并发写入一个文件,要求不脏读、数据不丢失

    使用PHP文件锁写一个多个请求同时并发写入一个文件,要求不脏读.数据不丢失. //并发文件操作 function filehandle($filename,$data){ $start = 0; $e ...

  4. Javascript写入txt和读取txt文件的方法

    文章主要介绍了Javascript写入txt和读取txt文件的方法,需要的朋友可以参考下1. 写入 FileSystemObject可以将文件翻译成文件流. 第一步: 例: 复制代码 代码如下: Va ...

  5. 解决Fiddler不能监听Java HttpURLConnection请求的方法

    在默认情况下,Fiddler不能监听Java HttpURLConnection请求.究其原因,Java的网络通信协议栈可能浏览器的通信协议栈略有区别,Fiddler监听Http请求的原理是 在应用程 ...

  6. ELK之logstash收集日志写入redis及读取redis

    logstash->redis->logstash->elasticsearch 1.安装部署redis cd /usr/local/src wget http://download ...

  7. 使用Fiddler监听java HttpURLConnection请求

    使用Fiddler监听java HttpURLConnection请求

  8. js的cookie写入存储与读取

    js的cookie写入存储与读取 在路径url截取需要的数据,存储到cookie里,读取成功并实现跳转. //写cookies 过期时间 2小时后 function setCookie(c_name, ...

  9. 分享自己配置的HttpURLConnection请求数据工具类

    >>该工具类传入string类型url返回string类型获取结果import java.io.BufferedReader;import java.io.InputStream;impo ...

随机推荐

  1. DM8168硬件平台

    DM8168硬件平台  作者:Marvin_wu TMS320DM8168是一款多核SoC,它集成了包含ARM Cortex A8.DSP C674X+.M3 VIDEO.M3 VPSS等处理器.DS ...

  2. C/C++ Resources

    C/C++ Resources 一.C/C++相关资源 语言标准及文档● ISO C99http://www.open-std.org/JTC1/SC22/WG14/www/docs/n1124.pd ...

  3. 基础知识(3)- Java的基本程序设计结构

    3.1 一个简单的Java应用程序 3.2 注释 3.3 数据类型  3.3.1 整型  3.3.2 浮点类型  3.3.3 char类型  3.3.4 boolean类型 3.4 变量  3.4.1 ...

  4. air ios 输入遮挡问题

    <!-- Adobe AIR Application Descriptor File Template. Specifies parameters for identifying, instal ...

  5. wamp环境中mysql更改root密码

    集成的wamp环境命令不好使,在phpmyadmin中更改密码 权限——root用户修改,执行 然后,你会发现你不能用phpmyadmin登陆了修改下phpmyadmin里面对应的密码就可以了将php ...

  6. [Windows Phone]模仿魔兽3技能按钮SkillButton

    简介: 模仿魔兽3技能按钮,带CD效果.使用的时候可以当做普通按钮使用,同时也支持Binding. 音效紧耦合在控件内部,因为控件本身目的就是模拟魔兽3的技能按钮,所以不考虑音效的扩展. Demo结构 ...

  7. ssh-copy-id -i ~/.ssh/id_rsa.pub admin@172.17.42.66

    ssh-copy-id -i ~/.ssh/id_rsa.pub admin@172.17.42.66

  8. Threejs 的场景查看 - 几个交互事件库助你方便查看场景

    Threejs 的场景查看 - 几个交互事件库助你方便查看场景 太阳火神的漂亮人生 (http://blog.csdn.net/opengl_es) 本文遵循"署名-非商业用途-保持一致&q ...

  9. 解决SQL查询总是超时已过期

    解决SQL查询总是超时已过期 .在WIN8里提示:OLE DB 或 ODBC 错误 : 查询超时已过期; HYT00 1.由于数据库设计问题造成SQL数据库新增数据时超时 症状:   Microso ...

  10. nginx fastcgi 自定义错误页面

    http{ fastcgi_intercept_errors on; error_page 404 /404.html; } fastcgi_intercept_errors on;必须设置 之后通过 ...