End of File Exception - android

Good day.
I have a problem with my NodeJS server.
I have an android app that gets information from MySQL database thru HttpUrlConnection every 30 seconds. The app and my server are working fine. But after about (not sure) 10 minutes or 20? my server does nothing and in my Logcat it says that my app throws EOFException
can someone help me fix this?
this image shows the app is working fine
and my server
but after sometime
server became this
this is my codes in getting info from mysql nodejs server
protected String doInBackground(String... arg0) {
HttpURLConnection connection = null;
HttpURLConnection connection1 = null;
String json = (String) arg0[0];
System.setProperty("http.keepAlive", "false");
try {
URL u = new URL("http://"+ MainActivity.ipadd +"/getmessage");
connection = (HttpURLConnection) u.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "close");
connection.setRequestProperty("Content-Type","application/json");
//connection.setConnectTimeout(10000);
//connection.setReadTimeout(15000);
if (json != null) {
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
Log.i("message", "To send : " + json);
byte[] outputInBytes = json.getBytes("UTF-8");
OutputStream os = connection.getOutputStream();
os.write( outputInBytes );
os.close();
os.flush();
}
//Connect to the server
connection.connect();
int status = connection.getResponseCode();
String staRes = connection.getResponseMessage().toString();
Log.i("HTTP Client", "HTTP status code : " + status + " " + staRes);
switch (status) {
case 200:
case 201:
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
sb.append(line + "\n");
}
bufferedReader.close();
Log.i("HTTP Client", "Response : " + sb.toString());
//return received string
holds.setRespone(sb.toString());
jo = new JSONObject(sb.toString());
jof = new JSONObject();
String tmp = jo.optString("mess");
String tmpp = jo.optString("cp");
String reff = jo.optString("ref");
boolean tmppp = false;
//jof.put("ref", jo.opt("ref"));
if(tmp.contains("err_code_01")){
tmppp = sendSMSMessage(tmpp, "Your MESSAGE was rejected. It contains wrong format.\nTrace Number:" + reff + "\nDo not reply.");
Log.v("sent message", "Your MESSAGE was rejected. It contains wrong format.");
} else if(tmp.contains("err_code_03")){
tmppp = sendSMSMessage(tmpp, "Your MESSAGE was rejected. It contains wrong position format.\nTrace Number:" + reff + "\nDo not reply.");
Log.v("sent message", "Your MESSAGE was rejected. It contains wrong position format.");
} else if(tmp.contains("err_code_04")){
tmppp = sendSMSMessage(tmpp, "Your MESSAGE was rejected. It contains wrong candidate-position format.\nTrace Number:" + reff + "\nDo not reply.");
Log.v("sent message", "Your MESSAGE was rejected. It contains wrong candidate-position format.");
} else if(tmp.contains("err_code_05")){
tmppp = sendSMSMessage(tmpp, "Your MESSAGE was rejected. It contains wrong vote count format.\nTrace Number:" + reff + "\nDo not reply.");
Log.v("sent message", "Your MESSAGE was rejected. It contains wrong vote count format.");
} else if(tmp.contains("success")){
tmppp = sendSMSMessage(tmpp, "Your MESSAGE was accepted.\nTrace Number:" + reff + "\nDo not reply.");
Log.v("sent message", "Your MESSAGE was accepted.");
}
return sb.toString();
}
} catch (MalformedURLException ex) {
Log.e("HTTP Client", "Error in HTTP Connection(Malformed URL) " + ex);
} catch (IOException ex) {
Log.e("HTTP Client", "Error in HTTP Connection(IO Exception) " + ex);
} catch (Exception ex) {
Log.e("HTTP Client", "Error in HTTP Connection(Exception) " + ex);
} finally {
//if (connection != null) {
//try {
connection.disconnect();
//} catch (Exception ex) {
// Log.e("HTTP Client", "Error in HTTP Connection " + ex.toString());
//}
//}
}
return null;
}
and for calling from MainActivity.class
final Handler handlerr = new Handler();
runnableGet = new Runnable(){
#Override
public void run() {
try{
gett = new GetMessageFromServer();
gett.execute(tmpp.toString());
}catch (Exception e){
//err here
Log.v("err", "runnable: " + e.toString());
} finally{
handlerr.postDelayed(runnableGet, 30000);
}
}
};
handlerr.postDelayed(runnableGet, 30000);

