Java IOException "Unexpected end of file from server" when posting large data - java

I am trying to post XML data to a server which processes this XML and gives a response back, some times the XML data can be very large and the server takes a while to process it, in those cases i fail to get any response back instead i receive a IOException with the message "Unexpected end of file from server". I am positive the XML being sent to the server is not full of errors, is there anything i can do on my end to make sure this doesn't happen or is this a server side issue? Below is code fragment of the method i call to post the data.
Thanks.
String encodedData="some XML"
String urlString="example.com"
try {
URL url = new URL(urlString);
HttpURLConnection urlConnection;
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", contentType);
urlConnection.setRequestProperty("Content-Length", encodedData.length()+"");
OutputStream os = urlConnection.getOutputStream();
os.write(encodedData.getBytes());
BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
StringBuffer sb = new StringBuffer();
String inputLine;
while ((inputLine = in.readLine()) != null) {
sb.append(inputLine);
}
in.close();
} catch (MalformedURLException e) {
logger.debug("MalformedURLException " + e.getMessage());
logger.debug((new StringBuilder()).append("urlString=").append(urlString).toString());
throw (e);
} catch (IOException e) {
logger.debug("IOException " + e.getMessage());
logger.debug((new StringBuilder()).append("urlString=").append(urlString).toString());
throw (e);
}
return sb.toString();

Not much could be done from the client side, it's just a server side issue in which the server takes very long to process the data which results in the servers connection to timeout before it could send a response.

Related

Server Receive empty JSON string array From android app

I am sending image data from my android app to server,I can see in log that string array is not empty and has correct data but on server it receive null.
Here is my AsyncTask from where i am sending data to server
protected Void doInBackground(Void... params) {
BufferedReader reader;
try {
URL url = new URL("http://www.example.com/Data/galleryLog.php");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
Log.d(TAG,"String Data "+Images);
//For POST Only - Begin
OutputStream os = connection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(Images);
writer.flush();
writer.close();
os.close();
connection.connect();
//For POST Only End
int responseCode = connection.getResponseCode();
Log.d(TAG, "POST RESPONSE CODE " + responseCode);
String LoginResult;
if (responseCode == HttpURLConnection.HTTP_OK) {
//Success
Log.d(TAG, "Success connection with database");
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = reader.readLine()) != null) {
response.append(inputLine);
}
reader.close();
Log.d(TAG, "Reader Close - Printing Result ");
//Print Result
Log.d(TAG, "Calling Response " + response.toString());
}
return null;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
This is the string i got in logcat which is not empty and has correct data
String Data {"galleryDesc":"My First Gallery","images":[{"base64code":"Base64Image","type":"jpg","imagename":"image-101.jpg"}],"User_ID":"18","galleryTitle":"Image-101.jpg"}
My Php Code where i am printing received data into file but it give me blank file always
<?php
$tm = 'ritu_gallery_'.time().'.log';
file_put_contents($tm, print_r($_POST, TRUE));
echo "Response<br>";
print_r($_POST);
?>
Its create text file like that
Array ( )
UPDATE: its an issue in AsyncTask String array. I don't know why its not working.If anyone knows please let me know
When i am sending this string array to server.it's print blank values on server
{"galleryDesc":"My First Gallery","images":[{"base64code":"Base64Image","type":"jpg","imagename":"image-101.jpg"}],"User_ID":"18","galleryTitle":"Image-101.jpg"}
when i add above String array into this
String data= URLEncoder.encode("Pic","UTF-8")+ "=" +URLEncoder.encode(Images,"UTF-8");
It creates file on server like this
Array (
[Pics] => {"galleryDesc":"My First Gallery","images":[{"base64code":"Base64Image","type":"jpg","imagename":"101.jpg"}],"User_ID":"18","galleryTitle":"101.jpg"}
)
with all correct values.If anyone know why this is happening. Please let me know
you are accessing the wrong variable here, an image is a file and it will be in $_FILE variable not in $_POST variable, also the form should be multipart formdata, i don't know if you are doing that or not cause i don't know very much about android but if are doing so then you can see your file in $_FILE variable

java.io.FileNotFoundException: When using real server

I am beginner in Java and Android Studio. I have written a code by Android Studio and Wamp as server and Genymotion as simulator. all codes work fine and I can interact with mysql by use of my .php files
Then I decide to transfer codes to real server.
but I get this error:
java.io.FileNotFoundException: http://burj.1shahrvand.com/Burj/BikerLogin.php
The File is available check it here but I get Exception that file not found
The code is like this:
String uri = rp.getUri();
if(rp.getMethod().equals("GET")){
uri += "?" + rp.getEncodedParams();
}
HttpURLConnection connection;
try {
URL url = new URL(uri);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(rp.getMethod());
if (rp.getMethod().equals("POST")){
connection.setDoOutput(true);
connection.setDoInput(true);
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write(rp.getEncodedParams());
writer.flush();
}
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line);
}
return sb.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
Log.i("HESAM Original", e.getMessage());
e.printStackTrace();
}
return null;
I appreciate your Help!
You will get a FileNotFoundException if you call getInputStream after the server has responded withe a 404 or 410 status code.
If you want to avoid the exception, check that the response status code is a 2xx code. If it isn't then use getErrorStream instead of getInputStream.
In my case, There is an option in my Cpanel. It is MOD Security, Just turn it off, after 15 minutes my app worked properly.
Simply you need to add the port name(:8080) with the localhost ip address in URL String, like i did:
String login_url = "http://192.168.0.136:8080/login.php";

