HttpURLConnection doesn't receive response - java

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.

Related

PUT request (JAVA) with HttpUrlConnection

I'm trying to do a "PUT" request with Android Studio.
But, actually, it doesn't work, I received a "404 not found" whereas I got all the needed infos.
String url = "https://[...]";
URL obj = null;
try {
obj = new URL(url);
} catch (MalformedURLException e) {
e.printStackTrace();
}
HttpURLConnection con = null;
DataOutputStream dataOutputStream = null;
try {
con = (HttpURLConnection) obj.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
// optional default is GET
try {
con.setRequestMethod("PUT");
con.setDoInput(true);
con.setDoOutput(true);
System.out.println("Info User to update : " + params[0]);
con.setRequestProperty("X-Auth-Token", params[0].get("token"));
[...]
con.setRequestProperty("shop_id", params[1].get("id"));
dataOutputStream = new DataOutputStream(con.getOutputStream());
OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
osw.flush();
osw.close();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
if (dataOutputStream != null) {
try {
dataOutputStream.flush();
dataOutputStream.close();
} catch (IOException exception) {
exception.printStackTrace();
}
}
}
int responseCode = 0;
try {
responseCode = con.getResponseCode();
} catch (IOException e) {
e.printStackTrace();
}
If I try the request on Symfony (web app), it's worked well, but with the code, not anymore... Do you see any problems with my request ?
Problem solved, I was able to do what I wanted using a PATCH request instead.

how to handle exceptions an error occurred while executing doInBackground()

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));

Why isn't my node.js restful api recieving this output stream from Java Android?

I have a class audio sender which makes a connection to the nodejs server and uploads an audio file in POST method mode.
public class AudioSender implements Callable<JSONObject> {
String outputFile;
AudioSender(String fileLocation){
outputFile=fileLocation;
}
public JSONObject call(){
URL url = null;
HttpURLConnection urlConnection = null;
InputStream audioInputStream=null;
JSONObject response=null;
byte buffer[]=new byte[16];
try {
url = new URL("http://192.168.0.106:3000/upload");
} catch (MalformedURLException e) {
e.printStackTrace();
} finally {
try {
urlConnection = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
e.printStackTrace();
} finally {
urlConnection.setDoOutput(true);
urlConnection.setChunkedStreamingMode(16);
urlConnection.setRequestProperty("Content-Type","multipart/form-data");
urlConnection.setRequestProperty("Connection", "Keep-Alive");
urlConnection.setRequestProperty("Cache-Control", "no-cache");
urlConnection.setRequestProperty(
"Content-Type", "multipart/form-data;boundary=*****");
try {
OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
try {
audioInputStream = new BufferedInputStream(new FileInputStream(outputFile));
Log.d("hello","audioinputstream");
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
while(audioInputStream.read(buffer)!=-1) {
out.write(buffer);
Log.d("buffer",buffer.toString());
}
try {
audioInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
StringBuilder total = new StringBuilder();
while(in.read(buffer)!=-1)
total.append(buffer);
Log.d("response",total.toString());
try {
response = new JSONObject(total.toString());
}catch(JSONException e){
Log.e("Response Parse Error", "Could not parse malformed JSON");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
return response;
}
This is the upload that executes the AudioSender callable.
public void upload() {
JSONObject response=null;
AudioSender sender=new AudioSender(outputFile);
FutureTask<JSONObject> uploadTask=new FutureTask<JSONObject>(sender);
ExecutorService executorService= Executors.newFixedThreadPool(1);
executorService.execute(uploadTask);
Log.d("s","was here");
while(true){
if(uploadTask.isDone()){
try{
response=uploadTask.get();
}catch(InterruptedException|ExecutionException e){
e.printStackTrace();
Log.e("ee","ee",e.getCause());
}
}
}
}
I pretty much know this isn't node js's fault but here's the server code:
app.post('/upload',function(req,res){
console.log("someone called!");
req.on('data',function(chunk){
console.log('res');
console.log(chunk);
});
req.on('end',function(){
console.log("done!");
res.send({'name':'sg'});
});});
When I call upload(), the server console prints
someone called!
done!
I was debugging and found that indeed I am receiving the responded json object from the server. And I don't know if out.write(buffer) is doing the job, but debugging it shows that the buffer value is changing and is in par with my audio file's size.
Please do not suggest using ION or anything else.
I solved the problems by setting up the URLConnection as follows:
boundary = "===" + System.currentTimeMillis() + "===";
urlConnection.setUseCaches(false);
urlConnection.setDoOutput(true); // indicates POST method
urlConnection.setDoInput(true);
urlConnection.setRequestProperty("Content-Type","multipart/form-data; boundary=" + boundary);

How to get the response data from cloud to string

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();
}
}

FileNotFoundException on HttpsURLConnection with POST and unmutable doOutput variable

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.

Categories