Related

Second connection to server socket refused in android

I have a client/server socket program for android working through Direct WIFI connection.It includes several Request and Response between client and server phone. My code works perfectly for the first time but in second time client gets "Connection refused" and server "socket closed" error message.in third time it works again and in fourth time raise that errors and ....
Could anyone help me about this issue?
this is server code:
new Thread(){
public void run(){
ServerSocket welcomeSocket = null;
try {
//Create a socket and listen to that
try {
if(welcomeSocket == null)
welcomeSocket = new ServerSocket(COMMUNICATION_PORT);
}catch(Exception qwe){
Log.d("Info", "qwe:" + qwe.getMessage());
}
int i = 0;
while (i == 0) {
try {
//Waiting for client connection
socket = welcomeSocket.accept();
}catch(Exception qwe2){
Log.d("Info", "qwe2:" + qwe2.getMessage());
}
//i++;
new Thread(){
public void run(){
try {
InputStream is;
DataInputStream dIn;
OutputStream os;
DataOutputStream dOut;
//socket.setSoTimeout(SOCKET_TIMEOUT);
log("Connection accepted");
//Create an input stream for receiving data from server
is = socket.getInputStream();
dIn = new DataInputStream(is);
//Get an output stream for sending data to server phone
os = socket.getOutputStream();
dOut = new DataOutputStream(os);
boolean done = false;
byte messageType;
String message;
int serverReplyType = 0;
String serverReply = "NOP";
while (!done) {
messageType = dIn.readByte();
message = dIn.readUTF();
Log.d("Info", "Received: " + messageType);
Log.d("Info", "Received: " + message);
switch (messageType) {
//----------------------------------------
//Comparing Job ID and Location ID of client phone and server phone
case JOB_ID_CHECK_REQ:
String[] tokens = message.split("#");
serverReplyType = JOB_ID_CHECK_RESP;
if (Integer.parseInt(tokens[0]) == currentJob.getJobId() && Integer.parseInt(tokens[1]) == currentJob.getJobLocationId()) {
serverReply = "ACCEPTED";
log("Syncing data verified");
} else {
serverReply = "ID MISMATCH";
done = true;
log("It is not possible to sync none equal Jobs.");
log("Please select same Job in both phone.");
}
break;
//----------------------------------------
//Generating JSON string including Racks data
case RACK_LIST_REQ:
log("Sending Racks' data");
serverReplyType = RACK_LIST_RESP;
serverReply = racks.size() > 0 ? (new Gson()).toJson(racks) : "NOP";
break;
//----------------------------------------
//Inserting new Racks to local Db
case NEW_RACK_FOR_INSERT:
log("Receiving new Racks' data for insert");
if (!message.equals("NOP")) {
List<Rack> diffRacks = new Gson().fromJson(message, new TypeToken<List<Rack>>() {
}.getType());
rackDataSource rds = new rackDataSource(CrossPhoneSync.this);
rds.open();
rds.crossPhoneSync_InsertDiff(diffRacks);
rds.close();
}
serverReplyType = DONE;
serverReply = "NOP";
done = true;
break;
//----------------------------------------
case DONE:
done = true;
log("Done");
break;
}
Log.d("Info", "Send: " + serverReplyType);
Log.d("Info", "Send: " + serverReply);
dOut.writeByte(serverReplyType);
dOut.writeUTF(serverReply);
dOut.flush();
}
log("Operation completed!");
} catch (Exception e) {
log("Error: " + e.getMessage());
Log.d("Info", "ServerPhoneError:" + e.getMessage());
e.printStackTrace();
} finally {
//Close stream and socket
//closeSocket(true);
Disconnect(null);
}
log("Done!");
}
}.start();
}
}catch(Exception qw){
Log.d("Info", "Eq1:" + qw.getMessage());
}finally {
try {
if (welcomeSocket != null) {
welcomeSocket.close();
}
}catch (Exception e) {
Log.d("Info", "Close_ServerSocket#: " + e.getMessage());
}
}
}
}.start();
and client code:
Socket socket2 = null;
try {
InputStream is;
DataInputStream dIn;
OutputStream os;
DataOutputStream dOut;
//Create a socket for connecting to server phone
socket2 = new Socket(host, COMMUNICATION_PORT);
//socket.setSoTimeout(SOCKET_TIMEOUT);
//Get an output stream for sending data to server phone
os = socket2.getOutputStream();
dOut = new DataOutputStream(os);
//Create an input stream for receiving data from server
is = socket2.getInputStream();
dIn = new DataInputStream(is);
//Send first message
log("Sending verification data...");
int clientMessageType = JOB_ID_CHECK_REQ;
String clientMessageToSend = currentJob.getJobId() + "#" + currentJob.getJobLocationId();
dOut.writeByte(clientMessageType);
dOut.writeUTF(clientMessageToSend);
dOut.flush();
byte messageType;
String message;
boolean done = false;
while(!done) {
messageType = dIn.readByte();
message = dIn.readUTF();
Log.d("Info", "" + messageType);
Log.d("Info", message);
switch(messageType)
{
//----------------------------------------
//Sending current Job ID and Location ID to server phone for equality checking
case JOB_ID_CHECK_RESP:
if(message.equals("ACCEPTED")){
log("Data verified");
clientMessageType = RACK_LIST_REQ;
clientMessageToSend = "NOP";
log("Requesting for other phone's Racks data");
}else{
done = true;
log("It is not possible to sync none equal Jobs.");
log("Please select same Job in both phone.");
}
break;
//----------------------------------------
//Comparing...
case RACK_LIST_RESP:
log("Comparing Racks' data of two phones");
List<Rack> serverPhoneRacks;
if(!message.equals("NOP"))
serverPhoneRacks = new Gson().fromJson(message, new TypeToken<List<Rack>>() { }.getType());
else
serverPhoneRacks = new ArrayList<>();
rackDataSource rds = new rackDataSource(CrossPhoneSync.this);
rds.open();
List<Rack> diffRacks = rds.crossPhoneSync_Compare(racks,serverPhoneRacks);
rds.close();
clientMessageType = NEW_RACK_FOR_INSERT;
clientMessageToSend = diffRacks == null ? "NOP" : (new Gson()).toJson(diffRacks);
log("Sending new Racks' data for inserting on the other phone");
break;
//----------------------------------------
case DONE:
done = true;
log("Done!");
break;
}
if(!done) {
dOut.writeByte(clientMessageType);
dOut.writeUTF(clientMessageToSend);
dOut.flush();
}
}
log("Operation completed!");
}catch (Exception e) {
log("Error:" + e.getMessage());
e.printStackTrace();
Log.d("Info", " ClientPhoneError:" + e.getMessage());
}finally {
//Close stream and socket
//closeSocket(false);
try {
if (socket2 != null) {
//socket.shutdownInput();
//socket.shutdownOutput();
socket2.close();
}
}catch (Exception e) {
Log.d("Info", "Close_Socket_Error5: " + e.getMessage());
}
}
log("Finished!");

