将HTTP GET请求中的JSON数据从JAVA代码发送到REST API [英] Send JSON data in an HTTP GET request to a REST API from JAVA code

查看:129
本文介绍了将HTTP GET请求中的JSON数据从JAVA代码发送到REST API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am making the following curl request successfully to my API:

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代码内部发出此请求.我曾尝试通过Google搜索并在堆栈溢出中找到解决方案.我所发现的就是如何通过查询字符串发送数据或如何通过POST请求发送JSON数据.

I would like to know how can i make this request from inside JAVA code. I have tried searching through Google and stack overflow for the solution. All i have found is how to send data through a query string or how to send JSON data through a POST request.

谢谢

推荐答案

使用以下代码,您应该能够调用任何其他API.

Using below code you should be able to invoke any rest API.

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

Make a class called RestClient.java which will have method for get and post

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方法

invoke the get and post method

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.

将json转换为java并将java转换为json使用以下类

for json to java and java to json use below class

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方法.同样,您可以编写其他方法,例如放置和删除...

I wrote the RestClient.java class , to reuse the get and post methods. similarly you can write other methods like put and delete...

希望它会对您有所帮助.

Hope it will help you.

这篇关于将HTTP GET请求中的JSON数据从JAVA代码发送到REST API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