Java实现get或post请求

本文介绍了一个使用Apache HttpClient库实现的HTTP客户端工具类,包括GET和POST请求的发送方法,并展示了如何通过工具类进行简单的HTTP请求测试。

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

添加 jar 包支持

httpclient-4.3.1.jar
httpcore-4.3.jar
commons-logging-1.0.4.jar

编写工具类

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

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class HttpUtils {

    private static final String UTF_8 = "UTF-8";

    public static String post(String url, Map<String, Object> params)
            throws Exception {
        String result = "";
        HttpClient client = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);

        if (params != null && !params.isEmpty()) {
            List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                String name = entry.getKey();
                String value = entry.getValue().toString();
                BasicNameValuePair pair = new BasicNameValuePair(name, value);
                parameters.add(pair);
            }
            httpPost.setEntity(new UrlEncodedFormEntity(parameters, UTF_8));
        }
        try {
            HttpResponse response = client.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == 200) {
                result = EntityUtils.toString(response.getEntity(), UTF_8);
            } else {
                throw new Exception(response.toString());
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;
    }

    public static String get(String url, Map<String, Object> params) throws Exception {
        String result = "";
        HttpClient client = HttpClients.createDefault();

        if (params != null && !params.isEmpty()) {
            StringBuffer buffer = new StringBuffer();
            buffer.append("?");
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                String name = entry.getKey();
                String value = URLEncoder.encode(entry.getValue().toString(), UTF_8);
                buffer.append(name).append("=").append(value).append("&");
            }
            url += buffer.substring(0, buffer.length()-1).toString();
        }

        HttpGet get = new HttpGet(url);
        get.setHeader("charset", UTF_8);

        try {
            HttpResponse response = client.execute(get);
            if (response.getStatusLine().getStatusCode() == 200) {
                result = EntityUtils.toString(response.getEntity(), UTF_8);
            } else {
                throw new Exception(response.toString());
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
}

编写测试代码

import java.util.HashMap;
import java.util.Map;

public class HttpTest {

    public static void main(String[] args) {

        String url = "http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo";
        try {
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("mobileCode", "1888888");
            params.put("userID", "");
            String result = HttpUtils.get(url, params);
            System.out.println("GET请求:\n" + result);
            result = HttpUtils.post(url, params);
            System.out.println("POST请求:\n" + result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

测试结果

GET请求:
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://WebXml.com.cn/">1888888:北京 北京 北京移动全球通卡</string>
POST请求:
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://WebXml.com.cn/">1888888:北京 北京 北京移动全球通卡</string>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值