gpt4 book ai didi

java - android 转换结果时出错 java.io.FileNotFoundException

转载 作者:行者123 更新时间:2023-12-01 10:08:19 25 4
gpt4 key购买 nike

我在 post 方法中创建了一个 API,该 API 在 postman 中运行良好,即它给出了所需的响应。但是在 Android 中使用该 API 时出现错误:

Error converting result java.io.FileNotFoundException and Error parsing data org.json.JSONException: End of input at character 0 of

如果有人指导我如何执行此操作,我将不胜感激。

这是jsonparsermakeHttpRequest方法的代码:

public JSONObject makeHttpRequest2(String url2 , String method,
String name, String password) throws IOException {

// Making HTTP request
try {

// check for request method
if (method == "POST") {
// request method is POST

url = new URL(url2);
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setUseCaches(false);
conn.setConnectTimeout(10000);
conn.setReadTimeout(10000);
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Host", "android.schoolportal.gr");
conn.connect();

JSONObject jsonParam = new JSONObject();
jsonParam.put("name", name);
//jsonParam.put("email", email);
jsonParam.put("password", password);
Log.d("json",String.valueOf(jsonParam));
OutputStreamWriter out=new OutputStreamWriter(
conn.getOutputStream());
out.write(jsonParam.toString());
out.close();

}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}

try {
InputStream is = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
Log.e("JSON", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object

try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
Log.d("json3",String.valueOf(json));
// return JSON String
return jObj;

}

最佳答案

首先,在调用 conn.getInputStream(); 之前,您不会检查请求是否成功;如果请求失败,则该流为空,您需要调用

new BufferedReader(new InputStreamReader(connection.getErrorStream()));

哪个行号给您带来了问题?如果打印出 JSON 以确保响应是有效的 JSON。

关于java - android 转换结果时出错 java.io.FileNotFoundException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36315870/

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