java实现HTTP请求方式

目录

1.HttpURLConnection

2.Apache的HttpClient例子


1.HttpURLConnection

import javax.imageio.stream.ImageInputStreamImpl;
import org.eclipse.jetty.util.ajax.JSON;

public class Client {
	/**
	 * Http get请求
	 * @param httpurl
	 * @return
	 * @throws IOException
	 */
	public String sendGet(String httpurl) throws IOException {
		URL url = new URL(httpurl);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		//设置连接方式
		conn.setRequestMethod("GET");
		//设置主机连接时间超时时间3000毫秒
		conn.setConnectTimeout(3000);
		//设置读取远程返回数据的时间3000毫秒
		conn.setReadTimeout(3000);
		
		//发送请求
		conn.connect();
		//获取输入流
		InputStream is = conn.getInputStream();
		//封装输入流
		BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
		//接收读取数据
		StringBuffer sb = new StringBuffer();
		
		String line = null;
		while((line = br.readLine())!=null) {
			sb.append(line);
			sb.append("\r\n");
		}
		if(null!=br) {
			br.close();
		}
		if(null!=is) {
			is.close();
		}
		//关闭连接
		conn.disconnect();
		return sb.toString();
	}
	
	/**
	 * Http post请求
	 * @throws IOException 
	 */
	public String doPost(String httpurl, Map param) throws IOException {
		String jsonparam = JSON.toString(param);
		
		URL url = new URL(httpurl);
		//获取httpurlConnection连接
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		//设置读取超时
		conn.setConnectTimeout(3000);
		//设置读取超时
		conn.setReadTimeout(3000);
		
		//传送数据
		conn.setDoOutput(true);
		//读取数据
		conn.setDoInput(true);
		//设置请求方式
		conn.setRequestMethod("POST");
		//设置传入参数格式
		conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
		// 设置鉴权信息:Authorization: Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0
        conn.setRequestProperty("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
        
        //获取输出流
        OutputStream os = conn.getOutputStream();
        //输出数据
        os.write(jsonparam.getBytes());
        //获取输入流
        InputStream is = conn.getInputStream();
        //封装输入流
        BufferedReader br = new BufferedReader(new InputStreamReader(is,"UTF-8"));
        
        StringBuffer sb = new StringBuffer();
        String line = null;
        
        while((line = br.readLine())!=null) {
        	sb.append(line);
        	sb.append("\r\n");
        }
        if(null != br) {
        	br.close();
        }
        if(null != is) {
        	is.close();
        }
        if(null != os) {
        	os.close();
        }
        //关闭连接
        conn.disconnect();
        
	return sb.toString();
	}
}

2.Apache的HttpClient例子

/**
     * 发送HttpGet请求
     * @param url
     * @return
     */
    public static String sendGet(String url) {
        //1.获得一个httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        //2.生成一个get请求
        HttpGet httpget = new HttpGet(url);
        CloseableHttpResponse response = null;
        try {
            //3.执行get请求并返回结果
            response = httpclient.execute(httpget);
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        String result = null;
        try {
            //4.处理结果,这里将结果返回为字符串
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                result = EntityUtils.toString(entity);
            }
        } catch (ParseException | IOException e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }


 /**
     * 发送HttpPost请求,参数为map
     * @param url
     * @param map
     * @return
     */
    public static String sendPost(String url, Map map) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        List formparams = new ArrayList();
        for (Map.Entry entry : map.entrySet()) {
            //给参数赋值
            formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
        HttpPost httppost = new HttpPost(url);
        httppost.setEntity(entity);
        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(httppost);
        } catch (IOException e) {
            e.printStackTrace();
        }
        HttpEntity entity1 = response.getEntity();
        String result = null;
        try {
            result = EntityUtils.toString(entity1);
        } catch (ParseException | IOException e) {
            e.printStackTrace();
        }
        return result;
    }

 

你可能感兴趣的:(初级Java成长专栏)