gpt4 book ai didi

java - 使用 POST 方法的 RESTful Java 客户端

转载 作者:太空宇宙 更新时间:2023-11-04 06:36:01 25 4
gpt4 key购买 nike

我的 Rest 客户端有问题。我的服务

@POST
@Path("/post")
@Consumes("text/plain")
public Response getNumber(String a){
return Response.status(201).entity("Number is: "+a.toString()).build();
}

我的客户

   try{
URL url = new URL("http://localhost:8080/RESTform/core/take/post");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "text/plain");
String input = "123";
OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();
if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
}
catch(MalformedURLException e){}
catch(IOException e){}

我的路径是:ProjectName/core/take/post在 Eclipse 中的服务器上调试后,我收到一条消息:

输入状态报告,消息方法不允许,描述 所请求的资源不允许指定的 HTTP 方法。汤姆猫8.0.9

请帮助我:(

最佳答案

我仅将 jersey 1.9 版本提供的 jars(全部)包含到我的库中。

这是 REST 服务:

导入 javax.ws.rs.Consumes;
导入 javax.ws.rs.GET;
导入 javax.ws.rs.POST;
导入javax.ws.rs.Path;
导入 javax.ws.rs.Produces;
导入 javax.ws.rs.core.MediaType;
导入 javax.ws.rs.core.Response;
@Path("/你好")

public class HelloWorld {

@POST
@Path("/post")
@Consumes("text/plain")
public Response getNumber(String a){
return Response.status(201).entity("Number is: "+a.toString()).build();
}
}

这是其余的客户端:import java.io.BufferedReader;
导入java.io.IOException;
导入 java.io.InputStreamReader;
导入 java.io.OutputStream;
导入 java.net.HttpURLConnection;
导入 java.net.MalformedURLException;
导入java.net.URL;

public class Test {
public static void main(String[] args) {

try {
URL url = new URL("http://localhost:5050/REST-simple/rest-simple/hello/post");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "text/plain");
String input = "123";
OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();
if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (MalformedURLException e) {
} catch (IOException e) {
}
}}

试试这个你应该得到输出。

关于java - 使用 POST 方法的 RESTful Java 客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25377566/

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