基于Java的HttpClient传输demo

本文介绍了一个实用的HTTP客户端工具类,包括POST和GET请求的实现。通过使用Apache HttpClient库,该工具类能够处理JSON参数的POST请求和发送GET请求,同时解决了中文乱码问题并设置了请求超时。

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

package cn.com.pubinfo.sifa.base.util;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
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.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;


public class HttpClientUtil {
	/**
     * post请求传输json参数
     *
     * @param url
     *            url地址
     * @param jsonParam
     *            参数
     * @return
     */
    public static String doPost(String url, String param) {
        // post请求返回结果
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String resultStr = null;
        HttpPost httpPost = new HttpPost(url);
        // 设置请求和传输超时时间
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(3000).setConnectTimeout(1000).build();
        httpPost.setConfig(requestConfig);
        try {
            if (null != param) {
                // 解决中文乱码问题
//                StringEntity entity = new StringEntity("cardId=1&userId=2", "utf-8");
//                entity.setContentEncoding("UTF-8");
//                entity.setContentType("application/json");
//                httpPost.setEntity(entity);
                StringEntity stringEntity = new StringEntity(param.toString(), "utf-8");  
                stringEntity.setContentEncoding("UTF-8");
                stringEntity.setContentType("application/json");  
                httpPost.setEntity(stringEntity); 
            }
            CloseableHttpResponse result = httpClient.execute(httpPost);
            //请求发送成功,并得到响应
            if (result.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                try {
                    //读取服务器返回过来的json字符串数据
                	resultStr = EntityUtils.toString(result.getEntity(), "utf-8");
                } catch (Exception e) {
                    //logger.error("post请求提交失败:" + url, e);
                }
            }
        } catch (IOException e) {
            //logger.error("post请求提交失败:" + url, e);
        } finally {
            httpPost.releaseConnection();
        }
        return resultStr;
    }

    /**
     * 发送 get请求
     */
    @SuppressWarnings("finally")
	public static String doGet(String url) {
    	String result = "";
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            // 创建httpget.
            HttpGet httpget = new HttpGet(url);
            System.out.println("executing request " + httpget.getURI());
            // 执行get请求.
            CloseableHttpResponse response = httpclient.execute(httpget);
            try {
                // 获取响应实体
                HttpEntity entity = response.getEntity();
                // 打印响应状态
                System.out.println(response.getStatusLine());
                if (entity != null) {
                    // 打印响应内容长度
                    //System.out.println("Response content length: " + entity.getContentLength());
                    // 打印响应内容
                    //System.out.println("Response content: " + EntityUtils.toString(entity));
                    result = EntityUtils.toString(entity);
                }
            } finally {
                response.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return result;
        }
    }
    
    
    public static void main(String[] args) {
    	String msg = doGet("http://baike.baidu.com/api/openapi/BaikeLemmaCardApi?scope=103&format=json&appid=379020&bk_key=%E9%93%B6%E9%AD%82&bk_length=600");
    	System.out.println(msg);
		
	}
    
    
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值