How to perform simple Http Post in android? - java

I'm new to http Post. All i want to do is to send that access_id=44321 as a url
like http://myurl.com/access_id=44321 will insert 44321 to access_id in the database how to perform this operation. Am I doing it Right ?
Thanks for the help !
public class IvrsPushService {
URL url;
HttpURLConnection conn;
Details details;
String userId;
void pushData() throws Exception {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://myurl.com/Acces/DEFAULT2.ASPX?");
try {
String accessid=Details.getAssetid();
String userid=Details.getUserid();
String datetime=Details.getDate()+"\""+Details.getTime();
String mobilenumber="9785";
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("access", accessid));
nameValuePairs.add(new BasicNameValuePair("user", userid));
nameValuePairs.add(new BasicNameValuePair("date", datetime));
nameValuePairs.add(new BasicNameValuePair("mobilenumber", mobilenumber));
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
}
}
}

Http Client from Apache Commons is the way to go. It is already included in android. Here's a simple example of how to do HTTP Post using 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", "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
}
}

Try this
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://myurl.com/");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("id", "44325"));
nameValuePairs.add(new BasicNameValuePair("first_name", "abc"));
nameValuePairs.add(new BasicNameValuePair("last_name", "xyz"));
nameValuePairs.add(new BasicNameValuePair("location", "lmn"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
} catch (Exception e) {
}

Related

BasicNamesValuesPaire not working

I need to pass variable from android to php.
my file is on localhost, and the connection between android and the file is ok except the php dont get the variables i send from android.
I tried with $_get, $_POST
I tried to add .tostring method after my int variable
doesn't work
Java
protected String doInBackground(String... param) {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<>();
nameValuePairs.add(new BasicNameValuePair("p1", param[0].toString()));
nameValuePairs.add(new BasicNameValuePair("p2", param[1].toString()));
nameValuePairs.add(new BasicNameValuePair("p3", param[2].toString()));
nameValuePairs.add(new BasicNameValuePair("p4", param[3].toString()));
nameValuePairs.add(new BasicNameValuePair("p5", param[4].toString()));
nameValuePairs.add(new BasicNameValuePair("age", param[6].toString()));
nameValuePairs.add(new BasicNameValuePair("sexe", param[5]));
try {
HttpClient client = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/AppBdd.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
client.execute(httppost);
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
return null;
}
}
My php file appBdd.php :
require_once ("rees.php");
$pdo = PdoGsb::getPdoGsb();
$sexe = $_REQUEST['sexe'];
$age = $_REQUEST['age'];
$max = $_REQUEST['p1'];
$max2 = $_REQUEST['p2'];
$max3 = $_REQUEST['p3'];
$max4 = $_REQUEST['p4'];
$max5 = $_REQUEST['p5'];
$pdo->setClient($sexe, $age, $max, $max2, $max3, $max4, $max5);

Sending a large String from Android to Servlet using Async Task

In my app I am sending a String to the Servlet through BasicNameValuePairs, this way:
HttpClient httpClient = new DefaultHttpClient(); //127.0.0.1 - 10.201.19.153
HttpPost httpPost = new HttpPost(conn.urls.get("now"));
List<NameValuePair> nameValuePairs = new ArrayList<>(1);
nameValuePairs.add(new BasicNameValuePair("order", order));//"tours"
if(order.equals("reservation")){
String booking = new Gson().toJson(reservation);
nameValuePairs.add(new BasicNameValuePair("reservation", booking));
}
try {
// Add name data to request
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
//...
} //...
is there another way to send a String apart from using BasicNameValuePairs or this is the only way?
I don't exactly know why u need an alternative but here it is ..
instead of using Gson u can use following code
{
...
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("string",longString));
makeHttpRequest(url,"POST", params);
...
}
public void makeHttpRequest(String url, String method, List<NameValuePair> params) {
try {
if (method == "POST"){
DefaultHttpClient httpClient= new DefaultHttpClient();
HttpPost httpPost =new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse=httpClient.execute(httpPost);
HttpEntity httpEntity=httpResponse.getEntity();
is=httpEntity.getContent();
}else if (method == "GET"){
DefaultHttpClient httpClient=new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params,"utf-8");
if (!paramString.matches(""))
{
url +="?"+paramString;
}
HttpGet httpGet = new HttpGet(url);
lru =url;
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity=httpResponse.getEntity();
is=httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
I hope it helps

How to send a String array as basic name value pair as HTTPPOST?

I want to send a array as name value pair as httppost.My server accepts only array values.The following is my code snippet..
public String SearchWithType(String category_name, String[] type,int page_no) {
String url = "http://myURL";
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
String auth_token = Login.authentication_token;
String key = Login.key;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("authentication_token",
auth_token));
nameValuePairs.add(new BasicNameValuePair("key", key));
nameValuePairs.add(new BasicNameValuePair("category_name",
category_name));
int i = 0;
nameValuePairs.add(new BasicNameValuePair("type", type[i]));
nameValuePairs.add(new BasicNameValuePair("page", String.valueOf(page_no)));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
eu = EntityUtils.toString(entity).toString();
} catch (IOException ioe) {
String ex = ioe.toString();
return ex;
}
return eu;
}
I got the issue. Here's how:
try {
int i = 0;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("authentication_token", auth_token));
nameValuePairs.add(new BasicNameValuePair("key", key));
nameValuePairs.add(new BasicNameValuePair("category_name", category_name));
nameValuePairs.add(new BasicNameValuePair("type", type[i]));
nameValuePairs.add(new BasicNameValuePair("page", String.valueOf(page_no)));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
eu = EntityUtils.toString(entity).toString();
} catch (Exception e) {
Log.e(TAG, e.toString());
}
All I had to do was initialize a loop:
for (int i = 0; i < type.length; i++) {
nameValuePairs.add(new BasicNameValuePair("type[]",type[i]));
}
nameValuePairs.add(new BasicNameValuePair("type", Arrays.toString(type)));
convert from array to string and then send using http post,again server side parse from String to array
json_array = [{param1:"param1Value", param2:"param2Value"}]
if you want send a json array with nameValuePairs you can send like this;
new BasicNameValuePairs("param[0][param1]","param1Value")
new BasicNameValuePairs("param[0][param2]","param2Value")