Android JSON Get via HttpURLConnection error 405

so I'm trying to do a GET Request to my web service, and since I saw that the HttpGet class is being deprecated, I try to use the HttpURLConnection class instead, and I used it successfully with a 'POST' method... however when I try to do a simple 'GET' request - I get a 405 error (bad method).
I tested the link in DHC, and the link is fine.
Here's my method:
public JSONObject getClientByDeviceId (String link) {
try {
URL url = new URL(link);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// conn.setRequestMethod("GET");
// conn.setDoOutput(true);
// conn.setDoInput(true);
// conn.setUseCaches(false);
// conn.setAllowUserInteraction(false);
// conn.setRequestProperty("Content-Type", "application/json");
OutputStream outputStream = conn.getOutputStream();
outputStream.close();
if (conn.getResponseCode() != 200) {
Log.e("conn", "Error code: " + conn.getResponseCode());
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
conn.disconnect();
JSONObject returnedObject = new JSONObject(sb.toString());
if (returnedObject != null) {
Log.e("conn", "If 400, this is the object gained: " + returnedObject.getString("Message"));
} else {
Log.e("conn", "didn't get any JSON object");
}
conn.disconnect();
return returnedObject;
}
else {
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
Log.e("conn", "GREAT SUCCESS !!: " + conn.getResponseCode());
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
conn.disconnect();
JSONObject returnedObject = new JSONObject(sb.toString());
return returnedObject;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
Normally I would say that this problem is caused by trying to do a 'GET' request in a 'POST' URL. But without the two HttpGet and HttpPost classes I don't really know where to turn, all the properties that are commented out are like that because I tried them in the POST request and now I deleted one by one to try to get the method to work.
Any ideas ? or reference to an updated guide on how to properly use that HttpURLConnection class, since I couldn't find one.
Thanks in advance !
Solved it, apparently this code needed to be removed:
OutputStream outputStream = conn.getOutputStream();
outputStream.close();
I guess it was because I gave a GET URL and put that outputStream in my code and that caused the issues.
I still however don't understand why I got the "405: method GET not allowed" whereas I think I should have gotten the opposite: "POST" not allowed...
Anyway that is my solution, thanks a lot for your help guys !
HTTP 405 is caused by bad method call (Method not Allowed). That means you called GET method on POST request or vice-versa. You should add handling for you GET method on your Web-Service to get it working.
For anyone still reaching here from a search engine, my solution was similar -
I removed the line "conn.setDoOutput(true);" (or set it to false)

Send POST data from JSP page to remote PHP server (and get an answer)

I'm trying to send some data from a JSP page to a PHP one (which should execute some code and return a success message).
I'm using this java function to make some tests:
public String excutePost(String targetURL, String urlParameters)
{
URL url;
HttpURLConnection connection = null;
try {
//Create connection
url = new URL(targetURL);
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", "" +
Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches (false);
connection.setDoInput(true);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream (
connection.getOutputStream ());
wr.writeBytes (urlParameters);
wr.flush ();
wr.close ();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if(connection != null) {
connection.disconnect();
}
}
}
String urlParameters =
"var=" + URLEncoder.encode("varcontent", "UTF-8");
out.println(excutePost("remoteurl",urlParameters));
Now if i run the page i get the response "null" and none of the code in the php page is executed.
Am I doing something wrong? How can I allow the php page to run the code in it?
Isn't a simple echo $_POST['var'] enough to send the data back to the jsp page?
EDIT: I tried to see if the php page is receiving something by writing the posted variable in a file. But nothing is written in it.
$file = 'debug.txt';
echo file_put_contents($file, $_POST['var']);
and here is the exception i'm getting..
java.net.SocketException: Connection reset
No, an echo is not enough. Put $_POST['var'] in say a text file and serve the updated text file (Edit the text file each time you need to keep track of $_POST['var']). Alternatively you can put it in some DB and check for changes.

how to make http get request in Android

I am new to android.So i can any one sho me how to make a http get request such as
GET /photos?size=original&file=vacation.jpg HTTP/1.1
Host: photos.example.net:80
Authorization: OAuth realm="http://photos.example.net/photos",
oauth_consumer_key="dpf43f3p2l4k3l03",
oauth_token="nnch734d00sl2jdk",
oauth_nonce="kllo9940pd9333jh",
oauth_timestamp="1191242096",
oauth_signature_method="HMAC-SHA1",
oauth_version="1.0",
oauth_signature="tR3%2BTy81lMeYAr%2FFid0kMTYa%2FWM%3D"
in android(java)?
You're gonna want to get familiar with InputStreams and OutputStreams in Android, if you've done this in regular java before then its essentially the same thing. You need to open a connection with the request property as "GET", you then write your parameters to the output stream and read the response through an input stream. You can see this in my code below:
try {
URL url = null;
String response = null;
String parameters = "param1=value1&param2=value2";
url = new URL("http://www.somedomain.com/sendGetData.php");
//create the connection
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
//set the request method to GET
connection.setRequestMethod("GET");
//get the output stream from the connection you created
request = new OutputStreamWriter(connection.getOutputStream());
//write your data to the ouputstream
request.write(parameters);
request.flush();
request.close();
String line = "";
//create your inputsream
InputStreamReader isr = new InputStreamReader(
connection.getInputStream());
//read in the data from input stream, this can be done a variety of ways
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
//get the string version of the response data
response = sb.toString();
//do what you want with the data now
//always remember to close your input and output streams
isr.close();
reader.close();
} catch (IOException e) {
Log.e("HTTP GET:", e.toString());
}

Categories