How to replace by localhost link ? Android - android

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.

Related

Connecting Android Phone to local host

In my application i am using API's which are hosted on local server, and can be accessed on network. On emulator it works fine as it is connected to proper network. When I am using app on my phone it wont.
Is it possible to access local API's through phone with our normal internet connection?
I am using below http code for accessing API's.
public String getResponse(String url, int method, String postParameter) {
HttpResponse response = null;
// Creating HTTP client
HttpClient httpClient = new DefaultHttpClient();
// Creating HTTP Post
HttpPost httpPost = new HttpPost(url);
// Building post parameters
// key and value pair
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
nameValuePair.add(new BasicNameValuePair("jObj", postParameter));
// Url Encoding the POST parameters
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
} catch (UnsupportedEncodingException e) {
// writing error to Log
e.printStackTrace();
}
// Making HTTP Request
try {
response = httpClient.execute(httpPost);
// writing response to log
Log.d("Http Response:", response.toString());
} catch (ClientProtocolException e) {
// writing exception to log
e.printStackTrace();
} catch (IOException e) {
// writing exception to log
e.printStackTrace();
} catch (Exception e2) {
e2.printStackTrace();
}
return response.toString();
}
Is there any setting which we can do for accessing through our normal internet?
Thanks in Advance
If you have it hosted on your local machine, you will have to find a way to connect both your phone and your local machine on the same network (most commonly Wifi). A simple work-around to this is creating a hotspot in your android device and connecting your local machine to it. Make sure to set the correct IP address in the android app.
Find your local machine ip address where the api's are hosted
using ipconfig and pass on the ip address in url
your url should be like 192.168.0.102 which is assigned by modem.
Answering as I cant comment, Please check that your phone is connected to your network and not using mobile data or some other WIFI network outside of your network.

Can not connect to working webservice using android device

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

Get xml from a php webservice url using android

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.

UnknownHostException is thrown in android app if hostname is used instead of IP address

I have the following code which I use to send a request to the server.
String inputXML = createInputXML(searchText);
HttpClient httpclient = new DefaultHttpClient();
String url = "http://mysite.com/action";//Works fine if I use IP address directly,for eg:http://1.2.3.4/action
HttpPost httppost = new HttpPost(url);
HttpResponse response=null;
StringEntity se = null;
try {
se = new StringEntity(inputXML, HTTP.UTF_8);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
se.setContentType("text/xml");
httppost.setHeader("Content-Type","application/xml;charset=UTF-8");
httppost.setEntity(se);
try {
response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
When I run the program on emulator I am getting a UnKnownHostException on the line
response = httpclient.execute(httppost);
If I use the ip address directly instead of host name,the request is sent correctly.
Please note the following points:
I am using Android 2.3.3
I have added <uses-permission android:name="android.permission.INTERNET"></uses-permission> in the manifest xml
Proxy settings are updated in the emulator's APN.
Using the browser in the emulator I can access a website with their host names.
Any idea why this is causing an issue?
Please make sure, you followed all steps 1-4 user700284 described in his Question.
HttpClient client = new DefaultHttpClient();
//Get the default settings from APN (could be also hard coded stuff)
String proxyHost = android.net.Proxy.getDefaultHost();
int proxyPort = android.net.Proxy.getDefaultPort();
//Set Proxy params of client, if they are not the standard
if (proxyHost != null && proxyPort > 0) {
HttpHost proxy = new HttpHost(proxyHost, proxyPort);
client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
}
HttpGet request = new HttpGet("http://www.google.com");
The url has nothing to do with the line
se = new StringEntity(inputXML, HTTP.UTF_8);
are you sure it is this line?

Getting socket timeout exception on windows but not on linux

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.

Categories

Resources