android错误转换结果java.io.FileNotFoundException
我已经在post中创建了一个API方法,该方法在postman中运行良好,即提供了所需的响应。但在Android中使用该API时,会出现以下错误: 转换结果java.io.FileNotFoundException时出错,分析数据org.json.jsoneException时出错:输入结束,位于的字符0处 我将感谢任何人指导我如何做到这一点 下面是android错误转换结果java.io.FileNotFoundException,java,android,json,api,Java,Android,Json,Api,我已经在post中创建了一个API方法,该方法在postman中运行良好,即提供了所需的响应。但在Android中使用该API时,会出现以下错误: 转换结果java.io.FileNotFoundException时出错,分析数据org.json.jsoneException时出错:输入结束,位于的字符0处 我将感谢任何人指导我如何做到这一点 下面是jsonparser的makeHttpRequest方法的代码: public JSONObject makeHttpRequest2(String
jsonparser
的makeHttpRequest
方法的代码:
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.setDoInput(true); //After or before of setDoOutput(true) for organization :)
conn.setChunkedStreamingMode(0);
conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
编辑:如果需要为服务器上载JSON,请执行以下操作:
conn.setRequestProperty("Content-Length", "" + Integer.toString(JsonObjectstr.getBytes().length)); // Get the json string length
首先,在调用
conn.getInputStream()之前,您没有检查请求是否成功代码>如果请求失败,则流为空,您需要调用
new BufferedReader(new InputStreamReader(connection.getErrorStream()));
给你的问题是什么行号?如果打印JSON以确保响应是有效的JSON