【问题标题】:Send JSON data in an HTTP GET request to a REST API from JAVA code将 HTTP GET 请求中的 JSON 数据从 JAVA 代码发送到 REST API
【发布时间】:2014-07-01 23:46:26
【问题描述】:

我正在向我的 API 成功发出以下 curl 请求:

curl -v -X GET -H "Content-Type: application/json" -d {'"query":"some text","mode":"0"'} http://host.domain.abc.com:23423/api/start-trial-api/

我想知道如何从 JAVA 代码中发出这个请求。我曾尝试通过谷歌和堆栈溢出搜索解决方案。我所发现的只是如何通过查询字符串发送数据或如何通过 POST 请求发送 JSON 数据。

谢谢

【问题讨论】:

  • 到目前为止您看过哪些网页? GET 和 POST 的区别非常小。
  • 您正在执行 GET 并在正文中发送 json 数据。这是故意的吗?
  • 如果我错了,请纠正我,但是您甚至可以在 GET 请求中发送正文吗? GET 不会忽略 -d 吗?
  • @AlexandreSantos 有意发送带有 GET 请求的正文。
  • @metacubed curl 请求有效。我能够使用 API 中的数据。我只需要知道如何通过 JAVA 代码发出相同的 curl 请求。

标签: java json rest curl


【解决方案1】:

使用下面的代码,您应该能够调用任何 REST API。

创建一个名为 RestClient.java 的类,该类将具有获取和发布的方法

package test;

import java.io.IOException;

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

import com.javamad.utils.JsonUtils;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;

public class RestClient {

    public static <T> T post(String url,T data,T t){
        try {
        Client client = Client.create();
        WebResource webResource = client.resource(url);
        ClientResponse response = webResource.type("application/json").post(ClientResponse.class, JsonUtils.javaToJson(data));

        if (response.getStatus() != 200) {
            throw new RuntimeException("Failed : HTTP error code : "
                 + response.getStatus());
        }
        String output = response.getEntity(String.class);
        System.out.println("Response===post="+output);

            t=(T)JsonUtils.jsonToJavaObject(output, t.getClass());
        } catch (JsonParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JsonMappingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return t;
    }
    public static <T> T get(String url,T t)
    {
         try {
        Client client = Client.create();

        WebResource webResource = client.resource(url);

        ClientResponse response = webResource.accept("application/json").get(ClientResponse.class);

        if (response.getStatus() != 200) {
           throw new RuntimeException("Failed : HTTP error code : "
            + response.getStatus());
        }

        String output = response.getEntity(String.class);
        System.out.println("Response===get="+output);



            t=(T)JsonUtils.jsonToJavaObject(output, t.getClass());
        } catch (JsonParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JsonMappingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return t;
    }

}

调用get和post方法

public class QuestionAnswerService {
    static String baseUrl="http://javamad.com/javamad-webservices-1.0";

    //final String baseUrl="http://javamad.com/javamad-webservices-1.0";
    @Test
    public void getQuestions(){
        System.out.println("javamad.baseurl="+baseUrl);
        GetQuestionResponse gqResponse=new GetQuestionResponse();

        gqResponse =RestClient.get(baseUrl+"/v1/questionAnswerService/getQuestions?questionType=2",gqResponse);


        List qList=new ArrayList<QuestionDetails>();
        qList=(List) gqResponse.getQuestionList();

        //System.out.println(gqResponse);

    }

    public void postQuestions(){
        PostQuestionResponse pqResponse=new PostQuestionResponse();
        PostQuestionRequest pqRequest=new PostQuestionRequest();
        pqRequest.setQuestion("maybe working");
        pqRequest.setQuestionType("2");
        pqRequest.setUser_id("2");
        //Map m= new HashMap();
        pqResponse =(PostQuestionResponse) RestClient.post(baseUrl+"/v1/questionAnswerService/postQuestion",pqRequest,pqResponse);

    }

    }

制作自己的请求和响应类。

对于 json to java 和 java to json 使用下面的类

package com.javamad.utils;

import java.io.IOException;

import org.apache.log4j.Logger;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

public class JsonUtils {

    private static Logger logger = Logger.getLogger(JsonUtils.class.getName());


    public static <T> T jsonToJavaObject(String jsonRequest, Class<T> valueType)
            throws JsonParseException, JsonMappingException, IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(org.codehaus.jackson.map.DeserializationConfig.Feature.UNWRAP_ROOT_VALUE,false);     
        T finalJavaRequest = objectMapper.readValue(jsonRequest, valueType);
        return finalJavaRequest;

    }

    public static String javaToJson(Object o) {
        String jsonString = null;
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.configure(org.codehaus.jackson.map.DeserializationConfig.Feature.UNWRAP_ROOT_VALUE,true);  
            jsonString = objectMapper.writeValueAsString(o);

        } catch (JsonGenerationException e) {
            logger.error(e);
        } catch (JsonMappingException e) {
            logger.error(e);
        } catch (IOException e) {
            logger.error(e);
        }
        return jsonString;
    }

}