Android socket connection loses after app being idle for some time

My application listens to a socket. The application is connected to the socket using the following method.
public void connect() {
this.connectionStatus = CONNECT_STATUS_CONNECTING;
Log.v(AppConstants.DEBUG_TAG, userId + " : Connecting to Server");
if (mThread != null && mThread.isAlive()) {
return;
}
mThread = new Thread(new Runnable() {
#Override
public void run() {
try {
Log.v(AppConstants.DEBUG_TAG, userId + " : Thread Action Started");
String secret = createSecret();
int port = (mURI.getPort() != -1) ? mURI.getPort() : (mURI.getScheme().equals("wss") ? 443 : 80);
String path = TextUtils.isEmpty(mURI.getPath()) ? "/" : mURI.getPath();
if (!TextUtils.isEmpty(mURI.getQuery())) {
path += "?" + mURI.getQuery();
}
String originScheme = mURI.getScheme().equals("wss") ? "https" : "http";
URI origin = new URI(originScheme, "//" + mURI.getHost(), null);
SocketFactory factory = mURI.getScheme().equals("wss") ? getSSLSocketFactory() : SocketFactory.getDefault();
mSocket = factory.createSocket(mURI.getHost(), port);
PrintWriter out = new PrintWriter(mSocket.getOutputStream());
out.print("GET " + path + " HTTP/1.1\r\n");
out.print("Upgrade: websocket\r\n");
out.print("Connection: Upgrade\r\n");
out.print("Host: " + mURI.getHost() + "\r\n");
out.print("Origin: " + origin.toString() + "\r\n");
out.print("Sec-WebSocket-Key: " + secret + "\r\n");
out.print("Sec-WebSocket-Version: 13\r\n");
if (mExtraHeaders != null) {
for (NameValuePair pair : mExtraHeaders) {
out.print(String.format("%s: %s\r\n", pair.getName(), pair.getValue()));
}
}
out.print("\r\n");
out.flush();
HybiParser.HappyDataInputStream stream = new HybiParser.HappyDataInputStream(mSocket.getInputStream());
// Read HTTP response status line.
StatusLine statusLine = parseStatusLine(readLine(stream));
if (statusLine == null) {
Log.v(AppConstants.DEBUG_TAG, "Received no reply from server.");
throw new HttpException("Received no reply from server.");
} else if (statusLine.getStatusCode() != HttpStatus.SC_SWITCHING_PROTOCOLS) {
throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
}
// Read HTTP response headers.
String line;
boolean validated = false;
while (!TextUtils.isEmpty(line = readLine(stream))) {
Header header = parseHeader(line);
if (header.getName().equals("Sec-WebSocket-Accept")) {
String expected = createSecretValidation(secret);
String actual = header.getValue().trim();
if (!expected.equals(actual)) {
Log.v(AppConstants.DEBUG_TAG, "Bad Sec-WebSocket-Accept header value.");
throw new HttpException("Bad Sec-WebSocket-Accept header value.");
}
validated = true;
}
}
if (!validated) {
Log.v(AppConstants.DEBUG_TAG, "No Sec-WebSocket-Accept header.");
throw new HttpException("No Sec-WebSocket-Accept header.");
}
onConnect();
Log.v(AppConstants.DEBUG_TAG, userId + " : Thread should be connected by now");
// Now decode websocket frames.
mParser.start(stream);
} catch (EOFException ex) {
Log.d(AppConstants.DEBUG_TAG, "WebSocket EOF!", ex);
onDisconnect(0, "EOF");
} catch (SSLException ex) {
// Connection reset by peer
Log.d(AppConstants.DEBUG_TAG, "Websocket SSL error!", ex);
onDisconnect(0, "SSL");
} catch (Exception ex) {
onError(ex);
}
}
});
Log.v(AppConstants.DEBUG_TAG, userId + " : Thread about to be started");
mThread.start();
}
Here the problem is when I leave the application for 15 or more idle, the connection automatically closes and app becomes unusable.What is the reason behind it and how to resolve this?
Probably, it is the server that closes the idle connection. Send Ping (or Pong) periodically to keep the connection.
BTW, I guess your code is based on a certain open-source WebSocket library. If so, note that it is not of commercial quality. It does not perform even the closing handshake on disconnect().

Android socket connection timeout

My android app is connected to the server through socket, which is coded in node.js. When the is left in the foreground for 15 minutes it losses connection to the server. The following is the code that connects the sockt to the server
public void connect() {
this.connectionStatus = CONNECT_STATUS_CONNECTING;
Log.v(AppConstants.DEBUG_TAG, userId + " : Connecting to Server");
if (mThread != null && mThread.isAlive()) {
return;
}
mThread = new Thread(new Runnable() {
#Override
public void run() {
try {
Log.v(AppConstants.DEBUG_TAG, userId + " : Thread Action Started");
String secret = createSecret();
int port = (mURI.getPort() != -1) ? mURI.getPort() : (mURI.getScheme().equals("wss") ? 443 : 80);
String path = TextUtils.isEmpty(mURI.getPath()) ? "/" : mURI.getPath();
if (!TextUtils.isEmpty(mURI.getQuery())) {
path += "?" + mURI.getQuery();
}
String originScheme = mURI.getScheme().equals("wss") ? "https" : "http";
URI origin = new URI(originScheme, "//" + mURI.getHost(), null);
SocketFactory factory = mURI.getScheme().equals("wss") ? getSSLSocketFactory() : SocketFactory.getDefault();
mSocket = factory.createSocket(mURI.getHost(), port);
mSocket.setKeepAlive(true);
PrintWriter out = new PrintWriter(mSocket.getOutputStream());
out.print("GET " + path + " HTTP/1.1\r\n");
out.print("Upgrade: websocket\r\n");
out.print("Connection: Upgrade\r\n");
out.print("Host: " + mURI.getHost() + "\r\n");
out.print("Origin: " + origin.toString() + "\r\n");
out.print("Sec-WebSocket-Key: " + secret + "\r\n");
out.print("Sec-WebSocket-Version: 13\r\n");
if (mExtraHeaders != null) {
for (NameValuePair pair : mExtraHeaders) {
out.print(String.format("%s: %s\r\n", pair.getName(), pair.getValue()));
}
}
out.print("\r\n");
out.flush();
HybiParser.HappyDataInputStream stream = new HybiParser.HappyDataInputStream(mSocket.getInputStream());
// Read HTTP response status line.
StatusLine statusLine = parseStatusLine(readLine(stream));
if (statusLine == null) {
Log.v(AppConstants.DEBUG_TAG, "Received no reply from server.");
throw new HttpException("Received no reply from server.");
} else if (statusLine.getStatusCode() != HttpStatus.SC_SWITCHING_PROTOCOLS) {
throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
}
// Read HTTP response headers.
String line;
boolean validated = false;
while (!TextUtils.isEmpty(line = readLine(stream))) {
Header header = parseHeader(line);
if (header.getName().equals("Sec-WebSocket-Accept")) {
String expected = createSecretValidation(secret);
String actual = header.getValue().trim();
if (!expected.equals(actual)) {
Log.v(AppConstants.DEBUG_TAG, "Bad Sec-WebSocket-Accept header value.");
throw new HttpException("Bad Sec-WebSocket-Accept header value.");
}
validated = true;
}
}
if (!validated) {
Log.v(AppConstants.DEBUG_TAG, "No Sec-WebSocket-Accept header.");
throw new HttpException("No Sec-WebSocket-Accept header.");
}
onConnect();
Log.v(AppConstants.DEBUG_TAG, userId + " : Thread should be connected by now");
// Now decode websocket frames.
mParser.start(stream);
} catch (EOFException ex) {
Log.d(AppConstants.DEBUG_TAG, "WebSocket EOF!", ex);
onDisconnect(0, "EOF");
} catch (SSLException ex) {
// Connection reset by peer
Log.d(AppConstants.DEBUG_TAG, "Websocket SSL error!", ex);
onDisconnect(0, "SSL");
} catch (Exception ex) {
onError(ex);
}
}
});
Log.v(AppConstants.DEBUG_TAG, userId + " : Thread about to be started");
mThread.start();
}
anu solution to this problem?
After googling a lot I found out a solution to this problem. Add timeout to the socket connection.
mSocket.setSoTimeout(10*1000);
If there isn't any response, after 10 seconds it will throw SocketTimeoutException and in the catch of this exception close the connection if exists, then connect again.
catch (SocketTimeoutException e) {
if (mSocket.isConnected()) {
disconnect();
}
connect();
}
This is a simple example that shows how to set the timeout on a java socket :
sockAdr = new InetSocketAddress(SERVER_HOSTNAME, SERVER_PORT);
socket = new Socket();
timeout = 5000; // 5 seconds
socket.connect(sockAdr, timeout);
reader = new BufferedReader(new InputStreamReader(socket.getInputStream());
while ((data = reader.readLine())!=null)
log.e(TAG, "received -> " + data);
log.e(TAG, "Socket closed !");

Very slow retrieval on android with 3G connection. Not with HSDPA or WiFi or on emulator

This is a bit of a complicated question as I do not know the exact problem. The main issue is that it takes a very long to get a very small package of data from our REST server from our Android app. I will describe it in detail and hope you can help me.
Problem
Data retrieval is fast enough (+/- 100ms) when:
Connected with WiFi
Connected with HSDPA
Running on Android Emulator with network settings (delay and speed) set to GPRS
However, when I use a phone on a location with bad connection (3G instead of HSDPA) calling the services can take up to 4s (current timeout on the AsyncTask).
Android
This is the code used to communicate with the services:
/**
* Get json string from service
*
* #param urlString url of service
* #return json result from service
*/
private String callService(String urlString) {
InputStream in = null;
HttpURLConnection c = null;
Scanner s = null;
String json = null;
try {
URL url = new URL(urlString);
Log.i(getClass().getName() + ".callService()", "start calling service: " + url);
long start = java.lang.System.currentTimeMillis();
try {
setAuthentication();
c = (HttpURLConnection) url.openConnection();
c.connect();
in = new BufferedInputStream(c.getInputStream());
s = new Scanner(in);
s.useDelimiter("\\A");
json = s.next();
} catch (IOException e) {
Log.e(getClass().getName() + ".callService()", "error: " + e.getMessage(), e);
}
Log.i(getClass().getName() + ".callService()", "complete calling service: (" + (System.currentTimeMillis() - start) + " ms) " + url);
return json;
} catch (Exception e) {
Log.e(getClass().getName() + ".callService()", "error: " + e.getMessage(), e);
} finally {
if (s != null) {
s.close();
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
Log.e(getClass().getName() + ".callService()", "error: " + e.getMessage(), e);
}
}
if (c != null) {
c.disconnect();
}
}
return json;
}
I have tried several ways to call this, but currently this is done using an AsyncTask:
/**
* Retrieve json from service
*
* #param url url of service
* #return json
*/
public String getJsonFromServiceBasic(String url) {
ServiceTask task = new ServiceTask();
try {
return task.execute(url).get(4000, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
Log.e(getClass().toString() + " getJsonFromServiceBasic(" + url + ")", " interrupt exception: " + e.getMessage(), e);
} catch (ExecutionException e) {
Log.e(getClass().toString() + " getJsonFromServiceBasic(" + url + ")", " execution exception: " + e.getMessage(), e);
} catch (TimeoutException e) {
task.cancel(true);
Log.e(getClass().toString() + " getJsonFromServiceBasic(" + url + ")", " timeout exception: " + e.getMessage(), e);
} catch (Exception e) {
Log.e(getClass().toString() + " getJsonFromServiceBasic(" + url + ")", " timeout exception: " + e.getMessage(), e);
}
return null;
}
/**
* AsyncTask way of calling service
*/
class ServiceTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String json = callService(urls[0]);
return json;
}
}
AndroidManifest.xml:
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="16"/>
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Services
I do not think this is the issue, as it works fast enough with HSDPA, but I am not sure.
Restlet services on tomcat7 behind a proxy. We're using a ChallengeAuthenticator for authentication.
I have solved this problem by switching to Apache's HttpClient.
I am not sure why this is a solution as Google suggests using the HttpURLConnection, but for me this works.
Using this method instead of the callService method will solve my troubles with slow internet access.
private String callServiceClient(String urlString) {
String json = null;
HttpParams httpParams = new BasicHttpParams();
int connection_Timeout = 5000;
HttpConnectionParams.setConnectionTimeout(httpParams, connection_Timeout);
HttpConnectionParams.setSoTimeout(httpParams, connection_Timeout);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParams);
httpClient.getCredentialsProvider().setCredentials(new AuthScope(null, -1),
new UsernamePasswordCredentials(user, password));
HttpGet httpget = new HttpGet(urlString);
// Execute the request
HttpResponse response;
try {
response = httpClient.execute(httpget);
// Examine the response status
StatusLine responseCode = response.getStatusLine();
Log.i(getClass() + ".callServiceClient()", "responsecode: " + responseCode);
if (responseCode.getStatusCode() != HttpStatus.SC_OK) {
return json;
}
// Get hold of the response entity
HttpEntity entity = response.getEntity();
// If the response does not enclose an entity, there is no need
// to worry about connection release
if (entity != null) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
json = convertStreamToString(instream);
// now you have the string representation of the HTML request
instream.close();
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
e.printStackTrace();
}
return json;
}

How to send data on server through XML, And getting Response in android

I am Sending some request to server using XML file. And I should get a response accordingly. But i Am getting the File not found Exception in URL. My code is Here.
public InputStream testPost(String xmlString,URL url)
{
try
{
httpClient = new DefaultHttpClient();
connection = (HttpURLConnection)url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "text/xml");
DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(xmlString);
outputStream.flush();
isResponse = (InputStream) connection.getInputStream();
}
catch(UnknownHostException e)
{
Log.e("Failure","Network Failure"+e.toString());
}
catch(SocketException e)
{
Log.e("Failure--","Network Failure"+e.toString());
}
catch(Exception e)
{
e.printStackTrace();
}
return isResponse;
}
public void addLocation()
{
try
{
String strAddLocation = "<useraccount>" +
"<id>"+1+"</id>" +"<location>"+
"<geocode>"+77.254188+","+28.692365+"</geocode>" +
"<address>3523 16th street</address>" +
"<city>Hyd</city>" +
"<state>NY</state>" +
"<zip>"+11006+"</zip>" +
"<country>USA</country>" +
"<is_primary>"+false+"</is_primary>" +
"</location>"+"</useraccount>";
Log.i("this", strAddLocation);
urlPost = new UrlPost();
addLocationInputStream= urlPost.testPost(strAddLocation, new URL(AppConstants.HOST_URL+AppConstants.ADD_LOCATION+1));
if(addLocationInputStream!= null)
{
Log.i("the output is coming hare", "add location");
}
InputStreamReader reader = new InputStreamReader(addLocationInputStream );
StringBuilder buf = new StringBuilder();
char[] cbuf = new char[ 2048 ];
int num;
while ( -1 != (num=reader.read( cbuf )))
{
buf.append( cbuf, 0, num );
}
String result = buf.toString();
System.err.println( "\nResponse from server after delete = " + result );
reader.close();
Log.i("reponce","\nResponse from server after delete = " + result);
}
catch(Exception ee)
{
Log.i("the error is here", ee.toString());
}
}
Have you added
<uses-permission android:name="android.permission.INTERNET" />
inside of manifest tags and outside of application tag to your AndroidMainfest.xml file?

Categories

Resources