加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

REST风格WebService调用客户端

发布时间:2020-12-17 00:17:43 所属栏目:安全 来源:网络整理
导读:1. 客户端接口 package com.http.client;/** * * Http客户端接口 * @author ypqiao * */public interface HttpClient {/** 发送GET请求,返回 文本数据 **/public abstract String get(String urlStr) throws Exception;/** 发送GET请求,返回二进制数据 **/

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"));
		
	}
	
	
	

}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读