几种接口请求方式

1、post请求

   /**
 * 向指定url发送post请求
 * @param url:请求地址
 * @param params:请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
 * @return result:接口返回报文
 */
public static String post(String url,String params){
    OutputStream out = null;
    HttpURLConnection conn = null;
    String result = "";
    try{
        URLEncoder.encode(url, "UTF-8");
        URL readUrl = new URL(url);
        //打开与url的连接
        conn = (HttpURLConnection) readUrl.openConnection();
        // 设置通用的请求属性
        conn.setRequestProperty("accept", "*/*");
        conn.setRequestProperty("connection", "Keep-Alive");
        conn.setRequestProperty("content-type", "application/json");
        conn.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
        conn.setReadTimeout(60 * 1000); // 60s 超时时间
        // 发送POST请求必须设置如下两行
        conn.setDoOutput(true);
        conn.setDoInput(true);
        out = conn.getOutputStream();
        out.write(params.getBytes("utf-8")); //设置编码务必编码上下一样!
        out.flush();
        out.close();
        //获取返回结果
        StringBuffer buffer = new StringBuffer();
        BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"));
        String temp;
        while ((temp = br.readLine())!=null) {
            buffer.append(temp);
            buffer.append("\\n");
        }
        result = buffer.toString();
    }catch(Exception e){
        System.out.println("发送POST请求出现异常!" + e);
        e.printStackTrace();
    }
    return result;
}

2、get请求

/**
 * 发送get请求
 * @param url
 * @return 接口返回报文
 */
public static String sendGet(String url){
	String result = "";
	BufferedReader in = null;
	try{
	        URLEncoder.encode(url, "UTF-8");
		URL realUrl = new URL(url);
		// 打开和URL之间的连接
		URLConnection connection = realUrl.openConnection();
		// 设置通用的请求属性
		connection.setRequestProperty("accept", "*/*");
		connection.setRequestProperty("connection", "Keep-Alive");
		connection.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
		// 建立实际的连接
		connection.connect();
		// 获取所有响应头字段
		Map<String, List<String>> map = connection.getHeaderFields();
		// 遍历所有的响应头字段
		for (String key : map.keySet()) {
			System.out.println(key + "--->" + map.get(key));
		}
		// 定义 BufferedReader输入流来读取URL的响应
		in = new BufferedReader(new InputStreamReader(connection.getInputStream(),"utf-8"));
		String line;
		while ((line = in.readLine()) != null) {
			result += line;
		}
	}catch(Exception e){
		System.out.println("发送GET请求出现异常!" + e);
		e.printStackTrace();
	}// 使用finally块来关闭输入流
	finally {
		try {
			if (in != null) {
				in.close();
			}
		} catch (Exception e2) {
			e2.printStackTrace();
		}
	}		
	return result;
}

3、SSL请求

 
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;
public class CustomizedHostnameVerifier implements HostnameVerifier  
{  
	@Override  
	public boolean verify(String arg0, SSLSession arg1)  
	{  
		return true;  
	}  
}

import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.X509TrustManager;
public class MyX509TrustManager implements X509TrustManager { 
	public MyX509TrustManager() throws Exception { 

	} 
	/* 
	 * Delegate to the default trust manager. 
	 */ 
	public void checkClientTrusted(X509Certificate\[\] chain, String authType) 
			throws CertificateException { 
	} 
	/* 
	 * Delegate to the default trust manager. 
	 */ 
	public void checkServerTrusted(X509Certificate\[\] chain, String authType) 
			throws CertificateException { 
	} 
	/* 
	 * Merely pass this through. 
	 */ 
	public X509Certificate\[\] getAcceptedIssuers() { 	
		return new java.security.cert.X509Certificate\[0\];	
	} 
}
/**
 * SSL请求
 * @param requestUrl  请求地址
 * @param outputStr   请求报文
 * @param requestMethod  POST 还是 GET
 * @return
 */
