java_HttpClientUtil

本文深入探讨了HTTP GET和POST请求的实现方法,通过Java代码示例详细讲解了如何使用HttpClient库进行GET和POST请求,包括参数传递、数据流传输及JSON数据处理。适合对HTTP请求处理有兴趣的技术人员阅读。

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

post,get请求
传递map

package com.yb.handleTags.base.getUrl;

import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;


//httpclientutil 工具类
public class HttpClientUtil {

    public static String doGet(String url, Map<String, String> param) {

        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();

        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();

            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);

            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

    public static String doGet(String url) {
        return doGet(url, null);
    }

    public static String doPost(String url, Map<String, String> param) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建参数列表
            if (param != null) {
                List<NameValuePair> paramList = new ArrayList<NameValuePair>();
                for (String key : param.keySet()) {
                    paramList.add(new BasicNameValuePair(key, param.get(key)));
                }
                // 模拟表单
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList,"utf-8");
                httpPost.setEntity(entity);
            }
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        return resultString;
    }

    public static String doPost(String url) {
        return doPost(url, null);
    }
}

用数据流方式传输post


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
import org.codehaus.jackson.map.ObjectMapper;

public class HttpClientUtil {

	public static void main(String[] args) throws Exception {
		sxTest();
	}
	 
	private static void sxTest() {
		ObjectMapper mapper = new ObjectMapper();
		Map<String, String> entryMap = new HashMap<String, String>();
		entryMap.put("content",
				"有履行能力而拒不履行生效法律文书确定义务");
		entryMap.put("Date", "2019-07-30 11:03:50");
		entryMap.put("flag", "0");
		String str;
		try {
			str = mapper.writeValueAsString(entryMap);
			System.out.println(str);
			HttpClientUtil.sendPost("http://localhost:18091/sx", str);		
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static String sendPost(String url, String param) {
		OutputStreamWriter out = null;
		BufferedReader in = null;
		String result = "";
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();

			// 设置通用的请求属性

			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);

			// 1.获取URLConnection对象对应的输出流
			// out = new PrintWriter(conn.getOutputStream());
			// 2.中文有乱码的需要将PrintWriter改为如下
			if (param != null && param.length() > 1) {
				out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
				// 发送请求参数
				System.out.println("param=" + param);
				out.write(param);
				// flush输出流的缓冲
				out.flush();
			}
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}

		} catch (Exception e) {
			System.out.println("发送 POST 请求出现异常!" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输出流、输入流
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		System.out.println("post推送结果:" + result);
		return result;
	}
}

Java常用的Httpclient工具是HttpclientUtilHttpclientUtil是一个基于Apache HttpClient组件封装的工具类,它提供了简洁的接口和方法,使得Java开发者可以轻松地进行HTTP请求的发送和接收。 HttpclientUtil的主要特点和用途包括以下几个方面: 1. 发送HTTP请求:HttpclientUtil提供了getpost两种发送HTTP请求的方法,开发者可以根据需要选择合适的方法。发送请求时,可以设置请求头、请求参数、超时时间等。 2. 接收HTTP响应:HttpclientUtil能够接收HTTP响应,并对响应进行处理。开发者可以通过获取响应头、响应体等信息,实现对响应的解析和处理。 3. 支持HTTPS:HttpclientUtil对HTTPS请求也提供了支持,可以实现HTTPS请求的发送和接收。同时,也支持自定义HTTPS证书的配置,提高了安全性。 4. 连接池管理:HttpclientUtil使用连接池来管理HTTP连接,可以有效地提高请求的性能和效率。连接池可以复用已经建立的连接,减少了连接的建立和关闭的次数。 5. 支持cookie管理:HttpclientUtil能够自动管理请求和响应中的cookie信息,简化了开发者对cookie的处理过程。 6. 异步请求:HttpclientUtil支持异步请求,可以实现并发发送多个HTTP请求,并对响应进行处理。 总的来说,HttpclientUtil是一个功能强大、使用简便的Httpclient工具类,它方便了Java开发者进行HTTP请求的发送和接收,并提供了丰富的功能和选项,以满足不同的需求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值