I am developing a android app where I am using Zend framework to build APIs. I am calling API using this code. This is code in IntentService class.
HttpClient client = new DefaultHttpClient();
// Set timeout values
client.getParams().setIntParameter(
CoreConnectionPNames.CONNECTION_TIMEOUT,
CONNECTION_TIMEOUT * 1000);
client.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT,
SOCKET_TIMEOUT * 1000);try {
HttpUriRequest httpRequest = null;
HttpResponse response = null;
// Set HttpUriRequest based on type of HTTP method
if (method.equals("GET")) {
HttpGet request = new HttpGet(url);
httpRequest = request;
}
// Get response
response = client.execute(httpRequest);
BufferedReader rd = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
// Read the response
String responseString = readResponseContent(rd);
Log.e(TAG, "length of response is " + responseString.length());
Log.e(TAG, "response :" + responseString);
// If status code 200 then send response
}catch (Exception e) {
MyLog.e(TAG, "Exception while connecting to URL : " + url);
e.printStackTrace();
sendUnknownError();
}
Now the problem is I have created one API which response is very long. But After getting this I am sending broadcast to where it is called. It returns response in chunks So when it receives response first time but actually response is not yet completed. So that's causing some issues later on. So How can I wait for full response before calling broadcast method.
So I need to wait for it to get full response. How I can do this ?
Related
I want to fire a blocking call to my php file which queries my db. I want it to be blocking and not async as i don't want the user shown anything until this call is successful or not.
I run the below code, it stops at response = httpclient.execute(httpget); for a minute or two before going into catch for error. I cant see an error in the e item.
Anybody know whats going on here - my php file works with async task.
public static String blockingHttpCallToUrl(String url)
{
String result="nothingReturned";
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpGet httpget = new HttpGet(url);
// Execute the request
HttpResponse response;
try {
response = httpclient.execute(httpget);
// Examine the response status
Log.i("Praeda", response.getStatusLine().toString());
// Get hold of the response entity
HttpEntity entity = response.getEntity();
// If the response does not enclose an entity, there is no need
// to worry about connection release
if (entity != null) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
result= convertStreamToString(instream);
// now you have the string representation of the HTML request
instream.close();
}
} catch (Exception e) {}
return result;
}
i am developing an android application with RESTful WebServices
suppose ,
i am sending a url http request as somewebservice/data/access
and is sends data as {"serviceMessageCode":1,"serviceMessageText":"aaaaaa","items":null}
and i want to send another request with that obtained key as
somewebService/rest/services/secure/getcategories?apikey=aaaaaa
int sMC = jsonObj.getInt("serviceMessageCode");
if (sMC == 1) {
smt = jsonObj.getString("serviceMessageText");
can i use somewebService/rest/services/secure/getcategories?apikey=smt
i think i should not do so , some one tell me how to achieve this..!!
please help....
There is no reason why you could not pass some data by GET parameters. It really depends on Rest API on your backend server. Do you use any REST client or base apache http package classes to make requests to server?
Edited:
BufferedReader in = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpGet request = new HttpGet();
String uri = String.format("http://somewebService/rest/services/secure/getcategories?apikey=%s", Config.API_KEY); // API_KEY is constant value written somewhere or could you pass it as method argument
URI website = new URI(uri);
request.setURI(website);
HttpResponse response = httpclient.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = null;
StringBuilder builder = new StringBuilder();
while(null != (line = in.readLine())) {
builder.append(line);
}
in.close();
} catch(Exception e) {
Log.e("log_tag", "Error in http connection "+e.toString());
}
I use to make two types of httpGet call. One for parsing JSON with Gson and one for getting the string, for small JSONs....
This is what I use for parsing with GSON:
static HttpGet getRequest;
static HttpResponse getResponse;
#SuppressLint("NewApi")
public static InputStream retrieveStream(String url) {
if (android.os.Build.VERSION.SDK_INT >= 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
int timeout = 30000;
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, timeout);
HttpConnectionParams.setSoTimeout(httpParameters, timeout);
DefaultHttpClient client = new DefaultHttpClient(httpParameters);
getRequest = new HttpGet(url);
try {
getResponse = client.execute(getRequest);
final int statusCode = getResponse.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w("ERROR", "Error " + statusCode + " for URL " + url);
return null;
}
HttpEntity getResponseEntity = getResponse.getEntity();
return getResponseEntity.getContent();
} catch (IOException e) {
getRequest.abort();
Log.w("ERROR", "Error for URL " + url, e);
} catch (Exception e) {
getRequest.abort();
Log.w("ERROR", "Error for URL " + url, e);
}
return null;
}
Yes, almost always, if there are some errors on JSON or there's no connection, it gives me null and I handle it.
Yes, almost always, if JSON is correct and I have connection, I can parse it successfully.
But few times, I think around 10 or 11 in one month, it doesn't do anything. It stops and doesn't continue (I let it for 20 minutes). It doesn't return null due to URL error, JSON error or TIMEOUT, it just stops. In that moment, my connection is stopped (no movements) but my connection works normally (because I receive messages from, for example WhatsApp).
So, if I open a ProgressDialog, it never closes because I can't handle a null or a successful InputStream, so I can't make the user know that, in the worst of the cases, he/she has to retry.
I'm making all this stuff asynchronously.
What am I doing bad?
Thanks in advance.
I have a method to connect to send post data to a webservice and get the response back as follow:
public HttpResponse sendXMLToURL(String url, String xml, String httpClientInstanceName) throws IOException {
HttpResponse response = null;
AndroidHttpClient httpClient = AndroidHttpClient.newInstance(httpClientInstanceName);
HttpPost post = new HttpPost(url);
StringEntity str = new StringEntity(xml);
str.setContentType("text/xml");
post.setEntity(str);
response = httpClient.execute(post);
if (post != null){
post.abort();
}
if (httpClient !=null){
httpClient.close();
}
return response;
}
Then, in my AsyncTask of my fragment, I try to read the response using getEntity():
HttpResponse response = xmlUtil.sendXMLToURL("url", dataXML, "getList");
//Check if the request was sent successfully
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
// Parse result to check success
responseText = EntityUtils.toString(response.getEntity());
if (!xmlParser.checkForSuccess(responseText, getActivity())){
//If webservice response is error
///TODO: Error management
return false;
}
}
And when I reach that line:
responseText = EntityUtils.toString(response.getEntity());
I get an exception: java.net.SocketException: Socket closed.
This behavior doesn't happen all the time, maybe every other time.
Just write
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(your url);
HttpResponse response = client.execute(post);
it should work.No need to write codes which makes confusion.
I also experienced the 'socket closed' exception when using a client instance built using HttpClientBuilder. In my case, I was calling HttpRequestBase.releaseConnection() on my request object within a finally block before processing the response object (in a parent method). Flipping things around solved the issue... (working code below)
try {
HttpResponse response = httpClient.execute(request);
String responseBody = EntityUtils.toString(response.getEntity());
// Do something interesting with responseBody
} catch (IOException e) {
// Ah nuts...
} finally {
// release any connection resources used by the method
request.releaseConnection();
}
I've an app that call a webservice. I've logged the time it takes to complete this call with and without GZIP. I ran the app 5 times with and 5 time without GZIP and it actually took longer with GZIP. So i can only think GZIP had no effect or i have implemented it badly. Any ideas why there is no change?
public String connect(String url) {
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpGet httpget = new HttpGet(url);
httpget.addHeader("Accept-Encoding", "gzip");
// Execute the request
HttpResponse response;
try {
long start = System.currentTimeMillis();
response = httpclient.execute(httpget);
// Examine the response status
Log.i(TAG, response.getStatusLine().toString());
// Get hold of the response entity
HttpEntity entity = response.getEntity();
// If the response does not enclose an entity, there is no need
// to worry about connection release
if (entity != null) {
InputStream instream = response.getEntity().getContent();
Header contentEncoding = response.getFirstHeader("Content-Encoding");
if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
instream = new GZIPInputStream(instream);
}
// A Simple JSON Response Read
//InputStream instream = entity.getContent();
result = convertStreamToString(instream);
Log.i(TAG, result);
// A Simple JSONObject Creation
//json = new JSONObject(result);
// Closing the input stream will trigger connection release
instream.close();
long end = System.currentTimeMillis();
long elapsed = (end - start);
Log.e(TAG, "web call took ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^" + elapsed);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
.
RESULTS:
Without GZIP: average of 5 runs = 2923ms
With GZIP: average of 5 runs = 3179ms
There are at least two major contributions in the timing:
client side: connection speed vs. decoding speed
server side: connection speed vs. encoding speed
The gzip encoding can be static or dynamic on the server side. For some content it would make sense to store query data in already compressed form. For some content it can't be done and the server may have the "compression engine" occupied.
The timings are likely to change between ADSL, WLAN or direct ethernet connections.