这时,可以考虑用HTTP代替web service进行通信,因为web service传输必须是字符串流,也就是说所有的东西(包括java对象,二进制文件)都要经过BASE64编码后传输,接收端再用BASE64解码。这个过程是比较费时间和精力的,因为BASE64编码将使得传输的内容大小扩大了一半,特别是传输大量数据时,可能会出现性能瓶颈。而HTTP可以直接读二进制字节流,性能会好许多,因此,通常的做法是用HTTP传输代替出现瓶颈的地方.
点击下载后解压即可获得所需要的3个jar包:
1、commons-httpclient-3.0.1.jar
2、commons-logging-1.1.jar
3、commons-codec-1.3.jar
本例为获得百度主页的信息并将其生成Test_baidu.html。
当然也可以直接获得文件。
GetSample.java
import java.io.*;
import java.io.IOException;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
public class GetSample
{
public static void main(String[] args)
{
//构造HttpClient的实例
HttpClient httpClient = new HttpClient();
//创建GET方法的实例
GetMethod getMethod = new GetMethod("http://www.baidu.com");
//GetMethod getMethod = new GetMethod("http://10.164.80.52/dav/5000/moban.rar");
//使用系统提供的默认的恢复策略
getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler());
try
{
//执行getMethod
int statusCode = httpClient.executeMethod(getMethod);
if (statusCode != HttpStatus.SC_OK)
{
System.err.println("Method failed: " + getMethod.getStatusLine());
}
//读取内容
byte[] responseBody = getMethod.getResponseBody();
String serverfile = "d:\\Test_baidu.html";
//String serverfile = "d:\\moban.rar";
OutputStream serverout = new FileOutputStream(serverfile);
serverout.write(responseBody);
serverout.flush();
serverout.close();
//处理内容
//System.out.println(new String(responseBody));
System.out.println("OK!");
}
catch (HttpException e)
{
//发生致命的异常,可能是协议不对或者返回的内容有问题
System.out.println("Please check your provided http address!");
e.printStackTrace();
}
catch (IOException e)
{
//发生网络异常
e.printStackTrace();
}
finally
{
//释放连接
getMethod.releaseConnection();
}
}
}