Connecting Android Phone to local host - android

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.

Related

How can I pass data from my android application and receive it on my ASP.NET MVC website?

I want to send the some varibeles from my android application to my ASP.NET website, so I can use it there and I don't know how to do that.
If your ASP.NET application has some type of public API that would allow it to interact with external applications, you should be able to make a Web Request to it and post the appropriate values that you needed.
I'm not terribly familiar with Android syntax, but an example like this one on making HTTP GET/POST requests from Android should point you in the right direction :
// Build your client
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("your-asp-mvc-application/Home/AcceptData");
// Build a collection of data that you want to send
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
nameValuePair.add(new BasicNameValuePair("username", "test_user"));
nameValuePair.add(new BasicNameValuePair("password", "123456789"));
// Encoding POST data
try
{
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
}
catch (UnsupportedEncodingException e) {
// log exception
e.printStackTrace();
}
// Make the request
try
{
HttpResponse response = httpClient.execute(httpPost);
// write response to log
Log.d("Http Post Response:", response.toString());
}
catch (ClientProtocolException e)
{
// Log exception
e.printStackTrace();
}
catch (IOException e)
{
// Log exception
e.printStackTrace();
}
Basically, once you make make requests, you should be able to target your application and create a Controller Action that can actually accept what you are sending it :
public ActionResult AcceptData(string username, string password)
{
// Do something here
}
First, what form of ASP.NET are you using - Forms or MVC? Also, what do you mean by "send?" Where exactly do you want the data to end up and what exactly do you want your ASP.NET application to do once it receives the data? If you simply mean that you're creating data in your phone and you want your ASP.NET web site to be able to access it too, you can just insert the data into a database that your ASP.NET web site also has access to (e.g. through a web service call or something like that).

Stream Data to Website from Android device

For a project I would like to stream the sensor data of an Accelerometer (from an android phone) to a website.
Basically I have written the application that reads the data and stores it on the phone and converts it to a string. I just want to plot the x, y and z Values as line graph dynamically on a website. So If I shake my phone, the line on the website should be moving.
I had several ideas like using Node.js or Java webserver but I couldn't found any appropriate tutorials.
So maybe someone got a good idea where to find tutorials, where I can learn how to stream data to a website from my phone. It should be easy to do or not that hard but I am not very good in making webservers or so.
Keep sending your data to the server ideally making post request.
Your webserver can just read the data from the obtained requests and update the graph.
How to write a server ? go through the below link
http://tutorials.jenkov.com/java-multithreaded-servers/singlethreaded-server.html
how to post data from android ? use an async task doing the below things
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.server.com/");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("graphvalue", "12345"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}

Android authentication using JSON

I have a Python/Django server that is the API for a web service.
I'm building an Android application that will communicate with the API and authenticate users, and enable them do all pulls/pushes from the server.
My trouble is with the particular communication with the server. Currently I use my WiFi network, and run the server like so python manage.py runserver 192.168.1.3:8000 so that it is available to any test device on my LAN.
The API is written so it returns http status messages with every response, so that I can tell the success or failure of a request before parsing the JSON reply.
On my Android side, I have used HttpURLConnection because it has the getHeaderField(null) method that I use to pick the http status message from the response. I get a status message 200 [success] when I 'ping' my server - this is a sort-of proof of concept.
My real issue is authentication. My API requires I send it a JSON with data, and it returns a JSON response [with an http status message in the head].
I can't seem to figure out how to do this. The JSON action I've seen around the interwebs are merely picking, or posting.
I am wondering how I can POST and pick up a response from the server.
Extra information
- Server supports HEAD and GET and OPTIONS.
- Assuming server home is 192.168.1.3, user login/register would be in 192.168.1.3/user, events would be in 192.168.1.3/events and so on..
- This was the closest I got to figuring out a solution, but not quite..
CODE from the AsyncTask
protected JSONObject doInBackground(String... params) {
publishProgress(true);
/*Create a new HttpClient and Post Header*/
JSONObject result=null;
HttpClient httpclient = new DefaultHttpClient();
try {
URL url = new URL(cons.PROTOCOL,cons.SERVER,cons.PORT,"/user");
HttpPost httppost = new HttpPost(url.toURI());
HttpResponse response =null;
/*Add your data*/
JSONObject j1=new JSONObject();
JSONObject json=new JSONObject();
j1.put("username", "test");
j1.put("email","test#test.com");
j1.put("password","password");
j1.put("first_name","John");
j1.put("last_name","Doe");
json.put("user",j1);
json.put("mobile_number","256774622240");
StringEntity se = new StringEntity( json.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httppost.setEntity(se);
/*Execute HTTP Post Request*/
response= httpclient.execute(httppost);
Log.i("jazz","It's ALIVE!!!!!");
Log.i("jazz",response.getStatusLine().toString());
} catch (ClientProtocolException e) {
/* TODO Auto-generated catch block*/
} catch (IOException e) {
// TODO Auto-generated catch block
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
If your are building your HttpPostRequest well, and you only want to know how to attach JSON, here you are a possible solution for it:
StringEntity formEntity = new StringEntity(yourJsonObject.toString());
yourPostRequest.setEntity(formEntity);
I hope this helps!
PS:In addition, let me recommend you the use of this component:
https://github.com/matessoftwaresolutions/AndroidHttpRestService
I've used it in an Android app that is connecting to a python server API and it makes http request easier for your Android client.
Okay, so I'm now answering my own question :D
The issue was with the path variable in the URL string.
This is the format of one of the URL constructors based on this document.
URL(String protocol, String host, int port, String file)
Since I am posting the JSON to the /user path, that's the one I insert into the constructor as the directory.
So, my URL was formed like so:
URL url= new URL("http",cons.SERVER,cons.PORT,"/user/");
My mistake in the beginning was using /user instead of /user/
but other than that, the URL structure and connections are all alright.

Android app can't connect to hostname but can connect to IP on server

I am having an odd problem with my android app. I can connect and send data when I hardcode my server's IP address, but I get the errors below when I try to use the hostname. I have been testing this through android's emulator on Windows server 2003. I also have made sure to ensure that the address starts with http and that the app uses the internet's permission. Any ideas as to why this could be? E.G I can connect when I use 123.45.678/test.php but not servername/test.php
06-12 17:02:30.360: I/Choreographer(642): Skipped 31 frames! The application may be doing too much work on its main thread.
06-12 17:03:07.670: I/Choreographer(642): Skipped 85 frames! The application may be doing too much work on its main thread.
06-12 17:03:07.810: I/Choreographer(642): Skipped 36 frames! The application may be doing too much work on its main thread.
06-12 17:03:16.200: W/System.err(642): java.net.UnknownHostException: Unable to resolve host "HOSTNAME": No address associated with hostname
Post
public void postData(String Filename) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
if (!MainActivity.address.startsWith("https://") && !MainActivity.address.startsWith("http://")){
MainActivity.address = "http://" + MainActivity.address;
}
HttpPost httppost = new HttpPost(MainActivity.address);
HttpResponse response = null;
try {
// Add your data
//MainActivity.QRdata.replaceAll("\\s+","");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("data", "<data><serial><serial>SN001</serial></serial><items><item>Test1 = Failed</item><item>Test2 = Passed</item><item>Test3 = Passed</item></items></data>"));
nameValuePairs.add(new BasicNameValuePair("file", Filename));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
response = httpclient.execute(httppost);
String res = EntityUtils.toString(response.getEntity());
Log.v("Response = ", res);
} catch (ClientProtocolException e) {
e.printStackTrace();
// TODO Auto-generated catch block
} catch (IOException e) {
e.printStackTrace();
// TODO Auto-generated catch block
}
//return response.toString();
}
}
My problem was special permissions with my company that I did not understand. I was unable to use my app to connect due to security considerations. However, if anyone else runs into the same problem that I did (I just wanted to host a PHP script to use POST), use Google App Engine. I have been using it now and it is everything I have been looking for.
https://appengine.google.com/

How to implement post method for this http post request ?

Hi this is my HTTP Post Request Method in Android client.i don't know how to implement the #POST method in the Restful web server.
public class AndroidHTTPRequestsActivity extends Activity
{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Creating HTTP client
HttpClient httpClient = new DefaultHttpClient();
// Creating HTTP Post
HttpPost httpPost = new HttpPost(
"http://localhost:8080/GPS_Taxi_Tracker_Web_Server/resources/rest.android.taxi.androidclientlocation/Login");
// Building post parameters
// key and value pair
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
nameValuePair.add(new BasicNameValuePair("email", "user#gmail.com"));
nameValuePair.add(new BasicNameValuePair("message",
"Hi, trying Android HTTP post!"));
// Url Encoding the POST parameters
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
} catch (UnsupportedEncodingException e) {
// writing error to Log
e.printStackTrace();
}
// Making HTTP Request
try {
HttpResponse 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();
}
}
what is the implementation for the post method in the java restful web service , this is my code for the Rest sever what is wrong ?
#POST
#Path("{Login}")
#Consumes({"application/xml"})
public void Add(#PathParam("email") String email,AndroidClientLocation entity) {
entity.setEmail(email);
super.create(entity);
}
Multiple questions..
What are you using as container on server side
What is your base url mapping. Your API method's path being Login, how do are you routing the remaining part of the URL (/resources/rest.android.taxi.androidclientlocation) to the API.
The API consumes application/xml but the client code is not sending/setting Content-Type as application/xml, is it taken care by the client?
When you run the request from client what is the response (HTTP Error) that you get.
Where is your REST server running (Internal or External).
Answers to the question might clarify the request a bit more.
http://developer.android.com/tools/devices/emulator.html#networkaddresses
10.0.2.2 Special alias to your host loopback interface (i.e., 127.0.0.1 on your development machine)
http://localhost:8080/.
as per link & link2
Send a request to localhost' means to send it to the local machine. In your case that would be the Android device. You want to send the request to your desktop machine, which is a remote host. The problem is that the Appengine dev_sever by default only binds to the local address, so it can't be accessed remotely (i.e., from your Android device). You need to pass the --address option to make accessible from the outside. Check your computer's IP and pass it as the address. Something like:
dev_appserver.cmd --address=192.168.2.220

Categories

Resources