public static String sendSSL(String requestUrl,String outputStr,String requestMethod){
	StringBuffer buffer = new StringBuffer();    
	try {    
		System.setProperty ("jsse.enableSNIExtension", "false");  
		// 创建SSLContext对象,并使用我们指定的信任管理器初始化    
		TrustManager\[\] tm = { new MyX509TrustManager() };    
		SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");    
		sslContext.init(null, tm, new java.security.SecureRandom());    
		// 从上述SSLContext对象中得到SSLSocketFactory对象    
		SSLSocketFactory ssf = sslContext.getSocketFactory(); 
		URL url = new URL(requestUrl);
		//            URL url = new URL(null,requestUrl,new sun.net.www.protocol.https.Handler()); 使用这种
		HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();    
		httpUrlConn.setSSLSocketFactory(ssf);   
		httpUrlConn.setHostnameVerifier(new CustomizedHostnameVerifier());

		httpUrlConn.setDoOutput(true);    
		httpUrlConn.setDoInput(true);    
		httpUrlConn.setUseCaches(false);    
		// 设置请求方式(GET/POST)    
		httpUrlConn.setRequestMethod(requestMethod);
		httpUrlConn.setDoOutput(true);    
		httpUrlConn.setDoInput(true);    
		httpUrlConn.setUseCaches(false);    
		// 设置请求方式(GET/POST)    
		httpUrlConn.setRequestMethod(requestMethod);    

		if ("GET".equalsIgnoreCase(requestMethod))httpUrlConn.connect();

		// 当有数据需要提交时    
		if (null != outputStr) {    
			OutputStream outputStream = httpUrlConn.getOutputStream();    
			// 注意编码格式,防止中文乱码    
			outputStream.write(outputStr.getBytes("UTF-8"));    
			outputStream.close();    
		} 

		// 将返回的输入流转换成字符串    
		InputStream inputStream = httpUrlConn.getInputStream();    
		InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");    
		BufferedReader bufferedReader = new BufferedReader(inputStreamReader);  

		String str = null;    
		while ((str = bufferedReader.readLine()) != null) {    
			buffer.append(str);    
		}    
		bufferedReader.close();    
		inputStreamReader.close();    
		// 释放资源    
		inputStream.close();    
		inputStream = null;    
		httpUrlConn.disconnect();    
		System.out.println("返回的数据:"+buffer.toString()); 

	}catch(Exception e){
		System.out.println("发送GET请求出现异常!" + e);
		e.printStackTrace();
	}

	return buffer.toString();
}

4、socket

/**
 * socket请求
 * @param spServerIp  ip地址   127.0.0.1
 * @param spServerPort  端口号  10005
 * @return
 */
public static String sendSocket(String spServerIp,int spServerPort){

	String seriesNumer = new SimpleDateFormat("yyyyMMddHHmmss").format(Calendar.getInstance().getTime());
	OutputStream out = null;
	Reader reader = null;
	Socket socket = null;
	StringBuffer sb = new StringBuffer();
	try{			
		StringBuffer sb1 = new StringBuffer();
		sb1.append(seriesNumer);
		String body = sb1.toString();// 报文体
		socket = new Socket();
		socket.setTcpNoDelay(false);
		socket.connect(new InetSocketAddress(spServerIp, spServerPort));
		socket.setSoTimeout(60000);// 设置超时时间
		out = socket.getOutputStream();
		out.write(body.getBytes());
		out.flush();
		// 写完以后进行读操作
		reader = new InputStreamReader(socket.getInputStream());
		char chars\[\] = new char\[64\];
		int len;

		while ((len = reader.read(chars)) != -1) {
			String temp = new String(chars, 0, len);
			sb.append(temp);
		}
		return sb.toString();
	}catch(Exception e){
		System.out.println("发送socket请求出现异常!" + e);
		e.printStackTrace();
	}finally{
		try {
			if (out != null) {
				out.close();
			}
			if (reader != null) {
				reader.close();
			}
			if (socket != null) {
				socket.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}		
	return sb.toString();
}

5、Xsocket

import java.io.IOException;  
  
import org.xsocket.connection.BlockingConnection;  
import org.xsocket.connection.IBlockingConnection;  
import org.xsocket.connection.INonBlockingConnection;  
import org.xsocket.connection.NonBlockingConnection;  
/** 
 * 客户端接收服务端信息 
 * @author longgangbai 
 * IBlockingConnection:这个的话就是不支持事件回调处理机制的! 
 *INonBlockingConnection:这个连接支持回调机制 
 * 
 *非阻塞的客户端是能够支持事件处理的方法的。即如果从网络通道中没有取到想要的数据就会自动退出程序 
 */  
public class XSocketClient {  
    private static final int PORT = 10005;  
    public static void main(String\[\] args) throws IOException {  
            //采用非阻塞式的连接  
            //INonBlockingConnection nbc = new NonBlockingConnection("127.0.0.1", PORT, new ClientHandler());  
             
            //采用阻塞式的连接  
            INonBlockingConnection nbc = new NonBlockingConnection("127.0.0.1", PORT);   
            IBlockingConnection bc = new BlockingConnection(nbc);  

            System.out.println("bc.isOpen()"+bc.isOpen());
           //设置编码格式  
            bc.setEncoding("gbk");  
            //设置是否自动清空缓存  
            bc.setAutoflush(true);  
            //向服务端写数据信息  
            bc.write("xxxxxxx"+"\\r\\n"); 
            bc.setConnectionTimeoutMillis(10000);
             //读取数据的信息   
            byte\[\] byteBuffers= bc.readBytesByDelimiter("\\r", "gbk");   
            System.out.println(new String(byteBuffers,"gbk"));  
           //打印服务器端信息    
            System.out.println("服务器端信息1:"+ bc.getRemotePort());
            System.out.println("服务器端信息2:"+ bc.getLocalAddress());
            System.out.println("服务器端信息3:"+ bc.getFlushmode());
            System.out.println("服务器端信息4:"+ bc.getId()); 
            //将信息清除缓存,写入服务器端  
            bc.flush();  
            bc.close();   
        
    }  
  
}