I am dumstruck here! I've written an android app that uploads an image from a device to a servlet. The app works FLAWLESSLY on the emulator on both my windows 7 and linux pcs. However when i run the app on my real device and the servlet is on my windows pc, I get a SocketTimeoutException! But if the servlet is running on the linux pc, it works perfectly!! Any ideas what i have to tweak on windows to get this to work?! I even changed my application servers from glassfish to tomcat and still the same results!! Any tips would be appreciated.. Thanks
Here's part of the servlet that reads the image from the android client. I used apache fileupload at the client end
try {
List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : items) {
if (item.getFieldName().equals("imgFile")) {
String fileName = item.getName();
InputStream fileContent = item.getInputStream();
int d;
FileOutputStream fout = new FileOutputStream(new File( DIR + "savedImage.jpg"));
while((d = fileContent.read()) != -1)
{
fout.write(d);
}
fout.close();
}
}
} catch (FileUploadException e) {
throw new ServletException("Cannot parse multipart request.", e);
}
With the servlet deployed on my windows machine, i get the exception at the
new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
line.
Here's the android client code segment that sends the file to the servlet
File f = new File("/mnt/sdcard/img/imgToUpload.jpg");
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://192.168.2.2:8084/WebApplication5/imgServlet");
MultipartEntity entity = new MultipartEntity();
FileBody fb = new FileBody(f);
entity.addPart("imgFile", fb);
post.setEntity(entity);
try {
HttpResponse servletResponse = client.execute(post);
HttpEntity respentity = servletResponse.getEntity();
} catch (IOException ex) {
Logger.getLogger(FTXWActivity.class.getName()).log(Level.SEVERE, null, ex);
}
The most likely explanations are
That your device and your Windows box are not on the same subnet (or even the same network). Are you sure your device is connected up to your wifi?
Your windows box has a firewall blocking port 8084. If you were running the emulator from your Windows box, it still would have worked.
You might try looking at netstat -ab output on the windows box and make sure you see it listening on the right port.
Related
I used android device to connect via wifi to localhost of my computer.This is the string i m passing to retrieve values from web service.
I get a error message in logcat OSNEtworkSystem_Connect fail:Timeout. Can any one sugest a solution please.
String tabledata = getServerData[a link]("http://10.0.2.2:52764/Service1.asmx/getTrainTimeTable? FromSt='"+frm+"'"+" ToSt= '" +t+ "'"+" FromTime= '" +t01+ "' "+"ToTime='"+t02+ "'"+" ArriveTime= '" +at+ "'"+" DepartTime= '" +dt+ "'"+" ReachingTime= '" +rt+ "'"+" TrainId= '"+tid+"'" )[a link];
private String getServerData(String url) {// requet and response happens here
String data = null;
try {
// Send GET request to <service>/GetPlates
HttpGet request = new HttpGet(url);
DefaultHttpClient httpClient = new DefaultHttpClient();
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
HttpResponse response = httpClient.execute(request);
HttpEntity responseEntity = response.getEntity();
// Read response data into buffer
char[] buffer = new char[(int) responseEntity.getContentLength()];
InputStream stream = responseEntity.getContent();
InputStreamReader reader = new InputStreamReader(stream);
reader.read(buffer);
System.out.println(new String(buffer));
stream.close();
JSONObject o = new JSONObject(new String(buffer));
data = (String) o.get("d");
System.out.println(data);
} catch (Exception e) {
e.printStackTrace();
}
return data;
}
after changing ip in to pc ip connection timeout eror is gone. now im gettin this error.
Your problem is that you are using 10:0:2:2 to connect to devices. you need to provide PC's IP address when trying the application on real device.
follow the steps:
1- go to CMD and type ipconfig.
2- Search for IPv4 and copy the address.
3- use it in your code.. this is an example of how it should look like:
http://192.168.0.106:52764/Service1.asmx/getTrainTimeTable?.... // you must have similar IP to this.
4- Turn off the firewall and any anti-virus program
hope this will make your application work in a real device. please give me a feedback of what will happen
If you really mean connect localhost via wi-fi
instal a virtual router to your computer. Then via wi-fi connect to your computer with your mobile device.
here is a link for virtual router
when you install it, connect with your mobile device to that virtual wi-fi provider. probably the ip that you should connect will be
http://192.168.1.1:52764/Service1.asmx/getTrainTimeTable? something(to
learn it open cmd-forwindowns enter ipconfig to learn the router device's
ip.
Be careful if you have internet connection
there will be two major ip addresses one is for your
computer that as a client to connect to the internet,
the other one is for the virtual router as a servise host which you need to connect connect
I am developing an app that updates independently from the Android Play Store. On start-up it checks for a newer version and downloads the new .apk file from the server if required.
The problem is that the .apk file download url executed by HTTP request, is redirected to a Vodafone landing page asking to change the mobile internet settings. The .apk file downloaded by the app is then actually this html webpage.
Visiting any website through the android internet browser does not get redirected to this page. My MIME settings on the hosting server is correctly set up. I am using the same code, hosting provider and mobile carrier on another project without any problems, although that project is running Toshiba tablets on OS 3.2 and this project is Samsung tablets on OS 4.1.
What can I test or change to get it working, or is it some carrier or tablet/OS related problem? Any help would be appreciated. The related code is included below if someone wants to check it, but as mentioned I have no problems with it on another project.
private class UpdateDownloadTask extends AsyncTask<Void, Void, String> {
HttpClient httpclient;
HttpGet httpget;
HttpResponse response;
HttpEntity httpentity;
OutputStream outputStream;
protected void onPreExecute () {
//do not lock screen or drop connection to server on login
activity.getWindow().addFlags(LayoutParams.FLAG_KEEP_SCREEN_ON);
//initiate progress dialogue to block user input during initial data retrieval
ProcessingDialog = ProgressDialog.show(context, "Please Wait", "Downloading Updates", true,false);
}
#Override
protected String doInBackground(Void... nothing) {
try {
//set timeouts for httpclient
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
HttpConnectionParams.setSoTimeout(httpParameters, 5000);
//setup http get
httpclient = new DefaultHttpClient(httpParameters);
httpget = new HttpGet(uriApk);
// Execute HTTP Get Request
response = httpclient.execute(httpget);
httpentity = response.getEntity();
//create location to store apk file
String path = Environment.getExternalStorageDirectory() + "/download/";
File file = new File(path);
file.mkdirs(); //if download folder not already exist
File outputFile = new File(file, apkName);
//write downloaded file to location
outputStream = new FileOutputStream(outputFile, false);
httpentity.writeTo(outputStream);
outputStream.flush();
outputStream.close();
return "success";
}
catch (Exception e) {
return "error: " + e.toString();
}
}
#Override
protected void onPostExecute(String result) {
//check if result null or empty
if (result.length() == 0 || result == null) {
Toast.makeText(context, "Could Not Download Updates, Please Try Again. Closing Application.", Toast.LENGTH_LONG).show();
activity.finish();
}
//update downloaded
if (result.equals("success")) {
//install downloaded .apk file
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/download/" + apkName)), "application/vnd.android.package-archive");
activity.startActivity(intent);
//activity.finish();
}
//update not downloaded
else {
Toast.makeText(context, "Could Not Download Updates, Please Try Again. Closing Application.", Toast.LENGTH_LONG).show();
activity.finish();
}
//close update dialog
try {
ProcessingDialog.dismiss();
} catch (Exception e) {
// nothing
}
//release screen lock
activity.getWindow().clearFlags(LayoutParams.FLAG_KEEP_SCREEN_ON);
}
}
I had to set carrier setting to "Do not adapt any sites" through the Android internet browser. After that I added the following code to get it working.
httpget.setHeader("Accept", "application/vnd.android.package-archive");
httpget.setHeader("Content-Type", "application/vnd.android.package-archive");
String userAgent = "Mozilla/5.0 (Linux; U; Android 2.2; en-us; SCH-I800 Build/FROYO) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1";
httpget.setHeader("User-Agent", userAgent);
Hope this helps someone else with the same problem.
I test in emulator it can run correctly. But I test on the phone, it always throw an exception.
public static String doGet(String url) {
try {
HttpGet method = new HttpGet(url);
DefaultHttpClient client = new DefaultHttpClient();
// HttpHost proxy = new HttpHost("10.0.0.172", 80); The two sentence added on the phone, it still can not run
// client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
method.setHeader("Connection", "Keep-Alive");
HttpResponse response = client.execute(method);
int status = response.getStatusLine().getStatusCode();
if (status != HttpStatus.SC_OK)
throw new Exception("");
return EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (Exception e) {
return "Connection errors!";
}
}
I check API4 when create project. And test in emulator android 1.6. Test the phone is on android 2.3.3. I also test in computer android-x86 2.2 jars. It is no problem. I add <uses-permission android:name="android.permission.INTERNET"/> in AndroidManifest.xml. I do not know the reason. Anyone’s opinion is thankful.
What thread you call this function? You cant create connection in UI thread
I am parsing an xml file.
One of the method is below :
public static String getXML(){
String line = null;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://p-xr.com/xml/");
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
line = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
} catch (MalformedURLException e) {
line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
} catch (IOException e) {
line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
}
return line;
}
Here, I want to replace
HttpPost httpPost = new HttpPost("http://p-xr.com/xml/");
by
HttpPost httpPost = new HttpPost("http://127.0.0.1/myfile.xml");
As i can browse http://127.0.0.1/myfile.xml in my browser.
But when i write this address to above code it doenst work.
why ?
My project requires http method to access xml file.
In emulator the localhost is the emulator itself not your system which runs the emulator. So it will not work.
Use 10.0.2.2 instead.
Use 10.0.2.2 in this case, check out Emulator Networking.
In the emulator there are some specially defined address aliases used to access networks outside of the emulator itself.
To access localhost on the system running the emulator (ie. the host system), use 10.0.2.2
Reference here:
http://developer.android.com/guide/developing/devices/emulator.html#emulatornetworking
If you're want to do this with an Android device:
You can find out the IP address of your computer by using ifconfig on Mac or Linux or ipconfig on Windows.
Then you can replace p-xr.com / 127.0.0.1 with that IP address.
You'll need to make sure that you don't have a firewall set up on your computer and if so, you'll have to allow access to your Android device in order to contact your local HTTP server.
I want to read a xml from a service url, I wrote the code, my url is ok, seen from browser,
public String getXML(){
String line = null;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpPost = new HttpGet("http://localhost/simplewebservice/index.php?user=1");
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
line = EntityUtils.toString(httpEntity);
} catch (Exception ex) {
Log.d("Error reading xml", ex.toString());
}
return line;
}
But it gives me the following error java.net.SocketException: Permission denied.
Can anyone have a better solution for this?
Kind regards,
Pritom.
in your manifest.xml add this description
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
I am sure that your using emulator.
Andriod emulator is separate virtual machine by itself. If we provide localhost/127.0.0.1 as a hostname, then emulator will try to search url within its environment. To avoid this problem, we need to provide the ipaddress of local machine.
Pls note that machine name as a hostname will also give problem.
127.0.0.1 refers to localhost in the Emulator, not your machine.
Use 10.0.2.2 to connect to your host machine.