Can not connect to working webservice using android device - android

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

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.

HTTP CONNECT method with Android

I want to extend an existing Android app which sets up a http connection to a remote device which it sends commands to and receives values from.
The feature consists of a tunneled connection via a custom proxy server that has been set up. I have the http header format given which should make the proxy server create and provide a tunnel for my app.
CONNECT <some id>.<target ip>:80 HTTP/1.1
Host: <proxy ip>:443
Authorization: basic <base64 encoded auth string>
# Here beginns the payload for the target device. It could be whatever.
GET / HTTP/1.1
Host: 127.0.0.1:80
The app uses the Apache HttpClient library to handle it's connections, and I would like to integrate with that. This is not mandatory, however.
The authorization is standard conform basic auth.
I have trouble implementing this because it is not clear to me how the HttpClient is intended to be used for such behaviour.
There is no CONNECT method in the library, only GET, POST and so on. I figured this would then be managed by the proxy settings of the HttpClient instance.
The problem here is that the request line is not standard, since the CONNECT line contains an id which the custom proxy then would parse and interpret.
I now would like to know if there is any intended method to implement this using the Apache HttpClient and what it would look like with this sample data given, or if I have to implement my own method for this. And if so, which interface (there are a few that would sound reasonable to inherit from) it should implement.
Any explanation, snippet or pointer would be appreciated.
UPDATE:
I now have a small snippet set up, without Android. Just plain Java and Apache HttpClient. I still think the Host mismatch in the request is a problem, since I can't manage to establish a connection.
final HttpClient httpClient = new DefaultHttpClient();
// Set proxy
HttpHost proxy = new HttpHost (deviceId + "." + "proxy ip", 443, "https");
httpClient.getParams().setParameter (ConnRoutePNames.DEFAULT_PROXY, proxy);
final HttpGet httpGet = new HttpGet("http://" + "target device ip");
httpGet.addHeader ("Authorization", "Basic" +
Base64.encodeBase64String((username + ":" + password).getBytes()));
// Trying to overvrite the host in the header containing the device Id
httpGet.setHeader("Host", "proxy ip");
System.out.println("Sending request..");
try {
final HttpResponse httpResponse = httpClient.execute (httpGet);
final InputStream inputStream = httpResponse.getEntity ().getContent ();
final InputStreamReader inputStreamReader =
new InputStreamReader(inputStream, "ISO-8859-1");
final BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
final StringBuilder stringBuilder = new StringBuilder ();
String bufferedStrChunk = null;
while ((bufferedStrChunk = bufferedReader.readLine ()) != null) {
stringBuilder.append (bufferedStrChunk);
}
System.out.println("Received String: " + stringBuilder.toString());
}
catch (final ClientProtocolException exception) {
System.out.println("ClientProtocolException");
exception.printStackTrace();
}
catch (final IOException exception) {
System.out.println("IOException");
exception.
}
This looks fairly good to me in the way of "it could actually work".
Anyways, I receive the following log and trace:
Sending request..
2015/03/03 13:16:16:199 CET [DEBUG] ClientParamsStack - 'http.route.default-proxy': https://"device id"."proxy ip":443
2015/03/03 13:16:16:207 CET [DEBUG] SingleClientConnManager - Get connection for route HttpRoute[{}->https://"device id"."proxy ip":443->http://"target device ip"]
2015/03/03 13:16:16:549 CET [DEBUG] ClientParamsStack - 'http.tcp.nodelay': true
2015/03/03 13:16:16:549 CET [DEBUG] ClientParamsStack - 'http.socket.buffer-size': 8192
2015/03/03 13:16:16:563 CET [DEBUG] DefaultClientConnection - Connection shut down
2015/03/03 13:16:16:563 CET [DEBUG] SingleClientConnManager - Releasing connection org.apache.http.impl.conn.SingleClientConnManager$ConnAdapter#bc6a08
Exception in thread "main" java.lang.IllegalStateException: Unable to establish route.
planned = HttpRoute[{}->https://"device id"."proxy ip":443->http://"target device ip"]
current = HttpRoute[{s}->https://"device id"."proxy ip":443->http://"target device ip"]
at org.apache.http.impl.client.DefaultRequestDirector.establishRoute(DefaultRequestDirector.java:672)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:385)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:641)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:576)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:554)
at run.main(run.java:71)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
Any ideas what goes wrong?
UPDATE: As stated here, this might be due to a bug when redirecting. The fact that the target does redirect tells me, that I do not have reached the correct target, implying that the Host parameter may have not been overwritten.
In fact, this can't be done with the HttpClient at all, I tried at the wrong level. It works when done with a TcpSocket (or a SSLSocket). The custom CONNECT header can simply be assembled and sent like that:
final Socket tcpSocket = SSLSocketFactory.getDefault().createSocket("host ip", 443);
String connect = "custom CONNECT header";
tcpSocket.getOutputStream().write((connect).getBytes());
tcpSocket.getOutputStream().flush();
The response from the server can then be read with a BufferedReader or whatever.

Android tcp connection from client

I'm trying to make my android phone a client to a server I wrote in python. The server works good (I have tried it) but I can't seem to connect the phone with the server.
This is the function that should create the connection:
public String createConnection() throws IOException{
InetAddress serverAddr = InetAddress.getByName(ipString);
clientSocket = new Socket(serverAddr, portNumber);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
outToServer.writeBytes(Client.INIT_HEY.name());
String ans = inFromServer.readLine();
return ans;
}
ipString is the server ip received by the user, portNumber is the port number and they are both correct.
When I try to connect to the server, I receive "null" as the error message.
Any thoughts?
Thanks!
Try it over wifi.
If you can find the phone's IP address, try ping it from your dev system.
If your are on cell network, try access web site from browser, make sure the network connection is working.
The error was because I was running a tcp connection on the main thread.. I could've fixed it by making the class an AsyncTask but I prefered adding this:
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Thanks all!

How to replace by localhost link ? 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.

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