首页 > 其他分享 >Springboot使用RestTemplate发送Post请求postForEntity (application-json)的坑

Springboot使用RestTemplate发送Post请求postForEntity (application-json)的坑

时间:2024-12-25 11:35:36浏览次数:3  
标签:gt postForEntity RestTemplate application lt values new ------------- public

Springboot使用RestTemplate发送Post请求postForEntity (application-json)的坑| Id | Title | DateAdded | SourceUrl | PostType | Body | BlogId | Description | DateUpdated | IsMarkdown | EntryName | CreatedTime | IsActive | AutoDesc | AccessPermission |

| -------------| -------------| -------------| -------------| -------------| -------------| -------------| -------------| -------------| -------------| -------------| -------------| -------------| -------------| -------------|
| 16334421| Springboot使用RestTemplate发送Post请求postForEntity (application/json)的坑| 2022-06-01T15:32:00| | BlogPost|

当使用RestTemplate进行http请求时,的确很方便,但是当需要进行post请求时遇到了坑

1POST传递参数 :采用 LinkedMultiValueMap ,不能使用HashMap

String url = 'http://posturl';
  MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>();        
 map.add("shopid","1");       
 HttpHeaders headers = new HttpHeaders();       
 headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);        
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers);        
return restTemplate.postForEntity(url, request,String.class);


注意 上面的请求支持参数类型均为String类型,如果MultiValueMap<String, Object>  LinkedMultiValueMap 会将value放进list中,key --> [value]

2 采用JSONObject或者实体类传递参数

        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
    JSONObject param </span>= <span style="color: #0000ff;">new</span><span style="color: #000000;"> JSONObject();
    param.put(</span>"username", "123"<span style="color: #000000;">);
    
    HttpEntity</span>&lt;String&gt; formEntity = <span style="color: #0000ff;">new</span> HttpEntity&lt;String&gt;<span style="color: #000000;">(param, headers);

    String result </span>= restTemplate.postForObject(url, formEntity, String.<span style="color: #0000ff;">class</span>);</pre>
public class LinkedMultiValueMap<K, V> implements MultiValueMap<K, V>, Serializable, Cloneable {
    private static final long serialVersionUID = 3801124242820219131L;
    private final Map<K, List<V>> targetMap;
</span><span style="color: #0000ff;">public</span><span style="color: #000000;"> LinkedMultiValueMap() {
    </span><span style="color: #0000ff;">this</span>.targetMap = <span style="color: #0000ff;">new</span><span style="color: #000000;"> LinkedHashMap();
}

</span><span style="color: #0000ff;">public</span> LinkedMultiValueMap(<span style="color: #0000ff;">int</span><span style="color: #000000;"> initialCapacity) {
    </span><span style="color: #0000ff;">this</span>.targetMap = <span style="color: #0000ff;">new</span><span style="color: #000000;"> LinkedHashMap(initialCapacity);
}

</span><span style="color: #0000ff;">public</span> LinkedMultiValueMap(Map&lt;K, List&lt;V&gt;&gt;<span style="color: #000000;"> otherMap) {
    </span><span style="color: #0000ff;">this</span>.targetMap = <span style="color: #0000ff;">new</span><span style="color: #000000;"> LinkedHashMap(otherMap);
}

@Nullable
</span><span style="color: #0000ff;">public</span><span style="color: #000000;"> V getFirst(K key) {
    List</span>&lt;V&gt; values = (List)<span style="color: #0000ff;">this</span><span style="color: #000000;">.targetMap.get(key);
    </span><span style="color: #0000ff;">return</span> values != <span style="color: #0000ff;">null</span> &amp;&amp; !values.isEmpty() ? values.get(0) : <span style="color: #0000ff;">null</span><span style="color: #000000;">;
}

</span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">void</span><span style="color: #000000;"> add(K key, @Nullable V value) {
    List</span>&lt;V&gt; values = (List)<span style="color: #0000ff;">this</span>.targetMap.computeIfAbsent(key, (k) -&gt;<span style="color: #000000;"> {
        </span><span style="color: #0000ff;">return</span> <span style="color: #0000ff;">new</span><span style="color: #000000;"> LinkedList();
    });
    values.add(value);
}
</span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">void</span> addAll(K key, List&lt;? <span style="color: #0000ff;">extends</span> V&gt;<span style="color: #000000;"> values) {
    List</span>&lt;V&gt; currentValues = (List)<span style="color: #0000ff;">this</span>.targetMap.computeIfAbsent(key, (k) -&gt;<span style="color: #000000;"> {
        </span><span style="color: #0000ff;">return</span> <span style="color: #0000ff;">new</span><span style="color: #000000;"> LinkedList();
    });
    currentValues.addAll(values);
}
</span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">void</span> addAll(MultiValueMap&lt;K, V&gt;<span style="color: #000000;"> values) {
    Iterator var2 </span>=<span style="color: #000000;"> values.entrySet().iterator();
    </span><span style="color: #0000ff;">while</span><span style="color: #000000;">(var2.hasNext()) {
        Entry</span>&lt;K, List&lt;V&gt;&gt; entry =<span style="color: #000000;"> (Entry)var2.next();
        </span><span style="color: #0000ff;">this</span><span style="color: #000000;">.addAll(entry.getKey(), (List)entry.getValue());
    }
}
</span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">void</span><span style="color: #000000;"> set(K key, @Nullable V value) {
    List</span>&lt;V&gt; values = <span style="color: #0000ff;">new</span><span style="color: #000000;"> LinkedList();
    values.add(value);
    </span><span style="color: #0000ff;">this</span><span style="color: #000000;">.targetMap.put(key, values);
}
</span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">void</span> setAll(Map&lt;K, V&gt;<span style="color: #000000;"> values) {
    values.forEach(</span><span style="color: #0000ff;">this</span><span style="color: #000000;">::set);
}
</span><span style="color: #0000ff;">public</span> Map&lt;K, V&gt;<span style="color: #000000;"> toSingleValueMap() {
    LinkedHashMap</span>&lt;K, V&gt; singleValueMap = <span style="color: #0000ff;">new</span> LinkedHashMap(<span style="color: #0000ff;">this</span><span style="color: #000000;">.targetMap.size());
    </span><span style="color: #0000ff;">this</span>.targetMap.forEach((key, values) -&gt;<span style="color: #000000;"> {
        </span><span style="color: #0000ff;">if</span> (values != <span style="color: #0000ff;">null</span> &amp;&amp; !<span style="color: #000000;">values.isEmpty()) {
            singleValueMap.put(key, values.get(</span>0<span style="color: #000000;">));
        }

    });
    </span><span style="color: #0000ff;">return</span><span style="color: #000000;"> singleValueMap;
}</span></pre>

 

