`
jahu
  • 浏览: 60963 次
  • 性别: Icon_minigender_1
  • 来自: 长沙
社区版块
存档分类
最新评论

简易的http-client

    博客分类:
  • java
 
阅读更多
package com.http;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;


/**
 * 所有数据默认返回 json
 * 目前不支持文件上传
 * @author vp
 *
 */
public class SimpleHttpClient {
	private Object object;
	
	public SimpleHttpClient(Class clazz){
		object = Proxy.newProxyInstance(clazz.getClassLoader(), 
			     new Class[]{clazz}, 
			     new ProxyHandler( new HttpClient("", PerFormEnum.POSTBODY)));
	}
	
	
	

	static class bulid {
		
	}
}

class HttpClient{
	private static final Map<String,String> defaultRequestProperty = new HashMap<String, String>();
	static{
		defaultRequestProperty.put("User-Agent", "laohu");
		defaultRequestProperty.put("Content-Type", "application/json");
		defaultRequestProperty.put("Accept", "application/json");
	}
	
	
	private Map<String,String> requestProperty = new HashMap<String, String>( defaultRequestProperty );
	
	private HttpRequestSerialization httpRequestSerialization;
	
	private HttpReturnSerialization httpReturnSerialization;
	
	private Perform perform;
	
	private int defaultConnectTimeout = 3000;
	private int defaultReadTimeout    = 3000;
	
	private int connectTimeout = 3000;
	private int readTimeout    = 3000;
	
	private String url;
	
	private PerFormEnum perFormEnum;
	
	private Map<String ,String> parameter;
	
	
	public HttpClient(String url , PerFormEnum perFormEnum){
		this( url , perFormEnum , new HashMap<String, String>());
	}
	
	public HttpClient(String url , PerFormEnum perFormEnum , Map<String ,String> parameter ){
		this( url , perFormEnum , parameter , new DefaultHttpRequestSerialization() , new StringHttpReturnSerialization());
	}
	
	
	public HttpClient(String url , PerFormEnum perFormEnum , Map<String ,String> parameter , HttpRequestSerialization httpRequestSerialization,HttpReturnSerialization httpReturnSerialization){
		if( url == null  || parameter == null){
			throw new NullPointerException();
		}
		this.url = url ;
		this.perFormEnum = perFormEnum;
		this.perform = perFormEnum.getPerform();
		this.perform.setUrl( this.url );
		
		this.parameter = parameter;
		
		if(parameter.containsKey( "connectTimeout")){
			connectTimeout = Integer.getInteger( this.parameter.get("connectTimeout"));
		}else{
			connectTimeout  = defaultConnectTimeout;
		}
		
		if(parameter.containsKey( "readTimeout")){
			readTimeout = Integer.getInteger( this.parameter.get("readTimeout"));
		}else{
			readTimeout = defaultReadTimeout;
		}
		
		
		this.httpRequestSerialization = httpRequestSerialization;
		this.httpReturnSerialization  = httpReturnSerialization;
				
	}
	
	
	public <T>T perform(String uri , Object object) throws Exception{
		String data = null;
		if(object != null){
			data = httpRequestSerialization.serialization( object );
		}
		String url = perform.urlPerform(uri, data);
		HttpURLConnection httpUrlConnection = (HttpURLConnection)new URL(url).openConnection();
		httpUrlConnection.setRequestMethod( perFormEnum.getMethon() );
		setRequestProperty( httpUrlConnection );
		
		perform.perform(httpUrlConnection, data);
		
		
		try{		
			httpUrlConnection.setUseCaches( false );
			
			httpUrlConnection.setReadTimeout( this.readTimeout );
			
			httpUrlConnection.setConnectTimeout( this.connectTimeout );
			
			httpUrlConnection.connect();
		}catch (Exception e) {
			//这里修改代码不
		}
		
		int i = httpUrlConnection.getResponseCode();
		if( i == 200)
			return returnDate( httpUrlConnection );		
		return null;		
	}
	
	
	private void setRequestProperty(HttpURLConnection httpUrlConnection){
		for( Entry<String, String> e : requestProperty.entrySet()){
			httpUrlConnection.setRequestProperty( e.getKey() , e.getValue() );
		}
	}
	
	/**
	 * 可以从请求头里面获得 数据长度,就不用循序了
	 * @param httpUrlConnection
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings({ "unused", "unchecked" })
	private <T>T returnDate(HttpURLConnection httpUrlConnection ) throws Exception{
		try(BufferedInputStream bais = new BufferedInputStream(httpUrlConnection.getInputStream())){
			ByteArrayOutputStream baos  = new ByteArrayOutputStream();
			byte[] contents = new byte[2024];  
	        int byteRead = 0;  
	        while((byteRead = bais.read(contents)) != -1){  
	        	baos.write( contents );
            }  	        
			return (T)httpReturnSerialization.serialization( baos.toByteArray() );
		}
	}	
}


/**
 * 
 * @author vp
 *
 */




class ProxyHandler implements InvocationHandler {

	private HttpClient httpClient;
	
	public ProxyHandler( HttpClient httpClient ){
		this.httpClient = httpClient;
	}
	
	
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		
		
		return httpClient.perform( method.getName() , args[0] );
	}
	
}


/**
 * 
 * @author vp
 *
 */

interface HttpRequestSerialization {
	
	public String serialization(Object o);
}

class DefaultHttpRequestSerialization implements HttpRequestSerialization{

	public String serialization(Object o) {
		
		return null;
	}

	private String mapSerialization(){
		
		return null;
	}
	
	private String entitySerialization(){
		
		return null;
	}
}

/**
 * 
 * @author vp
 *
 */
interface HttpReturnSerialization {

	
	public Object serialization(byte[] byteArray);
}

class StringHttpReturnSerialization implements HttpReturnSerialization {

	public Object serialization(byte[] byteArray) {
	
		return new String( byteArray );
	}

}


/**
 * 
 * @author vp
 *
 */


interface Perform {
	
	static final byte[] separator = new byte[]{13 , 10};
	
	static final byte[] piecewise = new byte[]{13 , 10 , 13 ,10};
	
	
	public void setUrl(String url );

	public String urlPerform(String url, String data);

	public void perform(HttpURLConnection httpUrlConnection, String data) throws Exception;
}


 enum PerFormEnum{
	
	GET("GET" , new GetPerform()),
	POST("POST" , new PostPerform()),
	POSTBODY("POST" , new PostBodyPerform());
	
	private String methon;
	
	private Perform perform;
	
	
	
	PerFormEnum(String methon , Perform perform ){
		this.methon = methon;
		this.perform = perform;
	}

	
	public String getMethon(){
		return methon;
	}
	
	public Perform getPerform(){
		return perform;
	}
}


abstract class PequestPerForm implements Perform {

	String url;
	
	public void setUrl(String url){
		this.url = url;
	}
	
	public String urlPerform(String url, String data) {
		return this.url + url;
	}

	public void perform(HttpURLConnection httpUrlConnection, String data) throws Exception {
		
	}
}

abstract class PostPequestPerForm extends PequestPerForm{
	
	private OutputStream outputStream;
	
	private HttpURLConnection httpUrlConnection;
	
	private int bodyLenth = 0;
	
	void setHttpURLConnection( HttpURLConnection httpUrlConnection ) throws IOException{
		this.httpUrlConnection = httpUrlConnection;
		httpUrlConnection.setDoOutput(true);
		httpUrlConnection.setDoInput(true);
		httpUrlConnection.setUseCaches(false);	
				
		this.outputStream = httpUrlConnection.getOutputStream();
	}
	
	
	void write(byte[] by , int length ) throws IOException{
		bodyLenth = bodyLenth + by.length;
		outputStream.write( by );
	}
	
	void write(byte[] by) throws IOException{
		write( by , by.length);
	}
	
	
	void length(){
		httpUrlConnection.setRequestProperty("Content-length" , ""+bodyLenth);
	}
}



class GetPerform extends PequestPerForm {
	public String urlPerform(String url, String data) {
		return super.urlPerform(url,data)+"?"+data;
	}
}

class PostPerform  extends PostPequestPerForm {

	public void perform(HttpURLConnection httpUrlConnection, String data) throws Exception{
		setHttpURLConnection( httpUrlConnection );
		write( data.getBytes() );

	}
}


class PostBodyPerform extends PostPequestPerForm {
	
	public void perform(HttpURLConnection httpUrlConnection, String data) throws Exception {
		setHttpURLConnection( httpUrlConnection );
		
		write( piecewise , 0 );
		write(data.getBytes());	
	}
}


 很简单,支持post,get请求,支持流传输,支持对象操作。

目的就是为了,没有依赖。给调用方使用。

分享到:
评论

相关推荐

    artemis-http-client-1.1.3.jar

    artemis-http-client-1.1.3.jar

    前端开源库-ipfs-http-client

    **前端开源库-ipfs-http-client** IPFS(InterPlanetary File System)是一个去中心化的文件存储和分发系统,旨在创建持久且分散的网络。它允许用户存储和共享数据,而无需依赖传统的中心化服务器。在前端开发中,...

    http-client.jar包下载

    http-client.jar包下载 HttpClient是Apache Jakarta Common下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTTP协议最新的版本和建议。

    google-http-java-client-1.13.1-beta

    "google-http-java-client-1.13.1-beta" 是Google官方发布的一个Java库,主要用于在Android平台上进行HTTP网络通信。这个库包含了丰富的工具类,能够帮助开发者方便地实现各种HTTP请求,从而满足Android应用中的网络...

    google-http-java-client-1.13.1-beta.zip

    "google-http-java-client-1.13.1-beta.zip" 是一个包含Google HTTP Java客户端库的压缩包,这个库主要用于Java开发者与Google的HTTP API进行交互。它提供了简单且强大的方式来构建网络请求,处理响应,并集成到Java...

    async-http-client-2.0.13.zip

    《深入解析Async-HTTP-Client 2.0.13:一个Twitter开源的网络请求库》 Async-HTTP-Client,作为一个高效的、基于Java的开源网络请求库,为开发者提供了异步HTTP请求处理的能力,其版本2.0.13在功能和性能上都有着...

    http-client-3.0.1.jar

    本文将深入探讨这个库的3.0.1版本——"http-client-3.0.1.jar",以及它如何作为"commons-http-client.jar"在Java应用程序中的关键依赖。 Apache Commons HttpClient 3.0.1是Apache软件基金会的一个开源项目,它提供...

    async-http-client-1.7.11-sources.jar

    async-http-client-1.7.11-sources.jar

    async-http-client.jar包下载

    用于android异步加载框架jar包,很实用async_http_client.jar

    jersey-core、jersey-client jar包.rar

    总的来说,这个场景涉及了Spring MVC的控制器逻辑、jersey-client的使用、HTTP请求的构建和发送,以及跨服务器通信的实现。这需要对Java、Spring框架、RESTful服务以及HTTP协议有深入理解。通过jersey-core和jersey-...

    DHC-REST-HTTP-API-Client(chrome插件)

    **DHC-REST-HTTP-API-Client:Chrome插件详解** DHC-REST-HTTP-API-Client是一款专为开发者设计的Chrome浏览器插件,它极大地简化了与RESTful API交互的过程。这款工具允许用户轻松地进行HTTP请求,包括GET、POST、...

    cas-client-core-3.3.3

    `cas-client-core-3.3.3` 是一个CAS客户端的核心库,它使得应用程序能够与CAS服务器进行交互,实现用户的认证和授权功能。 1. **CAS协议原理**: CAS协议通过代理票据(Proxy Ticket)和服务票据(Service Ticket...

    Async-http-client

    Async-http-client是一个在Java平台上广泛使用的异步HTTP客户端库,其设计目的是为了高效、便捷地进行网络通信。这个库的核心特点在于它支持非阻塞I/O,能够处理大量的并发连接,从而极大地提高了应用程序的性能。在...

    DHC-REST-HTTP-API-Client_v0.8.1.1

    【DHC-REST-HTTP-API-Client_v0.8.1.1】是一款基于Web的接口测试工具,专为简化API测试流程而设计。这款应用允许用户直接在谷歌浏览器中进行HTTP请求,从而便捷地检验RESTful API的功能和性能。REST...

    Appium-Python-Client-2.6.0.tar.gz

    在描述中提到,如果你需要使用Python编写脚本来执行Appium测试,那么Appium-Python-Client-2.6.0.tar.gz这个压缩包就是必不可少的依赖。这个压缩包包含了Python客户端的所有源代码和必要的文件,用于与Appium服务器...

    fastdfs-client-java-1.27-SNAPSHOT.zip

    在此次提及的压缩包"fastdfs-client-java-1.27-SNAPSHOT.zip"中,包含了两个关键文件:"fastdfs-client-java-1.27-SNAPSHOT.jar"和"fastdfs-client-java-1.27-SNAPSHOT.pom"。 1. **fastdfs-client-java-1.27-...

    Advanced-REST-client_v3.1.9.rar

    Advanced-REST-client是一款广受欢迎的API接口测试工具,专为谷歌浏览器(Google Chrome)设计。它为开发者提供了方便快捷的接口测试环境,帮助他们验证、调试和优化RESTful web服务。这款工具支持HTTP/HTTPS协议,...

    http-client-stream

    http-客户端-流用法使用 http 请求作为流: var http = require ( 'http-client-stream' )var endpoint = http ( 'http://www.google.com' )var stream = endpoint . createStream ( )process . stdin . pipe ( ...

    rtmp-rtsp-stream-client-java-master.zip

    【rtmp-rtsp-stream-client-java-master.zip】这个压缩包文件是针对安卓平台的一个开源项目,主要用于实现RTMP和RTSP直播推流功能。在Android Studio 3.5及以上版本中开发,它允许用户将手机上的视频内容实时推送到...

Global site tag (gtag.js) - Google Analytics