I am trying to send data from android to Django app. I want to store the data in a table in sqlite database called "mytable". Here is the android code:
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", "david");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
nameValuePairs.add(new BasicNameValuePair("year", j.toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// myTextView.setText(j.toString());
HttpResponse response = httpclient.execute(httppost);
myTextView.setText(response.getStatusLine().toString());
// myTextView.setText(response.toString());
}catch(Exception e) {
myTextView.setText("Error in http connection "+e.toString());
}
The issue is resolved now. I only needed to have a return value
Sounds like Django's Cross-Site Request Forgery framework, which by default prevents third-party POST requests. Read Django's CSRF docs for details.
Related
Hi i am trying to connect to Salesforce with the Rest API and i want to retrieve sObjects..Implementing as below
void getsObjects() throws IOException {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("https://na14.salesforce.com/services/data/v24.0/sobjects");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("X-HostCommonName", "ap1.salesforce.com"));
nameValuePairs.add(new BasicNameValuePair("X-PrettyPrint", "1"));
nameValuePairs.add(new BasicNameValuePair("Host", "ap1.salesforce.com"));
nameValuePairs.add(new BasicNameValuePair("X-Target-URI", "https://ap1.salesforce.com"));
nameValuePairs.add(new BasicNameValuePair("Content-Type", "application/json"));
nameValuePairs.add(new BasicNameValuePair("Connection", "Keep-Alive"));
nameValuePairs.add(new BasicNameValuePair("Authorization", "00D90000000qUEp!AQQAQNnuPZqEX2oqAkeQLmvq.qsBfKIMa3GCJvE7atLv2Cjy94YZn5ezRH0bosXTFthnoMNt.WpDturXB1Ijxxxxxxxxxx"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httppost.setHeader("Content-Type","application/json");
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
String result = EntityUtils.toString(response.getEntity());
System.out.println("Final response"+result);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
even if i am passing the the Authorization key , it is giving INVALID SESSION error
12-11 14:50:18.108: W/DefaultRequestDirector(27014): Authentication error: Unable to respond to any of these challenges: {token=WWW-Authenticate: Token}
12-11 14:50:18.498: I/System.out(27014): Final response[{"errorCode":"INVALID_SESSION_ID","message":"Session expired or invalid"}]
I am trying to connect to it from 2 days but no luck, can someone point me right direction, how to make rest calls.
The Authorization header should take the form Authorization: Bearer {sessionId} whereas you have Authorization:{sessionId}
You nameValuePairs appears to contains http headers, but you're not creating headers, you're passing them to setEntity, which sets the http body payload, not the headers.
You're creating a bunch of standard headers (like Host) which don't align with the actual url, and these aren't needed anyway.
try something like
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("https://na14.salesforce.com/services/data/v24.0/sobjects");
httpPost.setHeader("Authorization" , "Bearer " + sessionId)
StringEntity entity = new StringEntity("someJson", "UTF-8");
entity.setCotnentType("application/json");
httpPost.setEntity(entity)
HttpResponse response = httpclient.execute(httppost);
String result = EntityUtils.toString(response.getEntity());
System.out.println("Final response"+result);
You might also want to checkout the Force.com Android SDK which has a bunch of helpers for accessing the API.
I have a backend for my android app, which returns 404 on GET and json on POST. Now, I'm trying to do POST request using this snippet:
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/api/login");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("email", "email#email.com"));
nameValuePairs.add(new BasicNameValuePair("password", "qwerty"));
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
}
}
Server however receives GET request. With curl POST backend returns json as expected. But somehow httpPost sends GET(!) request. What could be the problem? What am I doing wrong?
Ok guys, answered my own question pretty quickly, may be helpful for others.
I replaced hostname with ip address, and it worked!
I am attempting to help a student write an android app that will contact a specific webserver. From the looks of the website, you can issue a GET requestion with your web browser and you get back a cookie session and an "authenticity token" (see the source of the page as an invisible input)
We issue a GET request and then want to follow it up with the post, but we are receiving a status code of 404 on the post. On a side note, the first GET request returns a code of 200.
Does anyone have any ideas? Below is the code that gets executed...
public void run()
{
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("https://co22.herokuapp.com/login/");
HttpPost httpPost = new HttpPost("https://co22.herokuapp.com/login/sessions");
HttpResponse response;
try
{
response = httpClient.execute(httpGet);
Log.d("matt",response.getStatusLine().toString());
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("session[network_id]", username));
nameValuePairs.add(new BasicNameValuePair("session[password]", password));
nameValuePairs.add(new BasicNameValuePair("authenticity_token","9yvxPOUpRFdsTeHAZtISEfBHpElDTHzvMjAbQnxOHDM="));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = httpClient.execute(httpPost);
Log.d("matt",response.getStatusLine().toString());
}
catch (ClientProtocolException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
It appears that the above will work correctly, but we were just sending the second post request to the wrong website.
I have android app . i should pass the data from android to web server with data security.Can any one suggest me to What are all the data security's can Provide.
You can send the data using HttpPost methos .
This is a simple example for it .
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
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
}
}
Use Https , you should buy a SSL for your server first , and then Use https to send data.
can anyone give me an idea of using web service using HTTP protocol.
Here is an example for "Executing a HTTP POST Request with HttpClient":
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "123"));
nameValuePairs.add(new BasicNameValuePair("username", "Paresh"));
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
}
}
We can use web services in our application to send and receive data from a remote server. Consider the case of an login section from a application where you need to pass username and password to the server for checking the whether the user is a valid user or not. In this case the username and password are attached with a url and send it to the remote server for validation and in response you get a value stating whether the user is a valid user or not. Usually the response will be either in XML format or JSON format from there we need to parse that response to get the necessary values. Check out the following example code in this I have created a class named "parsing" and it using the http protocol to receive a data.
public class parsing extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
HttpClient client = new DefaultHttpClient();
String postURL = "http://services.digg.com/topics?appkey=http://example.com&type=json";
HttpPost post = new HttpPost(postURL);
HttpResponse responsePOST = client.execute(post);
HttpEntity resEntity = responsePOST.getEntity();
String response=EntityUtils.toString(resEntity);
response=response.trim();
Log.i("RESPONSE=",response);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
See the response on the Logcat and do not for get to include <uses-permission android:name="android.permission.INTERNET" />
because we are fetching the data from the remote server which needs internet permission.