Java使用HttpClient发送GET和POST(带参数)请求

发送GET和POST请求

最近和朋友在开展一个新的项目,需要用到JAVA后台,所以这两天我在努力的进行知识迁移和学习,毕竟对JAVA语言不是很熟悉,所以有许多东西需要学习的。今天我需要调用某平台的接口,需要用到常用的GET和POST请求。

看了需对代码示例,我的天哪,JAVA对待我这个新人,还真不友好,写个请求还需要弄一大堆代码,(据了解其实是有很好用的封装类库,我还不会用)。相比之下,Python的Requets还是更好上手一点~好了,废话不多说,下面呢,我们开始自己封装一下,HttpUtil工具类,有了它妈妈再也不用担心我的JAVA了!额…好吧,过来人告诉我,孩子,你想多了!

  1. 第一步,引入依赖
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.2</version>
        </dependency>

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>4.4.5</version>
        </dependency>

  1. 第二步,好吧,最后一步,封装工具类
package com.example.demo.utils;

import java.io.IOException;
import java.util.Map;

import com.google.gson.JsonObject;
import org.apache.http.*;
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;

# 基本类结构

/**
 * @author Joe_yoy
 *
 */
public class HttpUtil {

		private static final CloseableHttpClient httpclient = HttpClients.createDefault();
		// 继续
}

这里是我用到的工具类, PS:关于json处理的包,我使用了gson
具体使用可以查看某网友的gson的简明使用

2.1 GET请求,不带参数

/**
     * 发送HttpGet请求
     * @param url
     * @return
     */
    public static String sendGet(String url) {

        HttpGet httpget = new HttpGet(url);
        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(httpget);
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        String result = null;
        try {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                result = EntityUtils.toString(entity);
            }
        } catch (ParseException | IOException e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

2.2. GET请求,带参数,放在header里

/**
     * 发送HttpGet带参请求
     * @param url
     * @param header
     * @return
     */
    public static String sendGet(String url, Map<String, String> header) {
        HttpGet httpGet = new HttpGet(url);


        //设置头部
        for(Map.Entry entry:header.entrySet()){
            
            httpGet.setHeader(entry.getKey().toString(),entry.getValue().toString());
        }


        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(httpGet);
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        String result = null;
        try {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                result = EntityUtils.toString(entity);
            }
        } catch (ParseException | IOException e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

2.3. POST请求,不带参数

/**
     * 发送不带参数的HttpPost请求
     * @param url
     * @return
     */
    public static String sendPost(String url) {
        HttpPost httppost = new HttpPost(url);
        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(httppost);
        } catch (IOException e) {
            e.printStackTrace();
        }
        HttpEntity entity = response.getEntity();
        String result = null;
        try {
            result = EntityUtils.toString(entity);
        } catch (ParseException | IOException e) {
            e.printStackTrace();
        }
        return result;
    }

2.4. POST请求,带参数

 /**
     * 发送HttpPost请求,参数为map
     * @param url
     * @param map
     * @return
     */
    public static String sendPost(String url, Map<String,String> map) {

        JsonObject jsonObject = new JsonObject();
        for(Map.Entry entry:map.entrySet()){
			jsonObject.addProperty(entry.getKey().toString(),entry.getValue().toString());
        }   // 以上循环操作是将 Map对象转化成 JsonObject对象
//        System.out.println(jsonObject.toString());
        StringEntity entity = new StringEntity(jsonObject.toString(), Consts.UTF_8);
        HttpPost httppost = new HttpPost(url); 
        httppost.setEntity(entity);     //设置请求体
        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(httppost);
        } catch (IOException e) {
            e.printStackTrace();
        }
        HttpEntity entity1 = response.getEntity();
        String result = null;
        try {
            result = EntityUtils.toString(entity1);
        } catch (ParseException | IOException e) {
            e.printStackTrace();
        }
        return result;
    }

具体的关键解释,放在代码注释里,如果有什么疑问,咱们再作交流~

下面,我将完整代码放于下方

package com.example.demo.utils;

import java.io.IOException;
import java.util.Map;

import com.google.gson.JsonObject;
import org.apache.http.*;
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;

/**
 * @author Joe_yoy
 *
 */
public class HttpUtil {

