httpUtil

该博客介绍了一个Java实现的HTTP请求工具类,包括POST和GET方式的API调用,支持参数传递、设置超时时间及请求头。内容涵盖了使用HttpURLConnection和HttpClient进行网络请求的方法,适用于发送JSON数据或表单数据。

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

url 解析工具
package org.iam.commpoment.timertask.demo;

import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpResponse;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HttpUtil {

	private static Log log=LogFactory.getLog(HttpUtil.class);

	/**
	 * 采用POST方式进行
	 * @param paramStr
	 * @return
	 */
	public static String POST_API(String urlStr,String paramStr,Map<String,String> headers) {
		log.debug(urlStr+","+paramStr+","+headers);
		BufferedReader br=null;
		OutputStream os=null;
		StringBuffer strBuf=new StringBuffer();
		try {
			URL url=new URL(urlStr);
			HttpURLConnection con=(HttpURLConnection) url.openConnection();
			con.setReadTimeout(5000);//5秒过期
			con.setDoOutput(true);
			con.setDoInput(true);
			con.setRequestMethod("POST");
			for (Map.Entry<String,String> entry : headers.entrySet()) {
				con.setRequestProperty(entry.getKey(), entry.getValue());
			}
			os=con.getOutputStream();

			os.write(paramStr.getBytes("UTF-8"));
			if(con.getResponseCode()==200){
				br=new BufferedReader(new InputStreamReader(con.getInputStream(),"UTF-8"));
				String line;
				while((line=br.readLine())!=null){
					strBuf.append(line);
				}
			}
		} catch (Exception e) {
			log.error("post_api error",e);
		} finally{
			if(os!=null){
				try{os.close();}catch(Exception e){}
			}
			if(br!=null){
				try{br.close();}catch(Exception e){}
			}
		}
		return strBuf.toString();
	}

    public static String GET_API(String urlStr,Map<String,String> headers) {
    	log.debug(urlStr+","+headers);
		BufferedReader br=null;
		OutputStream os=null;
		StringBuffer strBuf=new StringBuffer();
		try {
			URL url=new URL(urlStr);
			HttpURLConnection con=(HttpURLConnection) url.openConnection();
			con.setReadTimeout(5000);//5秒过期
			for (Map.Entry<String,String> entry : headers.entrySet()) {
				con.setRequestProperty(entry.getKey(), entry.getValue());
			}
			br=new BufferedReader(new InputStreamReader(con.getInputStream(),"UTF-8"));
			String line;
			while((line=br.readLine())!=null){
				strBuf.append(line);
			}
		} catch (Exception e) {
			log.error("get_api error",e);
		} finally{
			if(os!=null){
				try{os.close();}catch(Exception e){}
			}
			if(br!=null){
				try{br.close();}catch(Exception e){}
			}
		}
		return strBuf.toString();
    }

    public static String post(String requestUrl, String accessToken, String params)
            throws Exception {
        String contentType = "application/x-www-form-urlencoded";
        return HttpUtil.post(requestUrl, accessToken, contentType, params);
    }

    public static String post(String requestUrl, String accessToken, String contentType, String params)
            throws Exception {
        String encoding = "UTF-8";
        if (requestUrl.contains("nlp")) {
            encoding = "GBK";
        }
        return HttpUtil.post(requestUrl, accessToken, contentType, params, encoding);
    }

    public static String post(String requestUrl, String accessToken, String contentType, String params, String encoding)
            throws Exception {
        String url = requestUrl + "?access_token=" + accessToken;
        return HttpUtil.postGeneralUrl(url, contentType, params, encoding);
    }

    public static String postGeneralUrl(String generalUrl, String contentType, String params, String encoding)
            throws Exception {
        URL url = new URL(generalUrl);
        // 打开和URL之间的连接
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        // 设置通用的请求属性
        connection.setRequestProperty("Content-Type", contentType);
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setUseCaches(false);
        connection.setDoOutput(true);
        connection.setDoInput(true);

        // 得到请求的输出流对象
        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        out.write(params.getBytes(encoding));
        out.flush();
        out.close();

        // 建立实际的连接
        connection.connect();
        // 获取所有响应头字段
        Map<String, List<String>> headers = connection.getHeaderFields();
        // 遍历所有的响应头字段
        for (String key : headers.keySet()) {
            //System.err.println(key + "--->" + headers.get(key));
        }
        // 定义 BufferedReader输入流来读取URL的响应
        BufferedReader in = null;
        in = new BufferedReader(
                new InputStreamReader(connection.getInputStream(), encoding));
        String result = "";
        String getLine;
        while ((getLine = in.readLine()) != null) {
            result += getLine;
        }
        in.close();
       // System.err.println("result:" + result);
        return result;
    }

	public static String postGeneralUrl(String generalUrl, String contentType,
										Map<String, Object> params, String encoding) {
		String content = null;
		try {
			HttpPost post = new HttpPost(generalUrl);
			RequestConfig requestConfig = RequestConfig.custom()
					.setSocketTimeout(5000).setConnectTimeout(5000).build();
			post.setConfig(requestConfig);
			CloseableHttpClient httpClient = HttpClients.createDefault();
			List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
			for (Map.Entry<String, Object> val : params.entrySet())
				list.add(new BasicNameValuePair(val.getKey(), String
						.valueOf(val.getValue())));
			post.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
			HttpResponse response = httpClient.execute(post);
			content = EntityUtils.toString(response.getEntity(), "UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
		return content;
	}
	public static JSONObject doPost(String path) throws Exception {
		Thread.sleep(1000 * 1);
		String content;
		JSONObject json = new JSONObject();
		HttpClient http = null;
		CookieStore httpCookieStore = new BasicCookieStore();
		http = HttpClientBuilder.create().setDefaultCookieStore(httpCookieStore).build();
		// DefaultHttpClient client = new DefaultHttpClient();
		//准备post请求 定义 一个httpget实现
		HttpPost post = new HttpPost(path);
		//执行一个Post请求
		HttpResponse response = http.execute(post);
		//获取服务器返回的状态码
		int code = response.getStatusLine().getStatusCode();
		if (code == 200) {
			//获取服务器返回的数据   以流的形式返回
			InputStream inputStream = response.getEntity().getContent();
			//把流转换成字符串
			List<Cookie> cookies = httpCookieStore.getCookies();
			json.put("cookie", cookies.get(0).getValue());

		} else {
			json.put("msg", "false");
		}
		return json;
	}
}

 

### HttpUtil 工具类概述 HttpUtil 是用于简化 HTTP 请求操作的 Java 实用程序库。该工具类提供了便捷的方法来执行常见的 HTTP 操作,如 GET 和 POST 请求,并且集成了多种功能特性以增强其灵活性和可靠性[^1]。 ### 功能特点 - **超时设置**:允许开发者指定连接和读取数据的最大等待时间。 - **URL 参数处理**:能够方便地构建带有查询字符串的 URL 地址。 - **请求体格式选择**:支持不同的内容类型,特别是 JSON 格式的请求体。 - **异常处理机制**:内置了对可能出现错误情况的有效管理策略。 - **日志记录能力**:可以跟踪并记录每次网络交互过程中的重要事件。 ### Maven 依赖配置 为了使用基于 HttpClient 的 HttpUtil 类,在项目中需添加如下 Maven 依赖: ```xml <dependency> <groupId>com.seepine</groupId> <artifactId>httpclient</artifactId> <version>1.0.0</version> </dependency> ``` ### 示例代码展示 #### 发送简单的 GET 请求 下面是一个利用 HttpUtil 执行 GET 方法的例子,其中包含了如何定义目标地址以及获取响应结果的过程。 ```java public String sendGetRequest(String url) { try { HttpResponse response = HttpUtil.createGet(url).execute(); return response.body(); } catch (Exception e) { logger.error("Error occurred while sending get request", e); throw new RuntimeException(e.getMessage()); } } ``` #### 提交包含 JSON 数据的 POST 请求 此部分展示了怎样通过 PostMethod 对象发送携带 JSON 负载的数据到远程服务器端点上。 ```java public void doPostWithJsonBody(String url, Map<String, Object> params) throws Exception { HttpRequest request = HttpUtil.createPost(url) .header("Content-Type", "application/json") .body(JSON.toJSONString(params)); HttpResponse httpResponse = request.execute(); System.out.println(httpResponse.getStatusLine().getStatusCode() + ":" + httpResponse.body()); } ``` ### 日志与调试建议 当遇到问题时,启用详细的日志可以帮助定位具体原因。通常情况下,默认的日志级别可能不足以提供足够的诊断信息;因此推荐调整至更细粒度的日志输出模式以便更好地理解整个通信流程。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值