got exception when calling webservice in android? - java

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

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

org.apache.http.client.ClientProtocolException appears when HttpClient executes

I want to send to server some data via POST-request. My code:
protected Void doInBackground(Void... arg)
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost post = new HttpPost("https://money.yandex.ru/oauth/authorize");
post.addHeader("Host", "m.sp-money.yandex.ru");
post.addHeader("Content-Type", "application/x-www-form-urlencoded");
post.addHeader("Content-Length", "154");
//data back from server
String responseBackFromServer = "";
try
{
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("client_id", "51"));
pairs.add(new BasicNameValuePair("response_type", "code"));
pairs.add(new BasicNameValuePair("redirect_uri", "https://vk.com/"));
pairs.add(new BasicNameValuePair("scope", "account-info"));
post.setEntity(new UrlEncodedFormEntity(pairs));
HttpResponse server_response = httpclient.execute(post);//!!!exception is appearing here!!!
responseBackFromServer = EntityUtils.toString(server_response.getEntity());
}
catch (ClientProtocolException e)
{
e.printStackTrace();
Log.d(LOG_TAG, "" + e);
}
}
But on "HttpResponse server_response = httpclient.execute(post);" string ClientProtocolException appears. How can I fix it?
Try removing all the addHeader statements. The framework should add them for you.
See here for an example: https://hc.apache.org/httpcomponents-client-4.3.x/quickstart.html

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

Try Internet Connectivity only for few Seconds

I am trying to connect to internet where I have to fetch data, if the time exceeds more than 5 secs to connect I have to finish the process & continue to work offline.
Everything is working fine, sometimes it takes around 10secs to return when internet is not available, Now I have to return the xml == null; when the time exceeds more than time limit,
I don't want to do this in Async Task
public String getUrlData(String url) {
String xml = null;
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
System.out.println("waiting");
HttpResponse httpResponse;
try {
// start the timer here
httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
// check if the timer has exceeded by "if else"
// move to "return xml;" Manually when exceeds 5sec, but how?
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return xml;
}
Edited Code after this answer
public String getUrlData(String url) {
String xml = null;
final int TIMEOUT_MILLISEC = 5000; // 5 seconds
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParams);
HttpPost httpPost = new HttpPost(url);
System.out.println("waiting");
HttpResponse httpResponse;
try {
// start the timer here
System.out.println("Started");
httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Ended");
return xml;
}
LogCat Here >> 20 Secs
All you need to do is to define a timeout limit for your connections. For example:
final int TIMEOUT_MILLISEC = 5000; // 5 seconds
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
HttpClient httpClient = new DefaultHttpClient(httpParams);
and afterwards, use httpClient in the same way you are using it.
Edit
public String getUrlData(String url) {
String xml = null;
final int TIMEOUT_MILLISEC = 5000; // 5 seconds
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParams);
HttpPost httpPost = new HttpPost(url);
System.out.println("waiting");
HttpResponse httpResponse;
try {
// start the timer here
httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
// check if the timer has exceeded by "if else"
// move to "return xml;" Manually when exceeds 5sec, but how?
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return xml;
}
How about this:
Thread thread = new Thread() {
#Override
public void run() {
// do the downloading thing..
}
};
thread.start();
thread.join(5000);
This is just an idea, but you could set up a delayed runnable and check after 5 seconds if the file has any size.
HttpParams params = new BasicHttpParams();
// Turn off stale checking. Our connections break all the time anyway,
// and it's not worth it to pay the penalty of checking every time.
HttpConnectionParams.setStaleCheckingEnabled(params, false);
HttpConnectionParams.setConnectionTimeout(params, SOCKET_OPERATION_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, SOCKET_OPERATION_TIMEOUT);
HttpConnectionParams.setSocketBufferSize(params, 8192);
// Don't handle redirects -- return them to the caller. Our code
// often wants to re-POST after a redirect, which we must do ourselves.
HttpClientParams.setRedirecting(params, false);
// Use a session cache for SSL sockets
SSLSessionCache sessionCache = context == null ? null : new SSLSessionCache(context);
// Set the specified user agent and register standard protocols.
HttpProtocolParams.setUserAgent(params, userAgent);
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("http",
PlainSocketFactory.getSocketFactory(), 80));
schemeRegistry.register(new Scheme("https",
SSLCertificateSocketFactory.getHttpSocketFactory(
SOCKET_OPERATION_TIMEOUT, sessionCache), 443));
ClientConnectionManager manager =
new ThreadSafeClientConnManager(params, schemeRegistry);
// We use a factory method to modify superclass initialization
// parameters without the funny call-a-static-method dance.
return new AndroidHttpClient(manager, params);
Change SOCKET_OPERATION_TIMEOUT value according to your need.
This code may help you
this code from last answer is Ok
final int TIMEOUT_MILLISEC = 5000; // 5 seconds
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
HttpClient httpClient = new DefaultHttpClient(httpParams);
Only when you are trying to execute your request you have to care about 3 more exceptions
SocketTimeoutException, UnknownHostException, ConnectTimeoutException
so catch this 3 exceptions also.

Categories