标签: resttemplate

java.lang.IllegalArgumentException:使用 RestTemplate 时 [0] 没有匹配常量

我正在运行一个程序,它将针对某个 url 生成一些负载,并使用 RestTemplate 进一步使用相同的 URL。

我点击的网址将返回一个简单的字符串Hello World作为响应。

下面的程序将根据 url 生成负载。

public class ShellbareboneLnP {

    public static void main(String[] args) {

        try {

            // create thread pool with given size
            ExecutorService service = Executors.newFixedThreadPool(threads);

            // queue some tasks
            long startTime = System.currentTimeMillis();
            long endTime = startTime + (durationOfRun * 60 * 1000);

            for (int i = 0; i < threads; i++) {
                service.submit(new ShellBareboneTask(endTime));
            }

            service.shutdown();
            service.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
        } catch (InterruptedException e) {
            LOG.warn("Threw a Interrupted Exception in" …
Run Code Online (Sandbox Code Playgroud)

java illegalargumentexception resttemplate

0
推荐指数
1
解决办法
1万
查看次数

Spring RestTemplate I/O错误:没有对等证书

尝试获取https资源时,我总是得到同样的错误:

org.springframework.web.client.ResourceAccessException: I/O error: No peer certificate; nested exception is javax.net.ssl.SSLPeerUnverifiedException: No peer certificate
Run Code Online (Sandbox Code Playgroud)

我有一个自签名虚拟主机,我的应用程序运行,应用程序正常,http但我需要https.

这是我的Android应用程序中的代码:

mRestTemplate = new RestTemplate();
mRestTemplate.getMessageConverters().add(new GsonHttpMessageConverter());
mRestTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());

final ResponseObject responseObject = mRestTemplate.postForObject(APP_URL, requestObject, ResponseObject.class);
Run Code Online (Sandbox Code Playgroud)

更新1

  • 我尝试了@nilesh提出的解决方案但没有奏效.

  • 我尝试了这个解决方案同样的错误

    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, HTTP.DEFAULT_CONTENT_CHARSET);
    HttpProtocolParams.setUseExpectContinue(params, true);
    
    SchemeRegistry schReg = new SchemeRegistry();
    schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schReg);
    
    client = DefaultHttpClient(conMgr, params);
    
    final HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(); …
    Run Code Online (Sandbox Code Playgroud)

ssl spring android self-signed resttemplate

0
推荐指数
1
解决办法
5244
查看次数

为什么我的控制器发送内容类型“应用程序/八位字节流”?

我有一个 REST 控制器:

@RequestMapping(value = "greeting", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
@Transactional(readOnly = true)
@ResponseBody
public HttpEntity<GreetingResource> greetingResource(@RequestParam(value = "message", required = false, defaultValue = "World") String message) {
    GreetingResource greetingResource = new GreetingResource(String.format(TEMPLATE, message));
    greetingResource.add(linkTo(methodOn(AdminController.class).greetingResource(message)).withSelfRel());
    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.add("Content-Type", "application/json; charset=utf-8");
    return new ResponseEntity<GreetingResource>(greetingResource, responseHeaders, HttpStatus.OK);
}
Run Code Online (Sandbox Code Playgroud)

如您所见,我正在努力指定控制器返回的内容类型。

它是通过 REST 客户端访问的:

public String getGreetingMessage() {
    String message;
    try {
        HttpHeaders httpHeaders = Common.createAuthenticationHeaders("stephane" + ":" + "mypassword");
        ResponseEntity<GreetingResource> responseEntity = restTemplate.getForEntity("/admin/greeting", GreetingResource.class, httpHeaders);
        GreetingResource greetingResource …
Run Code Online (Sandbox Code Playgroud)

java spring spring-mvc resttemplate

0
推荐指数
1
解决办法
4万
查看次数

使用RestTemplate-如何将参数中的列表或数组从客户端传递到服务器

我有一个List<Integer>要发送到服务器的参数,Spring是否可以为此提供支持?

我尝试使用以下代码,

restTemplate.exchange("http://xxx.xx.xx.xx:8081/api/cart-items?cartItemsId={cartItemsId[]}", 
            HttpMethod.POST, httpEntity, Void.class, ArrayUtils.toPrimitive(cartItemsId.toArray(new Integer[cartItemsId.size()])));
Run Code Online (Sandbox Code Playgroud)

但是它向服务器发送如下内容:

http://xxx.xx.xx.xx:8081/api/cart-items?cartItemsId=%5BI@18275d8c

如果我使用,也会发生相同的问题:

restTemplate.exchange("http://xxx.xx.xx.xx:8081/api/cart-items?cartItemsId={cartItemsId[]}", 
            HttpMethod.POST, httpEntity, Void.class, cartItemsId);
Run Code Online (Sandbox Code Playgroud)

要么

restTemplate.exchange("http://xxx.xx.xx.xx:8081/api/cart-items?cartItemsId={cartItemsId[]}", 
            HttpMethod.POST, httpEntity, Void.class, cartItemsId.toArray(new Integer[cartItemsId.size()]));
Run Code Online (Sandbox Code Playgroud)

有什么方法可以使用参数将此列表或数组发送到服务器?

spring resttemplate

0
推荐指数
1
解决办法
5132
查看次数

Java 中的 RestTemplate - RestTemplate 没有足够的变量值

我有以下内容:

final String notification = "{\"DATA\"}";
final String url = "http://{DATA}/create";
ResponseEntity<String> auth = create(address, name, psswd, url);
Run Code Online (Sandbox Code Playgroud)

攻击该方法:

private ResponseEntity<String> create(final String address, final String name,
                                                          final String newPassword, final String url) {
        final Map<String, Object> param = new HashMap<>();
        param.put("name", name);
        param.put("password", newPassword);
        param.put("email", address);

        final HttpHeaders header = new HttpHeaders();

        final HttpEntity<?> entity = new HttpEntity<Object>(param, header);

        RestTemplate restTemplate = new RestTemplate();
        return restTemplate.postForEntity(url, entity, String.class);
    }
Run Code Online (Sandbox Code Playgroud)

我认为它应该有效,但它让我

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalArgumentException: Not …
Run Code Online (Sandbox Code Playgroud)

java url spring spring-mvc resttemplate

0
推荐指数
1
解决办法
2万
查看次数

下载 PDF 文件并捕获文件名

我有一个 PDF 资源的 URL,但它不能通过文件名来识别。该请求如下所示:

GET /api/docs/12345
Accept: application/pdf
Run Code Online (Sandbox Code Playgroud)

响应是:

Status: 200 OK
Content-Type: application/pdf
Content-Disposition: attachment; filename="sample.pdf"
Run Code Online (Sandbox Code Playgroud)

当我使用 Postman 调用 api 时,它会提示使用默认文件名“response”保存文件。因此文件保存为“response.pdf”。我需要使用 RestTemplate 客户端以编程方式执行此操作。我如何捕获响应,以便我可以提取文件名(如上面的响应中所示,它是sample.pdf),并且我可以相应地保存文件,而不是诸如“response.pdf”之类的通用文件名

resttemplate spring-boot

0
推荐指数
1
解决办法
5415
查看次数

RestTemplate 抛出通用 400 错误请求,但自定义服务器发送的消息不会丢失

我们有一个带有 POST 映射的休息控制器 API,它将一个对象作为请求参数并在数据库上创建相同的对象。我们对输入对象进行了很少的验证,如果有任何错误,那么我们将抛出带有自定义消息的异常。

如果我们从邮递员调用此 API,我们会看到相应的错误。

然而,当我们使用 Spring 的 RestTemplate 在其他应用程序的调用者方法中调用此方法时,我们看到的只是一个带有空正文的 400 Bad 请求。没有看到错误消息。

这里可能有什么问题。我们如何获取 API 抛出的自定义消息。

以下是我们如何使用 Rest 模板调用 API。

    String url = "https://localhost:8895/servuceUrl";
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    HttpEntity<AddRequest> entity = new HttpEntity<AddRequest>(obj, headers);
    ResponseEntity<String> data = null;
    adddata = restTemplate.exchange(syncurl, HttpMethod.POST, entity, String.class);
Run Code Online (Sandbox Code Playgroud)

在服务器端我们有一个异常写为

@ResponseStatus(value=HttpStatus.BAD_REQUEST)
public class InvalidDataException extends Exception {


    public InvalidDataException(String msg) {
        super(msg);
    }
}
Run Code Online (Sandbox Code Playgroud)

控制器看起来像

@PostMapping(RestUriMappings.POST_MAPPING)
public ResponseDto add(@Valid @RequestBody AddRequest data) throws InvalidDataException 
{

    logger.debug("Incoming data for add: {}", data.toString());

    // …
Run Code Online (Sandbox Code Playgroud)

java spring resttemplate spring-boot

0
推荐指数
1
解决办法
7262
查看次数

How to Send Emojis using RestTemplate in Spring Boot?

My requirement is to send JSON data from service (A) to another service (B), in this case, I am sending emojis in JSON using Spring Boot RestTemplate. If I send a request from A to B, in the service B the message is displayed as a text with a question mark(?) instead of emoji.

Sending this JSON data

{
"from": "1233222225",
"to":  "8585855858",
"message": "Hello A, hope you are doing 23012020 "
}
Run Code Online (Sandbox Code Playgroud)

displays in service B as

{
"from": …
Run Code Online (Sandbox Code Playgroud)

java resttemplate spring-boot microservices spring-rest

0
推荐指数
1
解决办法
2323
查看次数

java.lang.ClassNotFoundException: com.fasterxml.jackson.dataformat.xml.XmlMapper

正在使用 Spring boot 2.1.1 在使用 org.springframework.web.client.RestTemplate 时出现以下错误

java.lang.ClassNotFoundException: com.fasterxml.jackson.dataformat.xml.XmlMapper
    at java.net.URLClassLoader.findClass(Unknown Source) ~[na:1.8.0_191]
    at java.lang.ClassLoader.loadClass(Unknown Source) ~[na:1.8.0_191]
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) ~[na:1.8.0_191]
    at java.lang.ClassLoader.loadClass(Unknown Source) ~[na:1.8.0_191]
    at 
    org.springframework.http.converter.json
    .Jackson2ObjectMapperBuilder.build(Jackson2ObjectMapperBuilder.java:617) ~[spring-web- 
    5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter.<init> 
    (MappingJackson2XmlHttpMessageConverter.java:50) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at 
Run Code Online (Sandbox Code Playgroud)

从我的pom:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.1.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
</dependency>
Run Code Online (Sandbox Code Playgroud)

在创建 org.springframework.web.client.RestTemplate 对象时,我收到此异常

我该如何解决?

resttemplate java-8 spring-boot jackson-databind

0
推荐指数
1
解决办法
3595
查看次数

不带主体的 Spring RestTemplate POST 方法

我正在尝试编写一个客户端,在其中我将执行没有正文的 POST 方法。插入null是唯一的解决方案吗?例子:

client.exchange("/" + userId + "/logout", HttpMethod.POST, null, String.class);
Run Code Online (Sandbox Code Playgroud)

spring resttemplate spring-resttemplate

0
推荐指数
1
解决办法
7455
查看次数