Android httppost network violation - android

I have a problem with my android app. I mean I'm using the code from one of tuts in the internet, looks like below
public static String sendLocation(String s) {
// Create a new HttpClient and Post Header
//HttpParams params = new BasicHttpParams();
//params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://google.com/read.php");
//String d = "ok";
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("user", "mobile"));
nameValuePairs.add(new BasicNameValuePair("location", s));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// d = "CPE";
} catch (IOException e) {
// d = "E";
}
return "send";
}
}`
And the problem/bug appeared when the app try to send data to the remote server (the line below)
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
I also use the StrictMode and after that everything works, the logs shows network violation
11-08 22:34:40.020: D/StrictMode(939): StrictMode policy violation; ~duration=359 ms: android.os.StrictMode$StrictModeNetworkViolation: policy=31 violation=4
I included in the manifest file appropriate permission
<uses-permission
android:name="android.permission.ACCESS_FINE_LOCATION" />
Do you have any idea what should I do to run my app (actually send data via post to the server) without StrictMode?

The problem is that you are trying to do network calls on the main UI thread. Only use those types of methods in a separate thread.
A good example of that is here.

Related

Android server http Connection

My android app is connected to my server thorugh http connection.The server will close the connection after 10seconds . But in client side(android) i want to close the connection in 5 seconds neither i receive data or not from the server my android app must close the connection.
when I tried setsotimeout(5000) two things happens
1.The android app is sending request again and again for every 5000milliseconds.
2.It works well in the case when the server closes.
Suggest me some good logic
protected String doInBackground(Object[] params)
{
try
{
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(1);
nameValuePair.add(new BasicNameValuePair("carddata", "this " + "is " + "normal" + "transaction"));
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://127.0.0.1:8080/MyServletProject/DoubleMeServlet");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setSoTimeout(httpParameters, 5000);
httpPost.setParams(httpParameters);
HttpResponse response = httpClient.execute(httpPost);
Log.d("Http Post Response:", response.toString());
HttpEntity entity = response.getEntity();
dsds = EntityUtils.toString(entity);
} catch (Exception e)
{
if (e.toString().equals("java.net.SocketTimeoutException"))
{
dsds=e.toString();
}
If I was you, I would create a layer between by http client and my app. Every time a request is made, it restarts a 5000ms timer to kill the connection.

Unable to connect to Salesforce using RestAPI: INVALID SESSION

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.

Getting error while doing api call and android app is crash

i am new to android, i m trying to api call with php , i have done one example for it, that work on another computer fine but same app package gives error in eclipse on my laptop.
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", "Hi"));
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
}
} `
hear is my error log, i got this much of errors.
//Try following way
//List<NameValuePair> nameValuePairs
HttpClient hc = new DefaultHttpClient();
HttpPost hp = new HttpPost(url);
UrlEncodedFormEntity obj=new UrlEncodedFormEntity(nameValuePairs);
obj.setChunked(true);
hp.setEntity(obj);
HttpResponse hr = hc.execute(hp);
HttpEntity he = hr.getEntity();
Logcat is clear: Could not find a method postData(View) in the activity class. I guess you've used xml layout for setting button action.
In this case, just change your
public void postData() {
}
to
public void postData(View view) {
}
Note: setting button listeners this way isn't efficient.
Also, you should perform network operations on another thread - using network on main thread will raise NetworkOnMainThreadException on Android 3.0+

Android HTTP POST connection to file with response

How do I send the data to this PHP file below? I can establish the connection and send data, but can't receive the response. I need to send 3 parameters, the "op", Username and password.
switch ($_POST["op"]) {
// User Authentication.
case 1:
$UName = $_POST["UName"];
$UPass = $_POST["UPass"];
$UPass = md5($UPass);
//....Some code
// New user registration process.
case 2:
$UName = $_POST["UName"];
$UPass = $_POST["UPass"];
$UEmail = $_POST["UEmail"];
$UNick = $_POST["UNick"];
$UPass = md5($UPass);
//....Some code
}
My code so far:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://SomeUrl/login.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("1", "dan"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = httpclient.execute(httppost);
String responseBody = EntityUtils.toString(response.getEntity());
Log.d(TAG, ""+responseBody);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
What am I doing wrong?
Looking at your PHP code, at a bare minimum you need to specify an op parameter. Then depending on which op you're trying to carry out, make sure you specify the other needed parameters as well. For user authentication (op = 1):
nameValuePairs.add(new BasicNameValuePair("op", "1"));
nameValuePairs.add(new BasicNameValuePair("UName", "dan"));
nameValuePairs.add(new BasicNameValuePair("Pass", "somepass"));
On a side note, you should secure the PHP service with SSL, if you are using it to process sensitive user information.
Android HTTP POST should look like this:
HttpParams httpParams=new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
HttpConnectionParams.setSoTimeout(httpParams, 10000);
// Data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("UName", "dan"));
nameValuePairs.add(new BasicNameValuePair("UPass", "password"));
nameValuePairs.add(new BasicNameValuePair("op", "1"));
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://SomeUrl/login.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
}
In your PHP code I would strongly recommend to use mysql_real_escape_string($_POST['UName']) otherwise it is easy to attack via SQL injection.
I would also recommend to use either SSL connection (HTTPS) or to send the password only hashed (MD5)

403 FORBIDDEN message when I use HttpPost to send data to Django

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.

Categories

Resources