我的漫漫程序之旅

专注于JavaWeb开发
随笔 - 39, 文章 - 310, 评论 - 411, 引用 - 0
数据加载中……

HttpURLConnection请求数据流的写入(write)和读取(read)

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(相当于被请求的服务器):

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:您已经请求成功,这是响应数据
!


源码下载:here

posted on 2008-12-20 11:19 々上善若水々 阅读(19083) 评论(1)  编辑  收藏

评论

# re: HttpURLConnection请求数据流的写入(write)和读取(read)  回复  更多评论   

恩,不错
2008-12-20 22:58 | @beyondwcm

只有注册用户登录后才能发表评论。


网站导航: