user3923278 user3923278 - 4 months ago 112
Android Question

android Error converting result java.io.FileNotFoundException

I have created an API in post method which is working fine in postman i.e it is giving desired response. But while using that API in Android it is giving error:


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


I would appreciate anyone guiding me on how to do this.

Here is the code of
makeHttpRequest
method of
jsonparser
:

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;

}

Answer

Add this to your code:

conn.setDoInput(true); //After or before of setDoOutput(true) for organization :)
conn.setChunkedStreamingMode(0);
conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");

EDIT :
And this if you need to upload a JSON for the server:

conn.setRequestProperty("Content-Length", "" + Integer.toString(JsonObjectstr.getBytes().length)); // Get the json string length
Comments