简体   繁体   English

在 HTTP GET 请求中将 JSON 数据从 JAVA 代码发送到 REST API

[英]Send JSON data in an HTTP GET request to a REST API from JAVA code

I am making the following curl request successfully to my API:我正在向我的 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/

I would like to know how can i make this request from inside JAVA code.我想知道如何从 JAVA 代码内部发出此请求。 I have tried searching through Google and stack overflow for the solution.我尝试通过 Google 和堆栈溢出搜索解决方案。 All i have found is how to send data through a query string or how to send JSON data through a POST request.我所发现的只是如何通过查询字符串发送数据或如何通过 POST 请求发送 JSON 数据。

Thanks谢谢

Using below code you should be able to invoke any rest API.使用下面的代码,您应该能够调用任何 rest API。

Make a class called RestClient.java which will have method for get and post创建一个名为 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;
    }

}

invoke the get and post method调用 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);

    }

    }

Make your own Request and response class.制作自己的请求和响应类。

for json to java and java to json use below class对于 json 到 java 和 java 到 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;
    }

}

I wrote the RestClient.java class , to reuse the get and post methods.我编写了 RestClient.java 类,以重用 get 和 post 方法。 similarly you can write other methods like put and delete...同样,您可以编写其他方法,例如放置和删除...

Hope it will help you.希望它会帮助你。

You could use the Jersey client library, if your project is a Maven one just include in your pom.xml the jersey-client and jersey-json artifacts from the com.sun.jersey group id.您可以使用 Jersey 客户端库,如果您的项目是 Maven,则只需在 pom.xml 中包含来自 com.sun.jersey 组 ID 的 jersey-client 和 jersey-json 工件。 To connect to a web service you need a WebResource object:要连接到 Web 服务,您需要一个WebResource对象:

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

To make a call sending a payload you can model the payload as a POJO, ie要进行发送有效载荷的呼叫,您可以将有效载荷建模为 POJO,即

class Payload {
    private String query;
    private int mode;

    ... get and set methods
}

and then call the call using the resource object:然后使用资源对象调用调用:

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);

where ResultType is the Java mapped return type of the called service, in case it's a JSON object, otherwise you can remove the accept call and just put String.class as the get parameter and assign the return value to a plain string.其中 ResultType 是被调用服务的 Java 映射返回类型,以防它是 JSON 对象,否则您可以删除接受调用并将 String.class 作为获取参数并将返回值分配给普通字符串。

Spring's RESTTemplate is also useful for sending all REST requests ie GET , PUT , POST , DELETE Spring 的 RESTTemplate 也可用于发送所有 REST 请求,即 GET 、 PUT 、 POST 、 DELETE

By usingSpring REST template , You can pass JSON request with POST like below,通过使用Spring REST 模板,您可以使用 POST 传递 JSON 请求,如下所示,

You can pass JSON representation serialized into java Object using JSON serializer such as jackson您可以使用 JSON 序列化程序(例如 jackson)将序列化为 java Object 的 JSON 表示传递

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();

Struggled on the same question and found a nice solution using the gson .在同一个问题上gson挣扎,并使用gson找到了一个不错的解决方案。

The code:编码:

// 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();
    }
}

The packages:包:

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;

My pom.xml :我的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>

I hope this helps you!我希望这可以帮助你!

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

相关问题 Java:发送POST HTTP请求以将文件上传到MediaFire REST API - Java: send POST HTTP request to upload a file to MediaFire REST API Parse.com REST API错误代码400:从Java HTTP请求到云功能的错误请求 - Parse.com REST API Error Code 400: Bad Request from Java HTTP Request to Cloud Function 如何将带有JSON对象的“放置”请求发送到Java中的JSONPlaceHolder REST API - How to send a “Put” request with a JSON object to a JSONPlaceHolder REST API in Java 将带有JSON数据的POST请求从HTML发送到Java Rest Web服务时出现HTTP错误415 - HTTP Error 415 when sending POST request with JSON data from HTML to Java Rest web service 在 java/spring boot 中的 HTTP GET 请求中发送 JSON 正文 - Send JSON body in HTTP GET request in java/spring boot 在 Postman 的请求正文中传递多个 JSON 数据并使用 Jersy(JXRS) 进入 Java Rest API - Pass multiple JSON data in Request Body of Postman and Get into Java Rest API using Jersy(JXRS) 使用Java代码中的JIRA REST API的GET方法时出现HTTP 401异常 - HTTP 401 exception while using GET method of JIRA REST API from Java Code Java:从HTTP GET请求获取数据 - Java: getting data from HTTP GET request 从应用WP REST API发送GET请求 - send GET request from app WP REST API 如何从Java REST API请求解码PHP中的JSON? - How to decode JSON in PHP from Java REST API request?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM