Sending simple POST by HttpRequest with Android - java

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
}
}

Related

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 perform simple Http Post in android?

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) {
}

Put POST request with HttpRequest

I'm making a google login through GoogleTransport and ClientLogin.
private final GoogleTransport transport = new GoogleTransport();
private final ClientLogin authenticator = new ClientLogin();
Then I'm accessing the Picasa web api.
transport.setVersionHeader(PicasaWebAlbums.VERSION);
transport.applicationName = "google-picasaandroidsample-1.0";
HttpTransport.setLowLevelHttpTransport(ApacheHttpTransport.INSTANCE);
authenticator.authTokenType = PicasaWebAlbums.AUTH_TOKEN_TYPE;
authenticator.username = StaticVariables.USER_NAME+StaticVariables.USER_DOMAIN;
authenticator.password = StaticVariables.USER_PASSWORD;
try {
authenticator.authenticate().setAuthorizationHeader(transport);
HttpRequest request = transport.buildPostRequest();
request.setUrl("https://picasaweb.google.com/data/feed/api/user/default");
request.execute();
} catch (HttpResponseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The above is working fine.
Now I want to set a POST request. But buildPostRequest() method does not support any String parameter. So, unable to post any data at the URL. How to achieve it? Please help.
You may use HttpPost with NameValuePair
private boolean sendData(ArrayList<NameValuePair> data) {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(YOUR_URL);
httppost.setEntity(new UrlEncodedFormEntity(data));
HttpResponse response = httpclient.execute(httppost);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
Then create your Name Value pairs in a different method as
private ArrayList<NameValuePair> setupData() {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
3);
nameValuePairs.add(new BasicNameValuePair(USERID, SAMPLE_USER_ID);
nameValuePairs.add(new BasicNameValuePair(USERNAME, SAMPLE_USER_NAME));
return nameValuePairs;
}
Atlast call the send data method in an AsyncTask or Intent service as sendData(setupdata())
Data in a post request is usually sent in the body of the request.

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

Android, HttpPost for WCF

I'm trying to use httpost to get data from our WCF webservice
If the webservice function is without params , something like List getAllMessages()
I'm getting the List in json, no problem here
The tricky part is when the function needs to get argument
let's say Message getMessage(string id)
when trying to call this kind of functions I get error code 500
The working code is:
public String GetAllTitles()
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://www.xxx.com/Service/VsService.svc/GetAllTitles");
httppost.setHeader("Content-Type", "application/json; charset=utf-8");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
return readHttpResponse(response);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
this code works great for functios without arguments..
I took this code and changed it to:
public String SearchTitle(final String id)
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://www.xxx.com/Service/VsService.svc/SearchTitle");
httppost.setHeader("Content-Type", "application/json; charset=utf-8");
httppost.setHeader("Accept", "application/json; charset=utf-8");
NameValuePair data = new BasicNameValuePair("id",id);
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(data);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
return readHttpResponse(response);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
The function header in thr webservice is:
[OperationContract]
public TitleResult SearchTitle(string id)
{
Stopwatch sw = LogHelper.StopwatchInit();
try
{
TitleManager tm = new TitleManager();
Title title = tm.TitleById(id);
sw.StopAndLog("SearchTitle", "id: " + id);
return new TitleResult() { Title = title };
}
catch (Exception ex)
{
sw.StopAndLogException("SearchTitle", ex, "id: " + id);
return new TitleResult() { Message = ex.Message };
}
}
Anyone can see what am I missing?
Thanks, I'm breaking my head over this one.
List isn't json,
try
String data = "{ id : \"" + id + "\" }";
Don't forget to set Content-Length to data.length.

Categories