got exception when calling webservice in android?

I got two to three execption when calling webservice from android apps. When i call the webservice from apps on 2.3.3(Emulator) version then i got exception like UnhostException , connectiontimeoutexception on 4.2.1(real device) version and working fine on 3.1 version, i don't know why this happen. I was trying to solve this exception from yesterday but solved yet, if any changes needed in the code then please suggest me.
In LoginActivity I call the method for making the http request
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", login_tag));
params.add(new BasicNameValuePair("email", username));
params.add(new BasicNameValuePair("password", userpsw));
JsonParserWebs jsonDataFromSrvr = new JsonParserWebs();
String loginData = jsonDataFromSrvr.makeHttpReqToSrvr(loginUrl,"POST", params);
Following is the JsonParserWebs for calling webservice
public String makeHttpReqToSrvr(String url,String requestType,List<NameValuePair> params) {
Log.i(JsonParserWebs.class.getName(),"URL..."+url);
HttpEntity httpEntity=null;
//making http request
try {
if (requestType == "GET") {
//connection time out
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
HttpConnectionParams.setSoTimeout(httpParameters, 10000);
HttpClient httpClient = new DefaultHttpClient(httpParameters);
String paramString =URLEncodedUtils.format(params, "utf-8");
HttpGet httpGet = new HttpGet(url+"?"+paramString);
HttpResponse httpResp = httpClient.execute(httpGet);
httpEntity = httpResp.getEntity();
}
if (requestType == "POST") {
//connection time out
// From stackoverflow, I addes following three line but still got ConnectTimeoutException
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
HttpConnectionParams.setSoTimeout(httpParameters, 10000);
HttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResp = httpClient.execute(httpPost);
httpEntity = httpResp.getEntity();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
json = EntityUtils.toString(httpEntity);
Log.v("JSON", "data"+json);
} catch (Exception e) {
e.printStackTrace();
}
// try parse the string to a JSON object
return json;
}
Thanks in Advance
You need to use AsyncTask , otherwise it will crash!
1. use AsyncTask when ever you use time consuming process other wise you will get network exception
2. take internet permission in .mainfeast

Sending simple POST by HttpRequest with Android

I want my application to send two strings through the query string to a php file that will handle them as POST variables.
So far I have this code
public void postData() {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("www.mywebsite.com/my_phpfile.php?var1=20&var2=31");
try {
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
I think it's an easy problem to solve but it's my first android app and I'd appreciate all the help.
Use nameValuePairs to pass data in the POST request.
Try it like this :
public void postData() {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/yourscript.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "123"));
nameValuePairs.add(new BasicNameValuePair("string", "Hey"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// Catch Protocol Exception
} catch (IOException e) {
// Catch IOException
}
}

Categories