gson 我的发布请求返回状态代码404,我不确定原因[已关闭]

5fjcxozz  于 2022-12-13  发布在  其他
关注(0)|答案(1)|浏览(227)

**已关闭。**此问题需要debugging details。当前不接受答案。

编辑问题以包含desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem。这将有助于其他人回答问题。
11小时前关门了。
Improve this question
我对API和Java都很陌生,但我正试图通过制作一个简单的天气应用程序来理解,然而我下面的代码一直返回错误代码404。如有任何帮助,我将不胜感激。

public class Weather_Api_Class {
    
    public static void main(String[] args) throws URISyntaxException, IOException, InterruptedException {
        Transcript transcript = new Transcript();
        transcript.setUrl("https://api.open-meteo.com/v1/forecast?latitude=53.33&longitude=-6.25&hourly=temperature_2m");
        Gson gson = new Gson();
        String jsonRequest = gson.toJson(transcript);
        System.out.println(jsonRequest);
        HttpRequest postRequest = HttpRequest.newBuilder()
            .uri(new URI("https://api.open-meteo.com/v1/forecast?"))
            .POST(BodyPublishers.ofString(jsonRequest))
            .build();
    
        HttpClient httpClient =  HttpClient.newHttpClient();
        HttpResponse<String> postResponse = httpClient.send(postRequest, BodyHandlers.ofString());
        System.out.println(postResponse.statusCode());
    }

}
voj3qocg

voj3qocg1#

看起来你应该做一个GET而不是POST。我用curl来模拟你正在用java尝试的东西。

curl -X POST -vvv 'https://api.open-meteo.com/v1/forecast?latitude=53.33&longitude=-6.25&hourly=temperature_2m'

这会重现问题。得到以下输出:

HTTP/2 404 
date: Sun, 11 Dec 2022 13:37:36 GMT
content-type: application/json; charset=utf-8
content-length: 35

* Connection #0 to host api.open-meteo.com left intact
{"error":true,"reason":"Not Found"}* Closing connection 0

POST更改为GET,会有有用的输出:
第一次
通常,POST请求用于创建数据,而GET请求用于检索数据。
下面是一个修改后的程序,它成功地检索了预测数据。关键的变化是在创建HttpRequest时删除了.POST指令。它默认为GET。我还删除了一些与问题不直接相关的对象。您必须根据需要将它们添加回处理输出。

import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URI;
import java.net.http.*;

public class Weather_Api_Class {

    public static void main(String[] args) throws URISyntaxException, IOException, InterruptedException {
        String url = "https://api.open-meteo.com/v1/forecast?latitude=53.33&longitude=-6.25&hourly=temperature_2m";
        HttpRequest getRequest = HttpRequest.newBuilder()
            .uri(new URI(url))
            .build();

        HttpClient httpClient =  HttpClient.newHttpClient();
        HttpResponse<String> getResponse = httpClient.send(getRequest, HttpResponse.BodyHandlers.ofString());
        System.out.println(getResponse.statusCode());
        System.out.println(getResponse.body());
    }

}

相关问题