从JAVA代码向RESTAPI发送HTTP GET请求中的JSON数据

从JAVA代码向RESTAPI发送HTTP GET请求中的JSON数据,java,json,rest,curl,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代码内部发出此请求。我曾尝试通过谷歌和堆栈溢出搜索解决方案。我所发现的只是如何通过查询字符串发送数据,或者如何通过POST请求发送JSON数据

我正在向我的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数据


谢谢

如果您的项目是Maven项目,您可以使用Jersey客户端库,只需在pom.xml中包含com.sun.Jersey组id中的Jersey客户端和Jersey json工件即可。 要连接到web服务,您需要WebResource对象:

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);
网络资源= ClientHelper.createClient()资源(UriBuilder.fromUri(“”.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对象,则可以删除accept调用,只将String.class作为get参数,并将返回值分配给普通字符串。

Spring的RESTTemplate还可用于发送所有REST请求,即get、put、POST、DELETE

通过使用,您可以通过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();
RestTemplate RestTemplate=new RestTemplate();
列表>();
添加(新映射JacksonHttpMessageConverter());
restemplate.setMessageConverters(列表);
Person=新人();
字符串url=”http://localhost:8080/add";
HttpEntity=新的HttpEntity(个人);
//调用Restful web服务,使用jackson将person序列化为对象
ResponseEntity response=restTemplate.postForEntity(url、实体、Person.class);
Person=response.getBody();

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

创建一个名为RestClient.java的类,该类将具有get和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;
    }

}
封装测试;
导入java.io.IOException;
导入org.codehaus.jackson.JsonParseException;
导入org.codehaus.jackson.map.JsonMappingException;
导入org.codehaus.jackson.map.ObjectMapper;
导入com.javamad.utils.JsonUtils;
导入com.sun.jersey.api.client.client;
导入com.sun.jersey.api.client.ClientResponse;
导入com.sun.jersey.api.client.WebResource;
公共类RestClient{
公共静态T post(字符串url、T数据、T){
试一试{
Client=Client.create();
WebResource=client.resource(url);
ClientResponse response=webResource.type(“application/json”).post(ClientResponse.class,JsonUtils.javaToJson(data));
if(response.getStatus()!=200){
抛出新的RuntimeException(“失败:HTTP错误代码:”
+response.getStatus());
}
字符串输出=response.getEntity(String.class);
System.out.println(“响应===post=“+output”);
t=(t)JsonUtils.jsonToJavaObject(输出,t.getClass());
}捕获(JSONParsee异常){
//TODO自动生成的捕捉块
e、 printStackTrace();
}捕获(JsonMappingException e){
//TODO自动生成的捕捉块
e、 printStackTrace();
}捕获(IOE异常){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
返回t;
}
公共静态T get(字符串url,T)
{
试一试{
Client=Client.create();
WebResource=client.resource(url);
ClientResponse response=webResource.accept(“application/json”).get(ClientResponse.class);
if(response.getStatus()!=200){
抛出新的RuntimeException(“失败:HTTP错误代码:”
+response.getStatus());
}
字符串输出=response.getEntity(String.class);
System.out.println(“响应===get=“+output”);
t=(t)JsonUtils.jsonToJavaObject(输出,t.getClass());
}捕获(JSONParsee异常){
//TODO自动生成的捕捉块
e、 printStackTrace();
}捕获(JsonMappingException e){
//TODO自动生成的捕捉块
e、 printStackTrace();
}捕获(IOE异常){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
返回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);

    }

    }
公共类问题解答服务{
静态字符串baseUrl=”http://javamad.com/javamad-webservices-1.0";
//最终字符串baseUrl=”http://javamad.com/javamad-webservices-1.0";
@试验
公共问题{
System.out.println(“javamad.baseurl=“+baseurl”);
GetQuestionResponse GQRResponse=新GetQuestionResponse();
gqResponse=RestClient.get(baseUrl+“/v1/questionAnswerService/getQuestions?questionType=2”,gqResponse);
List qList=new ArrayList();
qList=(List)gqResponse.getQuestionList();
//系统输出打印LN(gqResponse);
}
公共问题{
PostQuestionResponse pqResponse=新的PostQuestionResponse();
PostQuestionRequest pqRequest=新的PostQuestionRequest();
pqRequest.setQuestion(“可能正在工作”);
pqRequest.setQuestionType(“2”);
pqRequest.setUser_id(“2”);
//Map m=新的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;
    }

}
package com.javamad.utils;
导入java.io.IOException;
导入org.apache.log4j.Logger;
导入org.codehaus.jackson.jsongGenerationException;
导入org.codehaus.jackson.JsonParseException;
导入org.codehaus.jackson.map.JsonMappingException;
导入org.codehaus.jackson.map.ObjectMapper;
公共类JsonUtils{
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;
<!--    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>