gpt4 book ai didi

java - POST 请求 JSON 解析器 Java

转载 作者:行者123 更新时间:2023-12-02 12:45:07 25 4
gpt4 key购买 nike

POST Request Java

我读过这篇关于如何在 Java 中执行 POST 请求的文章。我不明白如何在 JSON 解析器中实现它。这是我到目前为止尝试过的:

public class JSONParser {
private String read(BufferedReader bufferedReader) throws IOException {
//Creates new StringBuilder to avoid escaping chars
StringBuilder stringBuilder = new StringBuilder();
//Gets the currentLine
String currentLine;
while((currentLine = bufferedReader.readLine()) !=null ){
//Adds the currentLine to the stringBuild if the currentLine is not null
stringBuilder.append(currentLine);
}
//Returns the StringBuilder is String format
return stringBuilder.toString();
}

public JSONObject readJsonFromUrl(String JSONurl) throws IOException, JSONException {
InputStream url = new URL(JSONurl).openStream();
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(url));
String jsonText = read(bufferedReader);
JSONObject json = new JSONObject(jsonText);
return json;
} finally {
url.close();
}
}

public void printJSON() throws IOException, JSONException {
JSONObject json = readJsonFromUrl("http://grwn.ddns.net:1337/locations");
System.out.print(json);

//for (Integer i = 0; i < json.getJSONArray("damage_or_theft_car").length(); i++) {
// System.out.println(json.getJSONArray("damage_or_theft_car")
//.getJSONObject(i).get("hood_id"));
//}
}
}

当我使用不需要 POST 请求的链接运行此代码时,一切正常,但是当我在需要 POST 请求的链接上运行此代码时,出现以下错误:

Exception in thread "main" java.io.FileNotFoundException: http://grwn.ddns.net:1337/locations
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1872)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1474)
at java.net.URL.openStream(URL.java:1045)
at com.company.JSONParser.readJsonFromUrl(JSONParser.java:30)
at com.company.JSONParser.printJSON(JSONParser.java:42)
at com.company.Main.main(Main.java:33)

有人可以帮助我或为我指明正确的方向吗?

最佳答案

我认为您需要指定在打开连接后要发出 POST 请求,也许可以尝试这样的操作。

public JSONObject readJsonFromUrl(String JSONurl) throws IOException, JSONException {
URL url = new URL(JSONurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProprtry("Content-type", "application/JSON");
try {
BufferedReader bufferedReader = new BufferedReader(conn. getInputStream());
String jsonText = read(bufferedReader);
JSONObject json = new JSONObject(jsonText);
return json;
} finally {
url.close();
}
}

关于java - POST 请求 JSON 解析器 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44797785/

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