gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 03:23:09 28 4
gpt4 key购买 nike

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

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com