REST风格WebService调用客户端

1. 客户端接口

package com.http.client;

/**
 * 
 * Http客户端接口
 * @author ypqiao
 *
 */
public interface HttpClient {

	/** 发送GET请求,返回 文本数据 **/
	public abstract String get(String urlStr) throws Exception;
	
	/** 发送GET请求,返回二进制数据  **/
	public abstract byte[] getByte(String urlStr) throws Exception;

	/** 发送POST请求,返回文本数据 **/
	public abstract String post(String urlStr, String params) throws Exception;
	
	

}


2. 客户端实现

package com.http.client;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 
 * Http客户端实现
 * @author ypqiao
 *
 */
public class HttpClientImpl implements HttpClient {
	
	protected int cach_size = 3*1024*1024;
	protected int con_timeout = 36000;
	protected int read_timeout = 30000;
	protected String charset = "UTF-8";
	
	
	public HttpClientImpl() {}
	
	/* (non-Javadoc)
	 * @see com.http.client.HttpClient#get(java.lang.String)
	 */
	@Override
	public String get(String urlStr) throws Exception{
		
		String response = null;
		
		URL url = null;
		HttpURLConnection con = null;
		BufferedReader ins = null;
		
		url = new URL(urlStr);
		
		con = (HttpURLConnection) url.openConnection();
		con.setConnectTimeout(con_timeout);
		con.setReadTimeout(read_timeout);
		con.connect();
		
		ins = new BufferedReader(
				new InputStreamReader(con.getInputStream()),cach_size);
		
		
		if( con.getResponseCode() == 200 ){
			
			String line = null;
			StringBuilder rspStr = new StringBuilder();
			
			while( (line = ins.readLine()) != null ){
				rspStr.append(line);
			}
			
			response = rspStr.toString();
		}
		else {
			throw 
			new HttpCommunicationException(con.getResponseCode(),
					con.getResponseMessage());
		}
		
		ins.close();
		con.disconnect();
	
		return response;
	}
	
	/* (non-Javadoc)
	 * @see com.http.client.HttpClient#post(java.lang.String, java.lang.String)
	 */
	@Override
	public String post(String urlStr,String params ) throws Exception {
		
		String response = null;
		
		URL url = null;
		HttpURLConnection con = null;
		BufferedReader ins = null;
		OutputStream ous = null;
		
		url = new URL(urlStr);
		
		con = (HttpURLConnection) url.openConnection();
		con.setConnectTimeout(con_timeout);
		con.setReadTimeout(read_timeout);
		con.setDoInput(true);
		con.setDoOutput(true);
		con.setRequestMethod("POST");
		con.setUseCaches(false);
		con.connect();
		
		ous = con.getOutputStream();
		ous.write(params.getBytes(charset));
		ous.flush();
		ous.close();

		ins = new BufferedReader(
				new InputStreamReader(con.getInputStream()),cach_size);
		
		if( con.getResponseCode() == 200 ){
			
			String line = null;
			StringBuilder rspStr = new StringBuilder();
			
			while( (line = ins.readLine()) != null ){
				rspStr.append(line);
			}
			
			response = rspStr.toString();
		}
		else {
			throw 
			new HttpCommunicationException(con.getResponseCode(),
					con.getResponseMessage());
		}
	
		ins.close();
		con.disconnect();
		
		return response;
	}

	/* (non-Javadoc)
	 * @see com.http.client.HttpClient#getByte(java.lang.String)
	 */
	@Override
	public byte[] getByte(String urlStr) throws Exception {
		
		byte[] response = null;

		URL url = null;
		HttpURLConnection con = null;
		BufferedInputStream ins = null;
		
		url = new URL(urlStr);
		
		con = (HttpURLConnection) url.openConnection();
		con.setConnectTimeout(con_timeout);
		con.setReadTimeout(read_timeout);
		con.connect();
		
		ins = new BufferedInputStream(con.getInputStream(),cach_size);
		
		
		if( con.getResponseCode() == 200 ){
			
			int b = 0;
			int index = 0;
			byte[] response_tmp = null;
			response = new byte[cach_size];
			while( (b=ins.read()) != -1 ){
				
				if( index > response.length - 1){
					
					response_tmp = response;
					response = new byte[response_tmp.length*2];
					for( int i=0; i<response_tmp.length; i++){
						response[i] = response_tmp[i];
					}
					
				}
				
				response[index] = (byte)b;
				index++;
			}
			
			response_tmp = response;
			response = new byte[index];
			for( int i=0; i<index; i++){
				response[i] = response_tmp[i];
			}
			
		}
		else {
			throw 
			new HttpCommunicationException(con.getResponseCode(),
					con.getResponseMessage());
		}
		
		ins.close();
		con.disconnect();
	
		return response;
	}
	
	
}


