httpurlconnection请求数据流的写入(write)和读取(read) -凯发k8网页登录

专注于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 
= ""1.0\" encoding=\"utf-8\"?>爱心天使26";

        url url 
= null;
        httpurlconnection httpconn 
= null;
        outputstream output 
= null;
        outputstreamwriter outr 
= null;

        url 
= new ;
        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>26age>page>
code 
200
ok
response:您已经请求成功,这是响应数据
!


源码下载:

posted on 2008-12-20 11:19 々上善若水々 阅读(18934) 评论(1)    

# re: httpurlconnection请求数据流的写入(write)和读取(read)  回复     

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

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


网站导航:
              
 
网站地图