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
Related
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).
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.
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
}
}
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.
I am new to the client-server side programming so my question might be basic.
Basically, I am trying to send data in JSON format from android to a Django server. The code for sending the data is the following:
try {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost:8000/androidweb/edit/");
JSONObject j = new JSONObject();
try {
j.put("name", "cdfe");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
nameValuePairs.add(new BasicNameValuePair("year", j.toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
}catch(Exception e) {
//catch the exception and print it
}
So my intention is to basically call the url mentioned in code. I added the url to Django urls.py so I can use the views.py class to store the JSON data I entered above in a sqlite database table, which contains only one field called "name". However, I don't know if my approach is right. Most code samples I have seen pass the data to a php file, so I was wondering if it is possible to do it through a python class, views.py?
If it is possible, can you please give me a code sample to be implemented in "views.py" of how to capture JSON data sent from the above code and store it in a table with a "name" field?
Thanks!
Data sent via POST is available via request.POST. Try examining request.POST['year'].