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

标签 java json rest curl

我正在向我的 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 代码中发出这个请求。我尝试通过 Google 和堆栈溢出搜索解决方案。我所发现的只是如何通过查询字符串发送数据或如何通过 POST 请求发送 JSON 数据。

谢谢

最佳答案

使用下面的代码,您应该能够调用任何 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 到 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;
    }

}

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

希望对你有所帮助。

关于java - 将 HTTP GET 请求中的 JSON 数据从 JAVA 代码发送到 REST API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23645878/

相关文章:

iphone - xcode检查是否存在NSArray并包含对象?

xml - 在 RestEasy 中从 ExceptionMapper 返回 JSON 的简单方法?

javascript - Node js 中 Json 长度始终未定义

java - REST HttpURL 连接

java - 何时以及如何在我的 Rest Api 中实例化 Spring Bean

java - 无法在 Spring 中 Autowiring RequestMappingHandleMapping

java - 线程 hibernate 的工作方式与预期不同

java - 将包私有(private)类导入 JShell

java - 将 Java applet 项目导入 netbeans 将无法正常工作,即使手动设置,Netbeans 也拒绝识别甚至找不到主类

rest - 用于创建和编辑表单的REST URL