I am using Asynctask in my app to retrieve data from a server.
When my app is connected to the Internet it works fine, but when I disconnect, it suddenly force-stops.
Here's my code:
try {
URL url = new URL("http://javalovers.net16.net/showdata.php");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.connect();
switch (connection.getResponseCode()) {
case HttpURLConnection.HTTP_OK:
InputStream stream = connection.getInputStream(); //here getting response
br = new BufferedReader(new InputStreamReader(stream));
String line = "";
while ((line = br.readLine()) != null) {
// buffer.append(line);
str = str + line;
}
break; // fine, go on
case HttpURLConnection.HTTP_GATEWAY_TIMEOUT:
break; // retry
case HttpURLConnection.HTTP_UNAVAILABLE:
break; // retry, server is unstable
default:
break; // abort
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
connection.disconnect();
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
I'm getting the error:
-FATAL EXCEPTION: AsyncTask #3
Process: kuldeep.mourya.com.smartcollege, PID: 10617
java.lang.RuntimeException: An error occurred while executing
doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:309)
at
java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual
method 'void java.io.BufferedReader.close()' on a null object
reference
at
kuldeep.mourya.com.smartcollege.FragmentProfessor.CollegeNewsFragment$JsonTask.doInBackground(CollegeNewsFragment.java:223)
at
kuldeep.mourya.com.smartcollege.FragmentProfessor.CollegeNewsFragment$JsonTask.doInBackground(CollegeNewsFragment.java:148)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
Does anyone know why I am getting this error?
woow!!! i got answer while separating exception try catch block!
//URL url=new URL("http://javalovers.net16.net/showdata.php");
URL url = null;// this api link
try {
url = new URL("http://vcetsmart.netne.net/showdata.php");
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
connection = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
try {
connection.setRequestMethod("POST");
} catch (ProtocolException e) {
e.printStackTrace();
}
try {
connection.connect();
} catch (IOException e) {
e.printStackTrace();
}
try{
if(connection.getResponseCode()==200)
{
//Toast.makeText(getBaseContext(),"Everything is right",Toast.LENGTH_SHORT).show();
InputStream stream=connection.getInputStream(); //here getting response
BufferedReader br = new BufferedReader(new InputStreamReader(stream));
String line = "";
while ((line = br.readLine()) != null) {
// buffer.append(line);
str=str+line;
}
}
else {
Toast toast= Toast.makeText(getActivity(),"Something goes wrong", Toast.LENGTH_LONG);
toast.show();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return str;
br = new BufferedReader(new InputStreamReader(stream));
In the above line of code, where did you declare and initialize the BufferedReader ?
When the connection is available, there is high probability that you will definitely get the data into your stream. But when you are not connected to internet the stream is a null.
What i advice you is a small change in your code:
URL url = new URL("http://javalovers.net16.net/showdata.php");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.connect();
Put this in a separate try..catch and do it first. If this is successful, proceed to the code of reading the stream.
Also one more change is, declare the BufferredReader then and where you are using every time(this is generally a good practice). Like the code snippet below:
BufferredReader br = new BufferedReader(new InputStreamReader(stream));
Related
So I am having some problems with getting this code to work, I found some of this code online but it won't work. I have tried adjusting some code but no matter what I am doing, the app just crashes with an error. I have been trying to get this to work for a few days now with hours of googling and watching YouTube tutorials and I cannot seem to get this to work.
Can someone shed some light on what I am doing wrong here?
CODE:
public class fetchJSON extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
URL url;
try {
url = new URL("www.link.to.json");
urlConnection.setRequestMethod("GET"); //Your method here
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null)
buffer.append(line + "\n");
if (buffer.length() == 0)
return null;
return buffer.toString();
} catch (IOException e) {
Log.e(TAG, "IO Exception", e);
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(TAG, "Error closing stream", e);
}
}
}
}
#Override
protected void onPostExecute(String response) {
if(response != null) {
JSONObject json = null;
try {
json = new JSONObject(response);
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject jsonResponse = null;
try {
jsonResponse = json.getJSONObject("Question1");
} catch (JSONException e) {
e.printStackTrace();
}
MainActivity.jsonPrint.setText((CharSequence) jsonResponse);
}
}
}
ERROR:
E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: uk.co.jrtevents.fetchjsonfromurltest, PID: 4019
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:318)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
Caused by: java.lang.NullPointerException: Attempt to invoke a virtual method on a null object reference
at uk.co.jrtevents.fetchjsonfromurltest.fetchJSON.doInBackground(fetchJSON.java:31)
at uk.co.jrtevents.fetchjsonfromurltest.fetchJSON.doInBackground(fetchJSON.java:18)
at android.os.AsyncTask$2.call(AsyncTask.java:304)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
LINE 31:
urlConnection.setRequestMethod("GET");
HttpURLConnection urlConnection = null;
You never assign a value to urlConnection, and so it is null.
You would need to add:
urlConnection = url.openConnection();
before trying to use urlConnection.
URL and HttpURLConnection are very old, and very few developers use them anymore. You may have better luck using more modern HTTP client APIs, such as OkHttp.
Im reading a simple text file from my website using HttpURLConnection, and when it calls getInputStream it freezes and never finishes, the getResponseCode returns 200. It was working at first every time then it stopped working.
I have search for a solution all over the internet and none work. I think it maybe ddos protection on the web server, or something on there end blocking it.
public static String getLatestInfo(String urlString){
URL url = null;
HttpURLConnection connection = null;
/*InputStream inputStream = null;
InputStreamReader isr = null;
BufferedReader in = null;*/
try {
url = new URL(urlString);
connection = (HttpURLConnection) url.openConnection();
//connection.setRequestMethod("GET");
//connection.setDoOutput(true);
connection.setConnectTimeout(5000); // 5 seconds connectTimeout
connection.setReadTimeout(5000); // 5 seconds socketTimeout
connection.setRequestProperty("Connection", "close");
connection.setRequestProperty("Content-Type", "text/xml");
connection.setRequestProperty("Accept", "text/xml");
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");
connection.connect();
if (connection.getResponseCode() == 200) {
try(InputStream inputStream = connection.getInputStream())
{
try(InputStreamReader isr = new InputStreamReader(inputStream, "UTF-8")) {
try(BufferedReader in = new BufferedReader(isr))
{
String line;
String config = "";
while ((line = in.readLine()) != null) {
config = config + line + "\n";
}
return config;
}
}
}
/*inputStream = connection.getInputStream();
isr = new InputStreamReader(inputStream, "UTF-8");
in = new BufferedReader(isr);
String line;
String config = "";
while ((line = in.readLine()) != null) {
config = config + line + "\n";
}
return config;*/
}
}
catch (SocketTimeoutException e)
{
System.out.println("Timeout: " + e.getMessage());
}
catch (MalformedURLException e) {
System.out.println("Malformed URL: " + e.getMessage());
}
catch (IOException e) {
System.out.println("I/O Error: " + e.getMessage());
try {
System.out.println(connection.getResponseCode());
} catch (IOException e1) {
e1.printStackTrace();
}
}
finally {
if (connection != null) connection.disconnect();
/*try {
if (inputStream != null) inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (in != null) in.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (isr != null) isr.close();
} catch (IOException e) {
e.printStackTrace();
}*/
}
return null;}
I started simple and have added all the suggestion that should've fix it.. it gets response code 200 and then freezes on connection.getInputStream()
There were multiple things wrong in my code:
Some streams for file reading wasn't closed.
I was using FileInputStream/FileOutputStream and it was making it freeze. This explains it. Even though it shows a work around, but it still would make it freeze.
The main problem i was using SwingUtilities.invokeLater(new Runnable ()... and it was freeze and random points.
Fixing all the above factors and it solved my problem.
I've WebService invoke code in a loop in a Thread. I build URL with diffirent parameters and and invoke the WS using HttpURLConnection as follows:
public void run() {
//establish connection to db in another class
while(true) {
//Get args value from another class
for(String arg : args) {
try {
String invokeWS = "URL is built here with encoded args";
URL obj = new URL(invokeWS);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
con.disconnect();
System.out.println(response.toString());
} catch (UnsupportedEncodingException e) {
System.out.println("Unsupported Encoding Exception");
} catch (MalformedURLException e) {
System.out.println("Malformed URL Exception");
} catch (IOException e) {
System.out.println("IO Exception");
}
}
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
System.out.println("Interrupted Exception");
}
}
}
But if the network connection drops out after the 'GET' is sent and before the response is received then control never returns to the Thread in the loop. What am I doing wrong here?
Avoid Looping in runnable. I face the same issue i cut down my looping.I loaded straight away data and then looped at my end out side runnable task.
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.