基于jdk,urlApi的http请求工具类

本文介绍了一个 Java 实现的 URL 连接工具类,包括 GET 和 POST 请求的发送方法,展示了如何通过 Java 处理 HTTP 请求并解析响应。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.bx.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UrlConnectionUtil {
	
	private static final String BASEURL = "http://127.0.0.1:8080/GQPlatform/";
	/**
	 * url对象的openStream()只能读取网络资源,返回流使用有限
	 * 这里只做简单的测试
	 */
	public static void testOpenStream(){
	
		try {
			//创建url对象
			URL url = new URL("http://www.baidu.com");
			//打开连接,返回InputStream对象
			InputStream is = url.openStream();
			//处理输入流,写入本地文件中
			InputStreamReader isr = new InputStreamReader(is);
			BufferedReader br = new BufferedReader(isr);
			//构造本地文件对应的输出流
			File file = new File("d:\\testOpenStream.txt");
			BufferedWriter bw = new BufferedWriter(new FileWriter(file));
			//读、写
			String str;
			while((str = br.readLine()) != null){
				bw.write(str);
				bw.newLine();
			}
			bw.flush();
			bw.close();
			br.close();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 发送get请求
	 * 调用openConnection方法,
	 * 返回UrlConnection对象,建立一个可读可写的连接
	 * @param url
	 * @param parmsMap
	 * @return
	 */
	public static String sendGet(String url,Map<String, String> parmsMap){
		
		StringBuffer resultStr = new StringBuffer();
		URLConnection connection = null;
		InputStream is = null;
		BufferedReader br = null;
		url = BASEURL + url;
		//参数处理拼接到url上
		if(null != parmsMap && !parmsMap.isEmpty()){
			//遍历map
			for(String key:parmsMap.keySet()){
				
				url = url+"&"+key+"="+parmsMap.get(key);
			}
		}
		
		try {
			//新建url对象
			URL urlApi = new URL(url);
			//打开连接获取urlConnection对象
			connection = urlApi.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接收响应头信息
//            Map<String, List<String>> headersMap = new HashMap<String, List<String>>();
//            headersMap = connection.getHeaderFields();
//            for(String key : headersMap.keySet()){
//            	System.out.println(key+">>>>>>>>>>>>>"+headersMap.get(key));
//            }
            //用io流处理响应内容
            is = connection.getInputStream();
            br = new BufferedReader(new InputStreamReader(is,"UTF-8"));
            String tmpStr;
            while((tmpStr = br.readLine()) != null){
            	resultStr.append(tmpStr);
            }
            
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			try {
				if(null != is){
					is.close();
				}
				if(null != br){
					br.close();
				}	
			} catch (IOException e) {
				e.printStackTrace();
			}
            
		}
		return resultStr.toString();
	}
	
	/**
	 * 发送post请求
	 * @param url
	 * @param parmsMap
	 * @return
	 */
	public static String sendPost(String url,Map<String, String> parmsMap){ 
		
		StringBuffer resultStr = new StringBuffer();
		url = BASEURL + url;
		StringBuffer parms = new StringBuffer();
		BufferedWriter writer = null;
		BufferedReader reader = null;
		try {
			//创建url对象
			URL urlApi = new URL(url);
			//参数处理
			if(null != parmsMap && !parmsMap.isEmpty()){
				for(String key:parmsMap.keySet()){
					parms.append(key+"="+parmsMap.get(key)).append("&");
				}
			}
			if(parms.length()>0){
				parms.deleteCharAt(parms.length()-1);
			}
			URLConnection urlConnection = urlApi.openConnection();
			HttpURLConnection httpURLConnection = (HttpURLConnection)urlConnection;
			// 发送POST请求必须设置如下两行  
			httpURLConnection.setDoOutput(true);  
			httpURLConnection.setDoInput(true);  
			httpURLConnection.setRequestMethod("POST");    // POST方法 
			//设置通用属性
			httpURLConnection.setRequestProperty("accept", "*/*");  
			httpURLConnection.setRequestProperty("connection", "Keep-Alive");  
			httpURLConnection.setRequestProperty("user-agent",  
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			//建立实际连接
			httpURLConnection.connect();
			//用输出流发送参数
			OutputStream os = httpURLConnection.getOutputStream();
			writer = new BufferedWriter(new OutputStreamWriter(os,"UTF-8"));
			writer.write(parms.toString());
			writer.flush();
			//用输入流接收响应信息
			InputStream is = httpURLConnection.getInputStream();
			reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));
			String tmpStr;
			while((tmpStr=reader.readLine()) != null){
				resultStr.append(tmpStr);
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			try {
				if(null != writer){
					writer.close();
				}
				if(null != reader){
					reader.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		}
		return resultStr.toString();
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值