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

发送GET和POST请求

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

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

  1. 第一步,引入依赖
        
            org.apache.httpcomponents
            httpclient
            4.5.2
        

        
            org.apache.httpcomponents
            httpcore
            4.4.5
        

  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 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;
    }

}

你可能感兴趣的:(java,java,开发,GET,POST,工具类)