首页 > 编程语言 >用javax.ws.rs.client.Invocation queryParam 执行url中带参数的请求

用javax.ws.rs.client.Invocation queryParam 执行url中带参数的请求

时间:2024-05-15 15:21:14浏览次数:16  
标签:中带 String rs url token client import configuration target

来自于百度AI,为了实际需要,改成我自己的环境。

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.client.ClientProperties;
import org.glassfish.jersey.jackson.JacksonFeature;
import org.glassfish.jersey.media.multipart.MultiPartFeature;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import java.util.*;

public static void main(String[] args) {
    ClientConfig configuration = new ClientConfig();
    configuration = configuration.property(ClientProperties.CONNECT_TIMEOUT, 30000);
    configuration = configuration.property(ClientProperties.READ_TIMEOUT, 30000);
    Client client = ClientBuilder.newBuilder().withConfig(configuration).hostnameVerifier((s1, s2) -> true).register(new JacksonFeature()).build();

    // 定义目标服务的WebTarget,通用:Client client = ClientBuilder.newClient();
    WebTarget target = client.target("https://urlpath/list?limit=1000000&service=22503");
    // 添加查询参数
    String paramName = "service";
    Integer paramValue = 22503;
    WebTarget withQueryParam = target.queryParam(paramName, paramValue);
    String token = "actual token value";    
    // 发送请求,例如Post请求,通用:String response = withQueryParam.request().header("token",token).post(null,String.class);
    String response = withQueryParam.register(MultiPartFeature.class)
            .request(MediaType.APPLICATION_JSON).header("token", token).post(null, String.class);
    // 输出响应
    System.out.println(response);
    // 关闭客户端
    client.close();
}

 

之前把baseurl和相对路径分开用 client.target(baseUrl).path(path),查询结果为空,后来改成 client.target(absoluteUrl); 能正确返回结果。所以path(relativePath)用的时候有限制,但是还不知道原因,暂时不管了,用 client.target(absoluteUrl) 就行

public Invocation.Builder getBuilder(String relativePath, Map<String, Object> queryParameters) {
    ClientConfig configuration = new ClientConfig();
    configuration = configuration.property(ClientProperties.CONNECT_TIMEOUT, 30000);
    configuration = configuration.property(ClientProperties.READ_TIMEOUT, 30000);
    Client client = ClientBuilder.newBuilder().withConfig(configuration).hostnameVerifier((s1, s2) -> true).register(new JacksonFeature()).build();
    if (baseUrl == null) {
        baseUrl = EnvConfig.base_url;
    }
    String absoluteUrl = baseUrl + relativePath;
    WebTarget webTarget = client.target(absoluteUrl);

    for (Map.Entry entry : queryParameters.entrySet()) {
        webTarget = webTarget.queryParam(entry.getKey().toString(), entry.getKey().toString());
    }
    return webTarget.register(MultiPartFeature.class)
            .request(MediaType.APPLICATION_JSON)
            .header("token", token);
}


public <T> T doQueryParamPostRequest(String url, Map<String, Object> queryParams, Object payload, Class<T> klass) {
    Invocation.Builder invoker = this.getBuilder(url, queryParams);
    try {
        return invoker.post(Entity.entity(payload, MediaType.APPLICATION_JSON), klass);
    } catch (ProcessingException ex) {
        try {
            return invoker.post(Entity.entity(payload, MediaType.APPLICATION_JSON), klass);
        } catch (ProcessingException ex1) {
            CommonUtil.sleep(3000);
            return invoker.post(Entity.entity(payload, MediaType.APPLICATION_JSON), klass);
        }
    }
}

 

标签:中带,String,rs,url,token,client,import,configuration,target
From: https://www.cnblogs.com/panda4671/p/18193917

相关文章

  • RSA加解密懒得写了,记录一下代码
    packagecom.hoyo.common.core.utils;importcom.hoyo.common.core.utils.uuid.UUID;importsun.misc.BASE64Decoder;importsun.misc.BASE64Encoder;importjavax.crypto.Cipher;importjava.io.ByteArrayOutputStream;importjava.nio.charset.StandardCharsets;importjava......
  • 量化交易:财务选股RSRS择时的策略
    哈喽,大家好,我是木头左!引言本文将介绍一种结合财务指标选股和RSRS(Risk-AdjustedReturntoStrengthRatio)择时的策略,旨在帮助投资者在复杂的市场环境中做出更明智的决策。感兴趣的朋友,可以在下方公号内回复:001,即可获取源码,共同交流!策略原理财务指标选股财务指标选股是一种......
  • RSA 具有单向陷门置换的性质
    这篇文章我们介绍RSA的单向性,置换型等等.我们给出formal的RSA假设:RSA假设.给定一个三元组\((N,e,y)\),其中\(N\)是大素数\(p,q\)的乘积,\(gcd(e,\Phi(N))=1\),\(y\in\mathbbZ_n^*\),那么对于任意的PPT敌手\(\mathcalA\),能够找到\(x\)使得\(x^e=y......
  • CSS cursor(鼠标样式)
    属性值示意图描述auto 默认值,由浏览器根据当前上下文确定要显示的光标样式default默认光标,不考虑上下文,通常是一个箭头none 不显示光标initial 将此属性设置为其默认值inherit 从父元素基础cursor属性的值context-menu表示上下文菜单可用......
  • Python 常用第三方库 urllib3使用
    urllib3概述线程安全连接池管理客户端SSL/TLS验证支持HTTP和SOCKS代理官方文档:urllib32.0.4documentationurllib3安装通过pip安装pipinstallurllib3urllib3发送HTTP请求导入urllib3模块创建PoolManager实例调用request()方法importur......
  • CTF中RSA相关题型总结(持续更新)
    e很小时:importgmpy2fromfunctoolsimportreducefromCrypto.Util.numberimportlong_to_bytesdefCRT(items):N=reduce(lambdax,y:x*y,(i[1]foriinitems))result=0fora,ninitems:m=N//nd,r,s=gmpy2.gcdext(......
  • 时钟server 时钟质量等级--PRC、PRS、SSU
    PRC(PrimaryReferenceClock,基准参考时钟):G.811时钟信号SSU-A(primarylevelSSU,转接局时钟):G.812转接节点时钟信号SSU-B(secondlevelSSU,本地局时钟):G.812本地节点时钟信号SEC(SDHEquipmentClock,设备时钟):SDH设备时钟源信号DNU(DoNotUseforsynchronization,不应用作......
  • Linux 使用 curl 发送请求
    前言请各大网友尊重本人原创知识分享,谨记本人博客:南国以南i、提示:以下是本篇文章正文内容,下面案例可供参考#get请求json入参curlhttp://xxx.xxx:60512/scrm/chat/msg/selectFullChatListForDay-d'{"key":"215EACF20778586C788FFD9187AB0F72","qrDay":"2023-04-25"}�......
  • [996] Upload a file to an Amazon S3 bucket and obtain the URL of it using Python
    Certainly!TouploadafiletoanAmazonS3bucketusingPython(specificallywiththeboto3library)andobtainthelink(URL)forthatfile,followthesesteps:InstallBoto3:Makesureyouhavetheboto3libraryinstalled.Ifnot,youcaninstallit......
  • Преимущества RS485 для сбора данных LoRaWAN
    СборщикданныхRS485toLoRaWAN—этосборщикданных,которыйиспользуетстандартныйпротоколLoRaWANдлябеспроводногоинтерфейсавосходящейлиниисв......