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;
}
First off you are not checking that the request was successful, before calling the conn.getInputStream(); If the request failed that stream is empty and you need to call
new BufferedReader(new InputStreamReader(connection.getErrorStream()));
What line number is giving you issue? If you print out the JSON to insure that the response is valid JSON.
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
Related
Ive got
HttpURLConnection urlConnection = null;
String result = "";
try {
String host = "http://www.example.com/json.json";
URL url = new URL(host);
urlConnection = (HttpURLConnection) url.openConnection();
int code = urlConnection.getResponseCode();
if(code==200){
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
if (in != null) {
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject)jsonParser.parse(new InputStreamReader(in, "UTF-8"));
result=(String) jsonObject.get("name");
System.out.print(jsonObject);
}
in.close();
} else { result="9";}
return result;
} catch (MalformedURLException e) {
result="9";
} catch (IOException e) {
result="9";
}
catch (ParseException e) {
e.printStackTrace();
result="9";
}
finally {
urlConnection.disconnect();
}
return result;
When i input valid json data, all is OK, but if i got non json data, i got aplication crash with :
Caused by: java.lang.ClassCastException: java.lang.Long cannot be cast to org.json.simple.JSONObject
I think that
catch (ParseException e) {
e.printStackTrace();
result="9";
}
should handle this, but no.
So what i must do to avoid situation that aplication will crash when i do not get valid json?
The thrown exception is a ClassCastException. Maybe you can catch that exception also by adding another catch?
catch (ClassCastException e) {
e.printStackTrace();
result="9";
}
Try this to make a http request
class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
URL myUrl = null;
HttpURLConnection conn = null;
String response = "";
//String data = params[0];
try {
myUrl = new URL("http://www.example.com/json.json");
conn = (HttpURLConnection) myUrl.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
//one long string, first encode is the key to get the data on your web
//page, second encode is the value, keep concatenating key and value.
//theres another ways which easier then this long string in case you are
//posting a lot of info, look it up.
String postData = URLEncoder.encode("key", "UTF-8") + "=" +
URLEncoder.encode("value", "UTF-8");
OutputStream os = conn.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
bufferedWriter.write(postData);
bufferedWriter.flush();
bufferedWriter.close();
InputStream inputStream = conn.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
String line = "";
while ((line = bufferedReader.readLine()) != null) {
response += line;
}
bufferedReader.close();
inputStream.close();
conn.disconnect();
os.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
#Override
protected void onPostExecute(String s) {
try {
JSONObject jsonObject = new JSONObject(s);
} catch (JSONException e) {
//s may not be json
}
}
}
Before getting String from Json Object, check whether the Json object is not null and has that string. and then try to get it.
if (jsonObject!=null && jsonObject.has("name"))
{
result = jsonObject.get("name");
System.out.print(result);
}
I'm making an app that stores some data on a database, then it retrieves it.
On the server side I'm working with PHP, and on the client side I've got this file that gets the input and pass it to the PHP file.
new AsyncTask<String, String, String>() {
JSONParser jsonParser = new JSONParser();
private ProgressBar pBar;
private String url_post_pet = "http://192.168.0.13/Android/post_pet.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
/**
* Before starting background thread Show Progress Dialog
*/
#Override
protected void onPreExecute() {
super.onPreExecute();
//pBar = new ProgressBar();
//pBar.setIndeterminate(false);
//pBar.setVisibility(View.VISIBLE);
}
#Override
protected String doInBackground(String... args) {
// Building Parameters
HashMap<String, String> params = new HashMap<>();
params.put("name", a);
params.put("breed", BREED);
params.put("type", TYPE);
params.put("images", "Whatever");
params.put("description", c);
params.put("coords", b);
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_post_pet,
"POST", params);
// check log cat for response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create product
}
} catch (JSONException e) {
System.out.println("exception" + e);
e.printStackTrace();
}
System.out.println("nul");
return null;
}
/**
* After completing background task Dismiss the progress dialog
**/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
//pBar.dismiss();
}
}.execute();
}
});
}
Also, i've got this JSONParser:
public class JSONParser {
String charset = "UTF-8";
HttpURLConnection conn;
DataOutputStream wr;
StringBuilder result;
URL urlObj;
JSONObject jObj = null;
StringBuilder sbParams;
String paramsString;
public JSONObject makeHttpRequest(String url, String method,
HashMap<String, String> params) {
sbParams = new StringBuilder();
int i = 0;
for (String key : params.keySet()) {
try {
if (i != 0){
sbParams.append("&");
}
sbParams.append(key).append("=")
.append(URLEncoder.encode(params.get(key), charset));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
i++;
}
if (method.equals("POST")) {
// request method is POST
try {
urlObj = new URL(url);
conn = (HttpURLConnection) urlObj.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept-Charset", charset);
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.connect();
paramsString = sbParams.toString();
wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(paramsString);
wr.flush();
wr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
else if(method.equals("GET")){
// request method is GET
if (sbParams.length() != 0) {
url += "?" + sbParams.toString();
}
try {
urlObj = new URL(url);
conn = (HttpURLConnection) urlObj.openConnection();
conn.setDoOutput(false);
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept-Charset", charset);
conn.setConnectTimeout(15000);
conn.connect();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
//Receive the response from the server
InputStream in = new BufferedInputStream(conn.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
Log.d("JSON Parser", "result: " + result.toString());
} catch (IOException e) {
e.printStackTrace();
}
conn.disconnect();
// try parse the string to a JSON object
try {
System.out.println(jObj);
jObj = new JSONObject(result.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON Object
return jObj;
}
And this is the error i get every time i submit the data:
08-26 12:51:08.236 5089-5156/chtecnologies.myapplication D/JSON Parser: result:08-26 12:51:08.239 5089-5156/chtecnologies.myapplication E/JSON Parser: Error parsing data org.json.JSONException: End of input at character 0 of
08-26 12:51:08.793 5089-5096/chtecnologies.myapplication W/art: Suspending all threads took: 190.496ms
08-26 12:51:09.245 5089-5096/chtecnologies.myapplication W/art: Suspending all threads took: 137.277ms
08-26 12:51:09.267 5089-5156/chtecnologies.myapplication E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: chtecnologies.myapplication, PID: 5089
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:304)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.toString()' on a null object reference
at chtecnologies.myapplication.PostPet$4$1.doInBackground(PostPet.java:154)
at chtecnologies.myapplication.PostPet$4$1.doInBackground(PostPet.java:118)
at android.os.AsyncTask$2.call(AsyncTask.java:292)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
The data successfully goes into the database, but there seems to be a problem in the JSONParser, than can't get the result of the PHP file.
Would you tell me if there's anything wrong in the JSONParser file or somewhere else? This is the first time that i implement a server in my app, i hope you can help me! Thanks
The way you are sending data looks fishy. If you want to send data in POST use HttpURLConnection like
String postParam = "name=" + a + "&breed=" + BREED + "&type=" + "&images=" +
Whatever + "&description=" + c + "&coords=" + b;
try {
URL url = new URL(url);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
OutputStream os = connection.getOutputStream();
os.write(postParam.getBytes());
os.flush();
os.close();
// Fetching the response code
responseCode = connection.getResponseCode();
Log.d(TAG, "POST Response Code: " + responseCode);
} catch (Exception e) {
e.printStackTrace();
}
connection.setRequestMethod- sets Method you want to send your data with GET/POST
connection.setDoOutput(true)- to let you sent the output
connection.setDoInput(true)- to let you receive input after sending the data (if any)
Hope this solves your problem!
I want to call the following URL:
http://192.168.0.196:8080/openapi/localuser/set?{"syskey":"1234","usrname":"256","usrpwd":"556"}
Use this address to add a new user to the database. To do this I use HttpURLConnection in my AsyncTask class
try {
URL myUrl = new URL(params[0]);
HttpURLConnection conn = (HttpURLConnection) myUrl.openConnection();
conn.setReadTimeout(10000 );
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
// Starts the query
conn.connect();
int response = conn.getResponseCode();
Log.d("lab", "The response is: " + response);
statusMap.put("addUser", Integer.toString(response));
Log.d("lab", "URL: " + params[0]);
}catch (Exception e){
Log.d("lab", "Error2: " + e.getMessage());
}
params[0] = http://192.168.0.196:8080/openapi/localuser/set?{"syskey":"1234","usrname":"256","usrpwd":"556"}
Unfortunately, this call is not working. I do not get the error.
catch returns null
Try like this way. You need to add few line in your code.
public JSONObject makeHttpRequest(String requestURL, JSONObject register) {
try {
url = new URL(requestURL);
connection = (HttpURLConnection) url.openConnection();
connection.setReadTimeout(150000);
connection.setConnectTimeout(150000);
connection.setAllowUserInteraction(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept-Charset", "UTF-8");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
connection.setFixedLengthStreamingMode(register.toString().getBytes().length);
connection.setDoInput(true);
connection.setDoOutput(true);
OutputStreamWriter outputStream = new OutputStreamWriter(connection.getOutputStream());
outputStream.write(register.toString());
outputStream.flush();
Log.e("URL", connection.getURL().toString());
Log.e("JSONObject", register.toString());
} catch (Exception e) {
Log.e("MAIN Exception", e.toString());
}
try {
int statuscode = connection.getResponseCode();
if (statuscode == HttpURLConnection.HTTP_OK) {
is = connection.getInputStream();
} else {
}
} catch (IOException e) {
Log.e("IOException", e.toString());
}
try {
rd = new BufferedReader(new InputStreamReader(is));
response = new StringBuffer();
while ((line = rd.readLine()) != null) {
response.append(line);
response.append('\n');
}
Log.e("Response", response.toString() + " ");
rd.close();
} catch (IOException e) {
Log.e("BUFFER_READER", e.toString());
} catch (NullPointerException e) {
Log.e("NullPointerException", e.toString());
} finally {
connection.disconnect();
}
try {
return new JSONObject(response.toString());
} catch (JSONException e) {
Log.e("JSONException", e.toString());
}
return null;
}
Also You are using localHost you must have emulator which can connect to localhost. Unless it will not going to work on any device.
try this :
private String post(String url) throws JSONException {
JSONObject json = new JSONObject();
try {
String query = "";
String EQ = ":";
String AMP = "&";
for (NameValuePair param : parameters) {
query = json.put(param.getName(), param.getValue()) + ",";
}
// url+= "?" + query;
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
if (parameters != null) {
StringEntity se = new StringEntity(query.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
post.setEntity(se);
Log.d("POSTQuery", url + parameters);
}
HttpResponse response = client.execute(post);
StatusLine statusLine = response.getStatusLine();
Log.d("Status Code", "" + statusLine.getStatusCode());
if (statusLine.getStatusCode() == 200) {
return StringifyResponse(response);
}
Log.d("POSTQuery", url);
// Log.d("response", response.toString());
return StringifyResponse(response);
} catch (ClientProtocolException e) {
} catch (IOException e) {
Log.d("response", e.toString());
return "IOException";
}
return null;
}
You need to format all url querystring and then use outputwriter to flush the data :
// Create data variable for sent values to server
String data = URLEncoder.encode("syskey", "UTF-8")
+ "=" + URLEncoder.encode("1234", "UTF-8");
data += "&" + URLEncoder.encode("usrname", "UTF-8") + "="
+ URLEncoder.encode("256", "UTF-8");
data += "&" + URLEncoder.encode("usrpwd", "UTF-8")
+ "=" + URLEncoder.encode("556", "UTF-8");
and then flush the data:
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write( data );
wr.flush();
Link here :
http://androidexample.com/How_To_Make_HTTP_POST_Request_To_Server_-_Android_Example/index.php?view=article_discription&aid=64&aaid=89
I want to get the response to a string variable from the data from the cloud.
ClientResource cr = new ClientResource("http://localhost:8888/users");
cr.setRequestEntityBuffering(true);
try {
try {
cr.get(MediaType.APPLICATION_JSON).write(System.out);
} catch (IOException e) {
e.printStackTrace();
}
} catch (ResourceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I have response as JSON in the console and I want to convert it to string , Is the GSON library would be helpful? I haven't used it yet .What modifications should I need to do in my codes? Can anybody help me here.
In fact, Restlet receives the response payload as String and you can directly have access to this, as described below:
ClientResource cr = new ClientResource("http://localhost:8888/users");
cr.setRequestEntityBuffering(true);
Representation representation = cr.get(MediaType.APPLICATION_JSON);
String jsonContentAsString = representation.getText();
Hope it helps you,
Thierry
Below is a working example:
try {
URL url = new URL("http://localhost:8888/users");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Raw Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
I'm trying to POST some data to an https url, in my android application, in order to get a json format response.
I'm facing two problems:
is = conn.getInputStream();
throws
java.io.FileNotFoundException
I don't get if i do something wrong with HttpsURLConnection.
The second problem arose when i debug the code (used eclipse); I set a breakpoint after
conn.setDoOutput(true);
and, when inspecting conn values, I see that the variable doOutput remain set to false and type GET.
My method for https POST is the following, where POSTData is a class extending ArrayList<NameValuePair>
private static String httpsPOST(String urlString, POSTData postData, List<HttpCookie> cookies) {
String result = null;
HttpsURLConnection conn = null;
OutputStream os = null;
InputStream is = null;
try {
URL url = new URL(urlString);
conn = (HttpsURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setUseCaches (false);
conn.setDoInput(true);
conn.setDoOutput(true);
if(cookies != null)
conn.setRequestProperty("Cookie",
TextUtils.join(";", cookies));
os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(postData.getPostData());
writer.flush();
writer.close();
is = conn.getInputStream();
BufferedReader r = new BufferedReader(
new InputStreamReader(is));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line);
}
result = total.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
if (conn != null) {
conn.disconnect();
}
}
return result;
}
A little update: apparently eclipse debug lied to me, running and debugging on netbeans shows a POST connection. Error seems to be related to parameters i'm passing to the url.
FileNotFoundException means that the URL you posted to doesn't exist, or couldn't be mapped to a servlet. It is the result of an HTTP 404 status code.
Don't worry about what you see in the debugger if it doesn't agree with how the program behaves. If doOutput really wasn't enabled, you would get an exception obtaining the output stream.