| 648658| Springboot使用RestTemplate发送Post请求postForEntity (application/json)的坑| 2022-06-01T15:32:00| false| | 2022-06-01T15:32:18.11| true| 当使用RestTemplate进行http请求时,的确很方便,但是当需要进行post请求时遇到了坑 1POST传递参数 :采用 LinkedMultiValueMap ,不能使用HashMap String url = 'http://posturl'; MultiValueMap<String, | Anonymous|

标签:gt,postForEntity,RestTemplate,application,lt,values,new,-------------,public
From: https://www.cnblogs.com/ralphlauren/p/18621301

相关文章

  • [转]使用matplotlib绘图,报错“This application failed to start because no Qt platf
    问题使用matplotlib绘图时,报错:ThisapplicationfailedtostartbecausenoQtplatformplugincouldbeinitialized.Reinstallingtheapplicationmayfixthisproblem.Availableplatformpluginsare:minimal,offscreen,webgl,windows.如图  解决方法:impor......
  • Application Binary Interface(ABI)
    ApplicationBinaryInterface(ABI)是指应用程序在二进制级别上的调用约定和数据布局规则。它决定了一个程序如何与操作系统、库或其他程序的二进制部分交互。ABI是在编译后的程序之间的接口,而不是在源码层面的接口。ABI的主要内容函数调用约定(CallingConventions)定义了函......
  • 传输层安全协议TLS 超全解析!(含record、handshake握手全流程、Alert、ApplicationData)
    TLS协议概述SSL即安全套接字层,它位于OSI网络模型中的传输层,SSL在1999年更名为TLS,即传输安全层,直到现在,TLS一共出现过三个版本,1.1、1.2和1.3,目前最广泛使用的是1.2,所以接下来的探讨都是基于TLS1.2的版本上的。设计目标保密性通过加密算法保护数据内容,......
  • yaml to properties failed, reason: Parse yaml file content failed for namespace:
    背景springboot2.2.x升级到是springboot2.7.x,apollo-client也跟着升级到了2.0.1,配置中心使用.properties的应用启动正常,使用.yml报了上面的错误解决方案版本降级到1.33解决下面是ai回答的结果让我们尝试几个可能的解决方案:检查你的SpringBoot版本和SnakeYAML版......
  • How to enable core file dumps when an application crashes or segmentation faults
    OriginalarticleEnvironmentRedHatEnterpriseLinux5RedHatEnterpriseLinux4RedHatEnterpriseLinux3ForRedHatEnterpriseLinux6,7,8,9,pleaserefertheNOTEintheresolutionsection.IssueHowtoenablecorefiledumpswhenanapplic......
  • Shell Scripts to start and Stop Spring Boot Applications.
    Inthispost,WewilllearnaboutstartandstopshellscriptstorunSpringBootapplications.Springbootapplicationsareeasiertobuildandrun.However,thereisonesmallproblem.Mostofthedevelopersstillstrugglewhenitcomestorunning,stop......
  • ITP4206 Proprietary Mobile Application
    ITP4206ProprietaryMobileApplicationDevelopmentIndividualAssignment2023-24(20%ofoverallmarks)Objective:Bycompletingtheassignment,studentscanbefamiliarthebasicfeaturesoftheSwiftprogramminglanguage.practicethroughthestepsto......
  • 探索Spring之利剑:ApplicationContext接口
    嘿,开发者们!你是否曾在构建Spring应用时,感到困惑于那些复杂的配置和神秘的容器?今天,我们将揭开Spring中一个核心接口——ApplicationContext​的神秘面纱。这不仅是一篇技术文章,更是一次深入Spring心脏的探险之旅。系好安全带,我们即将启程!......
  • Implementing Memory in LLM Applications Using LangChain
    ImplementingMemoryinLLMApplicationsUsingLangChainhttps://www.codecademy.com/article/implementing-memory-in-llm-applications-using-lang-chain老版本https://python.langchain.com/v0.1/docs/modules/memory/types/buffer/ HowtomigratetoLangGraphmemor......
  • Post请求的两种编码格式:application/x-www-form-urlencoded和multipart/form-data
    一、前端表单提交时application/x-www-form-urlencoded表单代码:<formaction="http://localhost:8888/task/"method="POST">Firstname:<inputtype="text"name="firstName"value="Mickey&"><br>Last......