Sending a large String from Android to Servlet using Async Task - java

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

Related

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

sending a post request apache and java

I have this code block that sends a post request to one of my localhost ports:
public String request(String name){
String responseString = null;
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("userName", name));
params.add(new BasicNameValuePair("passWord","123455"));
HttpPost post = new HttpPost("http://localhost:2332/getData/postData");
post.addHeader("Content-Type", "application/x-www-form-urlencoded");
post.setEntity(new StringEntity(URLEncodedUtils.format(params,"UTF-8"), HTTP.UTF_8));
responseString = execute(post,params.toString());
return responseString;
}
public String execute(HttpRequestBase requestBase, String params){
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = null;
String responseString = "";
try {
LOG.info("Request Method:{}",requestBase.getMethod());
LOG.info("Request Parameters:{}",params);
response = httpClient.execute(requestBase);
HttpEntity entity = response.getEntity();
responseString = EntityUtils.toString(entity);
} catch (IOException e) {
e.printStackTrace();
}
return responseString;
}
I think that this code block should work because I used a tutorial as a reference but whenever I run my application the value of responseString is null or the application doesn't show me any results. Is there something wrong with my code?

Getting "Invalid JSON primitive" error while trying to get data from WebService

I'm working on an android app and I want to get some data from a WebService. I'm using this code to get JSON data from the WebService.
TextView textv=(TextView) findViewById(R.id.textv);
try {
HttpClient client = new DefaultHttpClient();
String URL = "http://server/WebService.asmx/Get_ActiveFair";
HttpPost post = new HttpPost(URL);
post.setHeader("Content-Type", "application/json; charset=utf-8");
HttpResponse responsePost = client.execute(post);
HttpEntity resEntityPost = responsePost.getEntity();
if (resEntityPost != null)
{
String response=EntityUtils.toString(resEntityPost);
Log.e("XXX",response);
textv.setText(response);
}
} catch (Exception e) {
e.printStackTrace();
textv.setText(e.toString());
Log.e("error!!",e.toString());
}
It works correctly an I get the data like this:
{
"d": "{\"Id\":2,\"Name\":\"Fair Name \",\"IsActive\":true,\"Date_Start\":\"\\/Date(1383343200000)\\/\",\"Date_End\":\"\\/Date(1384034400000)\\/\",\"Url_Map\":null,\"Details\":\"Fair Details \",\"Address\":\"FairAdress \",\"VisitingInfo\":\"Fair Visiting Info\",\"Contact\":null,\"Transportation\":\" Fair Transportation Info \"}"
}
But when I want to use another method in the webservice which needs to get FairId I get the result:
{
"Message": "Invalid JSON primitive: FairId.",
"StackTrace": " at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject()\r\n at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)\r\n at System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer)\r\n at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize[T](String input)\r\n at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)",
"ExceptionType": "System.ArgumentException"
}
And here is my code to run the Get_EventList method:
TextView textv=(TextView) findViewById(R.id.textv);
try {
HttpClient client = new DefaultHttpClient();
String URL = "http://server/WebService.asmx/Get_EventList";
HttpPost post = new HttpPost(URL);
List<NameValuePair> postParameters;
postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("FairId", "2"));
post.setEntity(new UrlEncodedFormEntity(postParameters));
post.setHeader("Content-Type", "application/json; charset=utf-8");
HttpResponse responsePost = client.execute(post);
HttpEntity resEntityPost = responsePost.getEntity();
if (resEntityPost != null)
{
String response=EntityUtils.toString(resEntityPost);
Log.e("XXX",response);
textv.setText(response);
}
} catch (Exception e) {
e.printStackTrace();
textv.setText(e.toString());
Log.e("hata!!",e.toString());
}
What can be the problem? How can I solve it?
I solve the problem by sending FairId to WebService with JSONObject. Here is my new code:
TextView textv=(TextView) findViewById(R.id.textv);
try {
HttpClient client = new DefaultHttpClient();
String URL = "http://server/WebService.asmx/Get_EventList";
HttpPost post = new HttpPost(URL);
JSONObject json = new JSONObject();
json.put("FairId", "2");
StringEntity se = new StringEntity( json.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
HttpResponse responsePost = client.execute(post);
HttpEntity resEntityPost = responsePost.getEntity();
if (resEntityPost != null)
{
String response=EntityUtils.toString(resEntityPost);
Log.e("XXX",response);
textv.setText(response);
}
} catch (Exception e) {
e.printStackTrace();
textv.setText(e.toString());
Log.e("hata!!",e.toString());
}

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