gpt4 book ai didi

java - 如何从服务器向客户端发送数据

转载 作者:行者123 更新时间:2023-12-01 13:52:14 25 4
gpt4 key购买 nike

我有一个包含 1000 个号码的文件 (data.txt)。我想将此文件从服务器发送到客户端。

客户端

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

ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
WebResource service = client.resource(getBaseURI());

// Get JSON for application
System.out.println(service.path("rest").accept(MediaType.APPLICATION_XML).get(String.class));

}

private static URI getBaseURI() {
return UriBuilder.fromUri("http://localhost8080/data").build();
}

我不知道如何发送数据.txt...

我创建了这个函数..

@Path("/data")
public class Date
{
@GET

@Produces(MediaType.TEXT_HTML)

int[] zmien(Scanner in)
{
int i=0;
int temp[] = new int [50];
while ( in.hasNext() )
{
temp[i] = in.nextInt();
i++;
}
in.close();
return temp;
}

并使用函数 main()

            Date test1 = new Data();        
File file = new File ("data.txt");
Scanner in1 = new Scanner(file);
int kaka[] = new int[10];
kaka = test1.zmien(in1);

但它不起作用...我是 REST 新手,所以我可能会犯一些简单的错误。请帮忙

<小时/>

我不知道如何使用 JSON 发送数据..到目前为止,我一直在创作。

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

ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
WebResource service = client.resource(getBaseURI());

// Get JSON for application
System.out.println(service.path("rest").path("data").accept(MediaType.APPLICATION_JSON).get(String.class));
}

private static URI getBaseURI()
{
return UriBuilder.fromUri("http://localhost:8080").build();
}

还有

@Path("/data")
public class Rest {

@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)

public JSONObject sayData(JSONObject inputJsonObj) throws Exception {

JSONArray numbers = new JSONArray();
numbers.put(2);
numbers.put(2);
numbers.put(3);

JSONObject result = new JSONObject();
result.put("numbers", numbers);

return result;

return outputJsonObj;
}
}

我的目的是使用 JSON 向客户端发送数据。数据位于文件(data.txt)中,现在我尝试发送简单的数组,当我运行程序时,我得到 ->“GET http://localhost:8080/rest/data 返回了 404 Not Found 的响应状态”返回了 404 Not Found 的响应状态...我知道如何发送简单的字符串,但是使用 .txt 我遇到了麻烦..稍后我必须接收这些数据并将其作为 int 数字处理(因为我必须执行一些数学运算在此数据上)

最佳答案

首先您需要决定如何发送数据。如果您想发送数字列表,JSON 可能如下所示: {numbers: [ 1, 2, 3] }

要创建这样的 JSON,请使用 JSONObject 构造函数和“put”等类方法。


JSONArray numbers = new JSONArray();
numbers.add(1);
numbers.add(2);
numbers.add(3);
JSONObject result = new JSONObject();
result.put("numbers", numbers);

然后就可以返回“结果”了。

关于java - 如何从服务器向客户端发送数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19881632/

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