Java的http工具

Java的http工具

代码:

package net.pushi.neo4jdata.util;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.springframework.util.StringUtils;

public class HttpClients {

	public static String doGet(String url){
		try{
			String paramString = "";
			int pos = url.indexOf("?");
			if(pos!=-1){
				paramString = url.substring(pos+1, url.length()); 
				url = url.substring(0, pos);
			}
        	return  doGet(url,paramString);
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    	return "[{\"code\":500}]";
	}
	/**
     * 向指定URL发送GET方法的请求
     * 
     * @param url
     *            发送请求的URL
     * @param param
     *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     */
    public static String doGet(String url, String param) {
        String result = "";
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            HttpURLConnection connection = (HttpURLConnection)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.setRequestProperty("NAME", "X-Mailer");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
//            for (String key : map.keySet()) {
//                System.out.println(key + "--->" + map.get(key));
//            }
            int resultCode = connection.getResponseCode();
            // 定义 BufferedReader输入流来读取URL的响应
            if(resultCode<300){
            	BufferedReader in = new BufferedReader(new InputStreamReader(
                        connection.getInputStream(),"utf-8"));
                String line;
                while ((line = in.readLine()) != null) {
                    result += line;
                }
                in.close();
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常!" + e);
            e.printStackTrace();
            result = "[{\"code\":500}]";
        }
        return result;
    }
    
    public static String doGet(String url, Map<String,String> param) {
    	try{
    		String paramString = "";
        	if(param!=null && !param.isEmpty()){
        		Set<String> keys = param.keySet();
        		java.util.Iterator<String> it = keys.iterator();
        		while(it.hasNext()){
        			String key = it.next();
        			String value = param.get(key);
        			paramString += key + "=" + (StringUtils.isEmpty(value)?"":java.net.URLEncoder.encode(value, "UTF-8")) + "&";
        		}
        		paramString = paramString.substring(0, paramString.length()-1);
        	}
        	return doGet(url,paramString);
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    	return "[{\"code\":500}]";
    }

    /**
     * 向指定 URL 发送POST方法的请求
     * 
     * @param url
     *            发送请求的 URL
     * @param param
     *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String doPost(String url, String param) {
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            HttpURLConnection conn = (HttpURLConnection)realUrl.openConnection();
           // conn.setConnectTimeout(3000);
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);//忽略缓存
            conn.setRequestMethod("POST");
            // 设置通用的请求属性
            conn.setRequestProperty("Accept", "application/json, text/javascript, */*; q=0.01");
            conn.setRequestProperty("Accept-Charset", "utf-8");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.81 Safari/537.36");
            conn.setRequestProperty("Content-Length", String.valueOf(param==null?0:param.length()));
            conn.setRequestProperty("X-Requested-With", "XMLHttpRequest");
            //conn.setReadTimeout(3000);
            //System.out.println(param.length());
            conn.setRequestProperty("NAME", "X-Mailer");
            conn.connect();
            // 获取URLConnection对象对应的输出流
            PrintWriter out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            out.close();
            int resultCode = conn.getResponseCode();
            System.out.println(resultCode);
            if(resultCode>0){
            	// 定义BufferedReader输入流来读取URL的响应
            	BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"));
                String line;
                while ((line = in.readLine()) != null) {
                    result += line;
                }
                System.out.println(result);
                in.close();
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常!"+e);
            e.printStackTrace();
            result = "[{\"code\":500}]";
        }
        System.out.println(result);
        return result;
    }    
    
    public static String doPost(String url, Map<String,String> param) {
    	try{
    		String paramString = "";
        	if(param!=null && !param.isEmpty()){
        		Set<String> keys = param.keySet();
        		java.util.Iterator<String> it = keys.iterator();
        		while(it.hasNext()){
        			String key = it.next();
        			String value = param.get(key);
        			paramString += key + "=" + (StringUtils.isEmpty(value)?"":java.net.URLEncoder.encode(value, "UTF-8")) + "&";
        		}
        		paramString = paramString.substring(0, paramString.length()-1);
        	}
        	return doPost(url,paramString);
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    	return "[{\"code\":500}]";
    }
    public static void main(String[] args) throws Exception{
    	String url = "http://pfoa.yffs131419.com/authorization";
        Map<String, String> param=new HashMap();
        param.put("userCode", "kh000001");
        param.put("userToken", "a752dbfb27194d0b8eef215aa55e5e01");
    	HttpClients.doPost(url,param);
    }
    
}

你可能感兴趣的:(Springboot,java)