    private static final CloseableHttpClient httpclient = HttpClients.createDefault();

    /**
     * 发送HttpGet请求
     * @param url
     * @return
     */
    public static String sendGet(String url) {

        HttpGet httpget = new HttpGet(url);
        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(httpget);
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        String result = null;
        try {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                result = EntityUtils.toString(entity);
            }
        } catch (ParseException | IOException e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 发送HttpGet带参请求
     * @param url
     * @param header
     * @return
     */
    public static String sendGet(String url, Map<String, String> header) {
        HttpGet httpGet = new HttpGet(url);


        //设置头部
        for(Map.Entry entry:header.entrySet()){
//            System.out.println(entry.getKey()+ "###########" + entry.getValue());
            httpGet.setHeader(entry.getKey().toString(),entry.getValue().toString());
        }
//        System.out.println(jsonObject.toString());


//        HttpGet httpget = new HttpGet(url);
        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(httpGet);
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        String result = null;
        try {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                result = EntityUtils.toString(entity);
            }
        } catch (ParseException | IOException e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 发送HttpPost请求,参数为map
     * @param url
     * @param map
     * @return
     */
    public static String sendPost(String url, Map<String,String> map) {
//        JsonObject formparams = new JsonObject();
//        for (Map.Entry<String, String> entry : map.entrySet()) {
//            formparams.add(entry.getKey(), entry.getValue();
//        }
        //json 格式
//        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
        JsonObject jsonObject = new JsonObject();
        for(Map.Entry entry:map.entrySet()){
//            System.out.println(entry.getKey()+ "###########" + entry.getValue());
            jsonObject.addProperty(entry.getKey().toString(),entry.getValue().toString());
        }
//        System.out.println(jsonObject.toString());
        StringEntity entity = new StringEntity(jsonObject.toString(), Consts.UTF_8);
        HttpPost httppost = new HttpPost(url);
        httppost.setEntity(entity);
        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(httppost);
        } catch (IOException e) {
            e.printStackTrace();
        }
        HttpEntity entity1 = response.getEntity();
        String result = null;
        try {
            result = EntityUtils.toString(entity1);
        } catch (ParseException | IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 发送不带参数的HttpPost请求
     * @param url
     * @return
     */
    public static String sendPost(String url) {
        HttpPost httppost = new HttpPost(url);
        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(httppost);
        } catch (IOException e) {
            e.printStackTrace();
        }
        HttpEntity entity = response.getEntity();
        String result = null;
        try {
            result = EntityUtils.toString(entity);
        } catch (ParseException | IOException e) {
            e.printStackTrace();
        }
        return result;
    }

}

  • 11
    点赞
  • 45
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
HttpClientJava中的一个开源库,用于支持HTTP协议的客户端编程。它是一个用于发送HTTP请求和接收HTTP响应的包装工具类HttpClient可以被用于执行GET和POST请求HTTP方法。走看看是一个基于Web的应用程序,包含了各种常见的网站功能,如搜索、资讯、体育、财经、购物等多个频道。下面将分别介绍HttpClient发送GET和POST请求时的一些重要知识点。 HttpClient发送GET请求时,需要构造一个HttpGet对象,并指定请求的URL。调用HttpClient.execute方法,并且将HttpGet对象传递给该方法。接下来,HttpClient发送GET请求到指定的URL,然后将响应内容作为一个HttpResponse对象返回给程序。可以从HttpResponse对象中获取响应状态、响应头和响应体等信息。 HttpClient发送POST请求时,需要首先构造一个HttpPost对象,并指定请求的URL。调用HttpPost.setEntity方法来设置请求体内容,然后调用HttpClient.execute方法,并将HttpPost对象传递给该方法。接下来,HttpClient会将POST请求数据发送到指定的URL,然后将响应内容作为一个HttpResponse对象返回给程序。与GET请求相似,可以从HttpResponse对象中获取响应状态、响应头和响应体等信息。 总的来说,HttpClient是一个十分强大和方便的网络编程工具类,可以方便地实现HTTP请求和响应的处理。可以根据自己的需求选择GET和POST请求发送,然后获取响应内容和各种信息。使用HttpClient能够简化开发,提高编程效率,是Java网络编程开发中非常重要的一种库。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值