3. 客户端异常

package com.http.client;


/**
 * 
 * Http运行时通信异常
 * @author ypqiao
 *
 */
public class HttpCommunicationException extends RuntimeException {

	private static final long serialVersionUID = 1L;
	
	private int code;
	private String msg;
	
	public HttpCommunicationException( int code,String msg){
		this.code = code;
		this.msg = msg;
	}

	@Override
	public String toString() {
		return "返回码:"+code+"消息描述:"+msg;
	}

	public int getCode() {
		return code;
	}

	public void setCode(int code) {
		this.code = code;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}
}


4.测试

package com.http.client;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;

/**
 * 
 * Http客户端测试类
 * @author ypqiao
 *
 */
public class RestTest {

	
	public static void main(String[] args) throws Exception {
		
		/** 测试方法为调用REST风格的WebService **/
		
		HttpClient httpClient = new HttpClientImpl();
		
		// 发GET请求,返回文本数据(html/xml)
		System.out.println(httpClient.get("http://server.arcgisonline.com/arcgis/rest/services"));
		
		// 发GET请求,返回文本数据(json)
		System.out.println(httpClient.get("http://server.arcgisonline.com/arcgis/rest/services?f=json"));
		
		// 发送GET请求,返回二进制数据(image),存放路径为c:/
		byte[] bytes = httpClient.getByte("http://sampleserver1c.arcgisonline.com/arcgisoutput/_ags_map5e57267ff6fb4227a8f8685915856213.png");
		BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream( new File("c:/export.png")));
		out.write(bytes);
		out.flush();
		out.close();
		
		// 发送POST请求,返回文本数据
		System.out.println(httpClient.post("http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Specialty/ESRI_StateCityHighway_USA/MapServer/find", "searchText=New York&layers=1"));
		
	}
	
	
	

}


  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
WebService是一种基于Web协议进行通信的技术,它允许应用程序在网络上交换数据,而不需要考虑具体的平台或语言。WebService可以提供多种服务,例如获取数据、处理事务或执行特定的功能等。调用WebService可以使用多种方式,包括以下几种: 1. 使用SOAP协议调用WebService:SOAP(简单对象访问协议)是一种基于XML的协议,用于在网络上进行应用程序之间的通信。SOAP协议定义了如何打包和传输消息,以及如何使用Web服务的接口。通过SOAP协议调用WebService需要使用SOAP客户端,可以使用多种编程语言和框架创建。 2. 使用RESTful风格调用WebServiceREST(Representational State Transfer)是一种基于HTTP协议的Web服务架构风格,它提供了一种简单的、可扩展的机制来进行Web服务之间的通信。RESTful Web服务使用HTTP方法(例如GET、POST、PUT和DELETE)来执行各种操作,例如获取资源、更新资源、删除资源等。通过RESTful风格调用WebService需要使用HTTP客户端,可以使用多种编程语言和框架创建。 3. 使用Web API调用WebServiceWeb API(Web应用程序接口)是一组定义在Web服务器上的程序接口,用于访问Web服务或Web资源。Web API可以使用SOAP或RESTful协议进行通信,可以使用多种编程语言和框架创建。通过Web API调用WebService可以使用多种方式,例如HTTP客户端Web浏览器、Web表单等。 总的来说,调用WebService需要先确定WebService的接口和协议,然后选择合适的客户端工具或框架,最后使用编程语言创建客户端代码来访问WebService
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值