繁体   English   中英

使用rest模板发送帖子数据

[英]sending post data using rest template

我正在尝试模仿以下请求:

curl -d
"client_id=pxb5bw&client_secret=yMwN&grant_type=password&username=foi&password=wdY"
"https://connect.xyz.com/oauth2/token" -k

使用休息模板

春季

package spring;



import com.fasterxml.jackson.core.JsonProcessingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.FormHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.w3c.dom.Entity;

public class Spring {

    private final RestTemplate restTemplate;


    public Spring(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;


    }




    public void call() 
{
    Spring client = null;


    client.restTemplate.getMessageConverters().add(new FormHttpMessageConverter());
    client.restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    HttpEntity<String> entity = new HttpEntity<String>(headers);
    MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
        map.add("grant_type", "password");
        map.add("client_id", "dsgdsfg");
                map.add("client_secret", "gvsdfg");
                map.add("username","foi");
                map.add("password", "wdY");
        ResponseEntity<String> result = restTemplate.postForEntity("https://connect.gettyimages.com/oauth2/token ", entity, String.class, map);
        System.out.println(result);




}


}

驱动程序

package spring;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Driver {

    public static void main(String[] args) throws Exception {
            ApplicationContext applicationContext =
                new ClassPathXmlApplicationContext("resources/ApplicationContext.xml", Driver.class);
        Spring client = applicationContext.getBean("springClient", Spring.class);
        client.call();
    }

}

ApplicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>

<!-- ~ Copyright 2009 the original author or authors. ~ ~ Licensed under the Apache License, Version 2.0 (the "License"); ~ you may not use this file except in compliance with the License. ~ You may obtain a copy of the License at ~ ~ http://www.apache.org/licenses/LICENSE-2.0 ~ ~ Unless required by applicable law or agreed to in writing, software ~ distributed under the License is distributed on an "AS IS" BASIS, ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ~ See the License for the specific language governing permissions and ~ limitations under the License. -->

<beans xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans">


<bean class="spring.Spring" id="springClient">

<constructor-arg ref="restTemplate"/>



</bean>


<bean class="org.springframework.web.client.RestTemplate" id="restTemplate">


</bean>

</beans>

运行项目时,在“结果”处得到一个空指针异常。 我是Springs的新手,请帮忙

Oct 02, 2014 4:39:04 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@1aa0e220: startup date [Thu Oct 02 16:39:04 EDT 2014]; root of context hierarchy
Oct 02, 2014 4:39:04 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring/resources/ApplicationContext.xml]
Exception in thread "main" java.lang.NullPointerException
    at spring.Spring.call(Spring.java:52)
    at spring.Driver.main(Driver.java:18)
Java Result: 1
BUILD SUCCESSFUL (total time: 1 second)

感谢大家的答复,但是我解决了问题。...问题是API调用什么也没返回,但是下面的代码解决了问题......

 package spring;



import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.core.JsonProcessingException;
import java.text.Normalizer.Form;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.FormHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.w3c.dom.Entity;

public class Spring {

    private final RestTemplate restTemplate;


    public Spring(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;


    }




    public void call() 
{
    Spring client = null;



    HttpHeaders headers = new HttpHeaders();
    headers.set("Api-Key", "pbw");
HttpEntity<String> entity = new HttpEntity<String>(headers);
       ResponseEntity<String> responseEntity =  restTemplate.exchange("https://connect.gettyimages.com/v3/search/images?phrase=books&fields=detail_set", HttpMethod.GET, entity, String.class);
System.out.println(responseEntity.getBody());




MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
                map.add("grant_type", "password");
                map.add("client_id", "ps5bw");
                map.add("client_secret", "y9vPRwN");
                map.add("username","foi");
                map.add("password", "ErdY");

HttpHeaders headers1 = new HttpHeaders();
headers1.setContentType(MediaType.APPLICATION_FORM_URLENCODED);      

HttpEntity<MultiValueMap<String, String>> entity1 = new HttpEntity<MultiValueMap<String, String>>(map, headers1);

 List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();

 messageConverters.add(new FormHttpMessageConverter());
 messageConverters.add(new StringHttpMessageConverter());
 restTemplate.setMessageConverters(messageConverters);


        ResponseEntity<String> result = restTemplate.exchange("https://connect.gettyimages.com/oauth2/token",HttpMethod.POST,entity1,  String.class );
        System.out.println(result);









}


}

正如Mike K提到的问题是,您正在调用NULL对象并期望发生某些事情,因此这就是Nul​​lPointerException出现的原因。

public void call() 
{
    Spring client = null;

// you need to initiliase the client object before you can call the below line
    client.restTemplate.getMessageConverters().add(new FormHttpMessageConverter());
    //rest of code

解决该问题,您的NullPointerException将消失。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM