I developed android app and tested in Samsung tab 2.The code fetch the data from java server page which hosted in server.It works day before,but now it shows network time out exception during urlConnection.getInputStream() .I d't change anything in my code. pls help me to overcome the error.
try {
String tally_ipaddr="XXXXXXX";
URL url = new URL(tally_ipaddr+"/Iplogin.jsp");
urlConnection = (HttpURLConnection) url.openConnection();
String line = "";
InputStreamReader isr = new InputStreamReader(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null){
sb.append(line);
}
Toast.makeText(MyActivity.this, sb.toString(), Toast.LENGTH_LONG).show();
}
catch (Exception e) {
e.printStackTrace();
Toast.makeText(MyActivity.this, e.toString(), Toast.LENGTH_LONG).show();
}
class UrlFetch extends AsyncTask<Void,Void,Void>
{
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
String tally_ipaddr="XXXXXXX";
URL url = new URL(tally_ipaddr+"/Iplogin.jsp");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000); // 5 seconds
conn.setRequestMethod("GET");
conn.connect();
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
conn.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
and call the asynctask like given below
new UrlFetch().execute();
Hope the above code will works for you
I notice the address ends with "Iplogin.jsp".
Make sure the server is accepting connections from the IP address of your device. I think the IP address of your device has changed and the server is no longer responding to requests from that device.
The fact that you can access the service from your desktop browser but NOT from the device browser is highly suspect.
Related
My application sends data to server and get data from it. The application successfully executes on WiFi, but it fails on 3G. Its exception is network problem and sometimes server timeout. It does not give response code when I try to log it.
The server code is prepared using REST API.
Here is the java code:
#Override
protected String doInBackground(String... params) {
String lastOduuFk = "new";
String oduuLang = "new";
String ROOT_WEB = "http://www.example.com/";
String updateTaateeUrl = ROOT_WEB + "v1/loadOduu?lastOduuFk=" + lastOduuFk + "&lang=" + oduuLang;
BufferedReader bufferedReader = null;
HttpURLConnection httpURLConnection = null;
URL url = null;
String api_val = "xxxxxxxxxxxxx";
String mainInfo = null;
try {
url = new URL(updateTaateeUrl);
Log.i(TAG, "Try this url");
httpURLConnection = (HttpURLConnection) url.openConnection();
//Property of the connection
httpURLConnection.setDoInput(true);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Authorization", api_val);
httpURLConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 5.1; rv:19.0) Gecko/20100101 Firefox/45.0");
httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
httpURLConnection.setConnectTimeout(30000);
httpURLConnection.setReadTimeout(30000);
httpURLConnection.connect();
int reponse = httpURLConnection.getResponseCode();
Log.i(TAG, "first_Req_res: " + reponse);
InputStream inputStream = httpURLConnection.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
String result = "";
String line;
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
mainInfo = result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (SocketTimeoutException connTimeout) {
this.socketTimedOut = true;
} catch (IOException e) {
e.printStackTrace();
this.netWorkProblem = true;
} finally {
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
try {
if (bufferedReader != null) {
bufferedReader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return mainInfo;
}
The codes runs well when the phone is connected to WiFi connection. But on 3G it does not work. When I open the link with the phone browser it opens successfully on 3G.
Even it does not log Log.i(TAG, "first_Req_res: " + reponse);
I have tried to change its user-agent to httpURLConnection.setRequestProperty("User-Agent", ""); , but did change any thing. I have also tried to increase its connection and read timeout time. The method just keeps putting out null.
It log looks like thi
................
08-14 16:17:43.092 14882-16108/xyz.natol.kubbaa I/xyz.natol.kubbaa: Try this url
08-14 16:18:52.420 14882-14882/xyz.natol.kubbaa I/xyz.natol.kubbaa: first_Req_result: null
08-14 16:18:55.923 14882-14882/xyz.natol.kubbaa D/InputMethodManager: windowDismissed mLockisused = false
........................
What shall I do to make it work on 3G?
I'm actually srugling with my application using HttpUrlConnection, I tried the simplest code found on the internet and still got a FatalShutDown in the logcat and I don't understand the problem.
Here is the code :
try {
URL url = new URL("http://www.android.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader r = new BufferedReader(new InputStreamReader(in));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line).append('\n');
}
response_textview.setText(total.toString());
urlConnection.disconnect();
}
catch (MalformedURLException e){
response_textview.setText(e.getMessage());
}
catch (IOException e){
response_textview.setText(e.getMessage());
}
And I got this in the logcat :
Thanks
Wrap your code with Asynktask doInBackground() method.
You need to make request in new thread. Probably, your code (it is only try catch) is running on main thread. This operation is denied. Try to use e.g. Thread.class to make request in new thread.
You shouldn't perform network operation on main thread. Use AsyncTask.
1. Create AsyncTask object and move your code into doInBackground method as mentioned below:
AsyncTask task = new AsyncTask<Void,String,String>(){
#Override
protected String doInBackground(Void... params) {
// perform your network operation here and return response
try {
URL url = new URL("http://www.android.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader r = new BufferedReader(new InputStreamReader(in));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line).append('\n');
}
urlConnection.disconnect();
}
catch (MalformedURLException e){
return e.getMessage();
}
catch (IOException e){
return e.getMessage();
}
return total.toString();
}
protected void onPostExecute(String response){
// response returned by doInBackGround() will be received
// by onPostExecute(String response)
response_textview.setText(response);
}
};
2. Execute task
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
I need to send data to a web service that is write in c# .net,
if I use a c# program it can get the names of the web service and
the function that I can use I guess cause it's java it can't do the same
as c#, if someone know how to do this it's will be great.
thanks for the help!
I use httpURLConnection and write this code to send and get the response
from connection.
BufferedReader reader = null;
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
sb.append(line + '\n');
}
Log.i("","here "+sb.toString());
return sb.toString();
} catch (Exception e) {
Log.i("","problem in connection");
return null;
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
If I'm not mistaken, C# web services uses SOAP protocol, so you'll probably need to parse the soap response which will give the information about the web service api:
check this thread:
Parsing SoapObject Responst in android
My android servlet is designed to post request and receive responses with a tomcat servlet on an Apache Tomcat server. For debugging, I have set up the Servlet with identical POST and GET methods so I can try the functionalities and accessability via browsers.
To cut the long story short: When I deploy the app, I can easily access it from the AVD device browser via 10.0.2.2:8080/my_app?request=test and I get a result that's just fine. Same is true for access from my machine with localhost:8080/my_app?request=test.
But when I try it from my app, I always get a java.io.FileNotFoundException: http://10.0.2.2:8080/my_app.
Why?
What did I try so far: The app has internet permissions and they also work, for to get to the Servlet communication point, I have to go through a login procedure via PHP first, and it's on the same server and works normally.
My AsyncTaskconnecting to the servlet looks like this:
AsyncTask<Void,Void,String> getDBdata = new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
URL url = null;
try {
url = new URL("http://10.0.2.2:8080/my_app");
} catch (MalformedURLException e) {
e.printStackTrace();
}
String text;
text = null;
JsonArray js = null;
try {
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("action", "getDBData");
connection.setDoInput(true);
connection.connect();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder builder = new StringBuilder();
String aux = "";
while ((aux = in.readLine()) != null) {
builder.append(aux);
}
text = builder.toString();
} catch (IOException e) {
e.printStackTrace();
}
return text;
Alright, of course I've been trying to send params in the header, and this led to BS. Rookie mistake!
bcody's answer from this question helped me a lot with debugging! Also, taking a look at the server protocol from the servlet might have led me to the error earlier.
This is the code that finally worked:
AsyncTask<Void,Void,String> getDBdata = new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
URL url = null;
try {
url = new URL(Constants.SERVER_URL + getDBdataURL);
} catch (MalformedURLException e) {
e.printStackTrace();
}
String text;
text = null;
try {
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Accept-Charset", "UTF-8");
connection.setRequestProperty("User-Agent", "Mozilla/5.0 ( compatible ) ");
connection.setRequestProperty("Accept", "*/*");
connection.setChunkedStreamingMode(0);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setDoOutput(true);
connection.setRequestMethod("POST");
String request = "action=getDBdata";
PrintWriter pw = new PrintWriter(connection.getOutputStream());
pw.print(request);
pw.close();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder builder = new StringBuilder();
String aux = "";
while ((aux = in.readLine()) != null) {
builder.append(aux);
}
text = builder.toString();
} catch (IOException e) {
e.printStackTrace();
}
return text;
}
I currently have a project where different parameters are requested from an online CGI file, and each request is supposed to be processed in different threads. When I run my code by itself it works great, however it doesn't seem to connect when I put it in a thread.
My code is below:
public void run() {
connect();
}
public synchronized void connect(){
StringBuffer response = new StringBuffer("");
try {
String data = "year=" + year + "&top=" + numNames + "number=";
// Send data
URL url = new URL("http://www.ssa.gov/cgi-bin/popularnames.cgi");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
response.append(line);
}
wr.close();
rd.close();
} catch (Exception e) {
System.out.println(e);
}
System.out.println(response);
}
}
Remove the synchronized call on connect. That should solve your problem
public synchronized void connect(){