首页 > 编程语言 >Java 第三方链接请求工具

Java 第三方链接请求工具

时间:2023-11-28 10:15:19浏览次数:31  
标签:Java String 第三方 return import apache new null 链接

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
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.methods.HttpPut;
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;
import javax.net.ssl.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 第三方链接请求工具
 */
public class HttpClientUtil {
    /**
     * 使用httpclint 发送请求
     *
     * @param url   调用的连接
     * @param parms 使用map装入需要调用的参数名与值
     * @return 响应结果
     */
    public static JSONObject doPostForm(String url, Map<String, String> parms) {
        HttpPost httpPost = new HttpPost(url);
        ArrayList<BasicNameValuePair> list = new ArrayList<>();
        parms.forEach((key, value) -> list.add(new BasicNameValuePair(key, value)));
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            if (Objects.nonNull(parms) && parms.size() > 0) {
                httpPost.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
            }
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            JSONObject jsonObject = JSON.parseObject(EntityUtils.toString(entity, "UTF-8"));
            return jsonObject;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (Objects.nonNull(httpClient)) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public static JSONObject doPutForm(String url, Map<String, String> parms) throws Exception {
        HttpPut httpPut = new HttpPut(url);
        ArrayList<BasicNameValuePair> list = new ArrayList<>();
        parms.forEach((key, value) -> list.add(new BasicNameValuePair(key, value)));
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            if (Objects.nonNull(parms) && parms.size() > 0) {
                httpPut.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
            }
            InputStream content = httpPut.getEntity().getContent();
            InputStreamReader inputStreamReader = new InputStreamReader(content, "UTF-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String readLine = bufferedReader.readLine();
            String s = URLDecoder.decode(readLine, "UTF-8");
            HttpResponse response = httpClient.execute(httpPut);
            HttpEntity entity = response.getEntity();
            JSONObject jsonObject = JSON.parseObject(EntityUtils.toString(entity, "UTF-8"));
            return jsonObject;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (Objects.nonNull(httpClient)) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public static JSONObject doGetForm(String url, Map<String, String> parms) throws Exception {
        ArrayList<BasicNameValuePair> list = new ArrayList<>();
        parms.forEach((key, value) -> list.add(new BasicNameValuePair(key, value)));
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            //3、转化参数
            String params = EntityUtils.toString(new UrlEncodedFormEntity(list, Consts.UTF_8));
            //4、创建HttpGet请求
            HttpGet httpGet = new HttpGet(url + "?" + params);
            CloseableHttpResponse response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            JSONObject jsonObject = JSON.parseObject(EntityUtils.toString(entity, "UTF-8"));
            return jsonObject;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (Objects.nonNull(httpClient)) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * 发送HttpPost请求,参数为map
     *
     * @param url
     * @param map
     * @return
     */
    public static String sendPost(String url, Map<String, String> map) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            //给参数赋值
            formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
        HttpPost httppost = new HttpPost(url);
        httppost.setEntity(entity);
        CloseableHttpResponse response = null;
        System.out.println(map);
        try {
            response = httpclient.execute(httppost);
        } catch (IOException e) {
            e.printStackTrace();
        }
        HttpEntity entity1 = response.getEntity();
        String result = "";
        try {
            InputStream content = entity1.getContent();
            BufferedReader in = null;
            in = new BufferedReader(
                    new InputStreamReader(content, "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url   发送请求的 URL
     * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param, Map<String, String> header) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = null;
            if ("https".equals(realUrl.getProtocol())) {
                SSLContext ctx = SSLContext.getInstance("TLS");
                X509TrustManager tm = new X509TrustManager() {
                    @Override
                    public void checkClientTrusted(X509Certificate[] chain, String authType) {
                    }
                    @Override
                    public void checkServerTrusted(X509Certificate[] chain, String authType) {
                    }
                    @Override
                    public X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }
                };
                ctx.init(null, new TrustManager[]{tm}, null);
                HttpsURLConnection connHttps = (HttpsURLConnection) realUrl.openConnection();
                connHttps.setSSLSocketFactory(ctx.getSocketFactory());
                connHttps.setHostnameVerifier(new HostnameVerifier() {
                    public boolean verify(String hostname, SSLSession session) {
                        return true;//默认认证不通过,进行证书校验。
                    }
                });
                conn = connHttps;
            } else {
                conn = (HttpURLConnection) 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)");
            for (Map.Entry<String, String> entry : header.entrySet()) {
                conn.setRequestProperty(entry.getKey(), entry.getValue());
            }
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            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();
            }
        }
        return result;
    }
}

 

简单的示例:

public static void main(String[] args) {
     //第三方URL
        String apiUrl = "";
        
        Map<String, String> header = new HashMap<>();
        header.put("token", "token");
        StringBuffer params = new StringBuffer();
        params.append("app_key=").append("app_key").append("&");
        params.append("keyword=").append("keyword").append("&");

        String str = HttpClientUtil.sendPost(apiUrl, params.toString(), header);
        return str;
    }

 

标签:Java,String,第三方,return,import,apache,new,null,链接
From: https://www.cnblogs.com/springclout/p/17861220.html

相关文章

  • Java8使用并行流(ParallelStream)注意事项
    本文转载自简书:https://www.jianshu.com/p/51c1d4f1bf84著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 Java8并行流ParallelStream和Stream的区别就是支持并行执行,提高程序运行效率。但是如果使用不当可能会发生线程安全的问题。Demo如下:1publics......
  • 用java写一个抽奖程序
    需求分析1)实现三个基本功能:登录、注册、抽奖。2)登录:用户输入账号密码进行登录,输入账号后会匹配已注册的用户,若输入用户不存在则退出,密码有三次输入机会,登录成功后主界面会显示已登录用户的账号信息。3)注册:用户首先输入账号名称,系统查询此名称是否存在,如存在则请求用户换一个名称,......
  • Java 实现统一社会信用代码有效性校验
    一、调用工具类:importcom.yf.utils.StringUtils;importjava.util.HashMap;importjava.util.Map;/***统一社会信用代码有效性校验**@authorFengQing*@programruoyi-vue-file*@description*@date2023/09/11*/publicclassTyshxydmVerificationUtil......
  • Java 将JSON数组转成List对象集合
     一、从对象列表中提取并组装JSON字段的数据:(工具类)publicclassJsonMsgUtils<T>{/***从对象列表中提取并组装JSON字段的数据。**@paramlogs包含对象的列表*@paramtargetClass目标对象类型,表示JSON消息的结构......
  • Java并发编程:面向对象思想与并发编程思想的融合
    1.封装共享变量1.1识别可变化与不变的共享变量识别可变化与不可变化的共享变量。针对初始化后不再改变的变量,可以添加final修饰。不仅编译器编译更快,也对后续开发人员指明了变量属性,更防范了意想不到的修改行为。1.2针对可变化的共享变量,进行封装处理针对共享变量的访问,若......
  • Java实现并行功能
    Java8线程池异步处理-->针对小包大MyTask 类中的 compute() 方法首先检查任务的规模是否小于等于1。如果是,它直接返回任务的结果。否则,它将任务拆分成两个子任务(leftTask 和 rightTask),并使用 fork() 方法将它们提交到 ForkJoinPool 中执行。这里定义了一个名为 My......
  • java System
    packagenet.elaina.system;publicclassTest1{publicstaticvoidmain(String[]args){/*publicstaticvoidexit(intstatus)终止当前运行的Java虚拟机publicstaticlongcurrentTimeMillis()返回当前系统的时间毫秒值形式p......
  • 支持修改键值的优先队列(以C++,Java为例)
    #include<queue>#include<functional>template<typenameT1,typenameT2>classmutable_priority_queue;template<typenameT1,typenameT2>classmutable_priority_queue{private:std::function<bool(conststd::pair<T1,T......
  • Java的Buffer流输入封装类
    importjava.io.BufferedReader;importjava.io.IOException;importjava.io.InputStreamReader;importjava.util.StringTokenizer;classQuickReader{privatefinalBufferedReaderbufferedReader=newBufferedReader(newInputStreamReader(System.in));......
  • 八股文-Java方法的重载与重写
    在Java中,重载和重写是两个关键的面向对象编程概念。重载通过方法的参数列表不同来区分同名方法,提供了更灵活的方法调用方式。而重写通过子类重新定义父类中已经存在的方法,实现了多态性的体现,让代码更具可扩展性和维护性。重载(Overloading)重载是指在同一个类中可以定义多个方法......