我编写了 RestClient.java 类,以重用 get 和 post 方法。同样,您可以编写其他方法,例如 put 和 delete...

希望对你有帮助。

【讨论】:

    【解决方案2】:

    Spring 的 RESTTemplate 也可用于发送所有 REST 请求,即 GET 、 PUT 、 POST 、 DELETE

    通过使用Spring REST template,您可以使用下面的 POST 传递 JSON 请求,

    您可以使用 JSON 序列化器(例如 jackson)将序列化的 JSON 表示传递到 java 对象中

    RestTemplate restTemplate = new RestTemplate();
    List<HttpMessageConverter<?>> list = new ArrayList<HttpMessageConverter<?>>();
    list.add(new MappingJacksonHttpMessageConverter());
    restTemplate.setMessageConverters(list);
    Person person = new Person();
    String url = "http://localhost:8080/add";
    HttpEntity<Person> entity = new HttpEntity<Person>(person);
    
    // Call to Restful web services with person serialized as object using jackson
    ResponseEntity<Person> response = restTemplate.postForEntity(  url, entity, Person.class);
    Person person = response.getBody();
    

    【讨论】:

      【解决方案3】:

      您可以使用 Jersey 客户端库,如果您的项目是 Maven 项目,只需在您的 pom.xml 中包含来自 com.sun.jersey 组 ID 的 jersey-client 和 jersey-json 工件。 要连接到 Web 服务,您需要一个 WebResource 对象:

      WebResource 资源 = ClientHelper.createClient().resource(UriBuilder.fromUri("http://host.domain.abc.com:23423/api/").build());

      要发送有效负载的调用,您可以将有效负载建模为 POJO,即

      class Payload {
          private String query;
          private int mode;
      
          ... get and set methods
      }
      

      然后使用资源对象调用调用:

      Payload payload = new Payload();
      
      payload.setQuery("some text"); payload.setMode(0);
      
      ResultType result = service  
          .path("start-trial-api").  
          .type(MediaType.APPLICATION_JSON)  
          .accept(MediaType.APPLICATION_JSON)  
          .get(ResultType.class, payload);
      

      其中 ResultType 是被调用服务的 Java 映射返回类型,如果它是 JSON 对象,否则您可以删除接受调用并将 String.class 作为 get 参数并将返回值分配给纯字符串。

      【讨论】:

        【解决方案4】:

        在同一个问题上苦苦挣扎,并使用gson 找到了一个不错的解决方案。

        代码:

        // this method is based on gson (see below) and is used to parse Strings to json objects
        public static JsonParser jsonParser = new JsonParser();
        
        public static void getJsonFromAPI() {
            // the protocol is important
            String urlString = "http://localhost:8082/v1.0/Datastreams"
            StringBuilder result = new StringBuilder();
        
            try {
                URL url = new URL(urlString);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                String line;  // reading the lines into the result
                while ((line = rd.readLine()) != null) {
                    result.append(line);
                }
                rd.close();
                // parse the String to a jsonElement
                JsonElement jsonObject = jsonParser.parse(result.toString());  
                System.out.println(jsonObject.getAsJsonObject()  // object is a mapping
                        .get("value").getAsJsonArray()  // value is an array
                        .get(3).getAsJsonObject()  // the fourth item is a mapping 
                        .get("name").getAsString());  // name is a String
        
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        

        包:

        import com.google.gson.JsonElement;
        import com.google.gson.JsonObject;
        import com.google.gson.JsonParser;
        import java.io.BufferedReader;
        import java.io.IOException;
        import java.io.InputStreamReader;
        import java.net.HttpURLConnection;
        import java.net.MalformedURLException;
        import java.net.URL;
        import java.util.Properties;
        

        我的pom.xml

        <!--    https://mvnrepository.com/artifact/com.google.code.gson/gson -->
            <dependency>
                <groupId>com.google.code.gson</groupId>
                <artifactId>gson</artifactId>
                <version>2.8.5</version>
            </dependency>
        

        希望对你有帮助!

        【讨论】:

          猜你喜欢
          • 2014-09-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-08-04
          • 2019-12-09
          • 2016-07-19
          • 2020-04-30
          • 2017-05-05
          相关资源
          最近更新 更多