I have written a web-service in Java. This web-service is hosted in TOMCAT. I am returning a JSON string. The JSON string is as follows:
accountDetailsNodes = [{mobileNumber=01948330292, errorMessage=null, customerCode=59744000002, photo=a string of 35536 charaters , accountOpenDate=null, errorFlag=N, customerNumber=4, customerName=Md. Saifur Hossain , accountID=2, accountTypeId=13, accountTypeDescription=Savings Account, customerPointId=1, balance=100000037640.50, accountTile=Md. Saifur Hossain}]
The length of the JSON string is 32613. But the full response is not coming to android apps. I think there may be some limitation on sending response from Tomcat. How can I overcome this limitation of Tomcat?
Updated:
This is my code to generate JSON.
try {
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
JSONObject json = new JSONObject();
CashDepositDao dao = new CashDepositDao();
for (CashDepositModel bo : dao.getAccountDetals(accountNo,branchCode)) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("accountTile", bo.getAccountTitle());
map.put("accountOpenDate", bo.getAccountOpenDate());
map.put("mobileNumber", bo.getMobileNumber());
map.put("balance", bo.getBalance());
map.put("accountTypeId", bo.getAccountTypeID());
map.put("accountTypeDescription", bo.getAccountTypeDescription());
map.put("accountID", bo.getAccountID());
map.put("customerNumber", bo.getCustomerNumber());
map.put("customerCode", bo.getCustomerCode());
map.put("customerName", bo.getCustomerName());
map.put("customerPointId", bo.getCustomerPointID());
map.put("photo", bo.getPhoto());
map.put("errorMessage", bo.getErrorMessage());
map.put("errorFlag", bo.getErrorFlage());
list.add(map);
json.put("accountDetailsNodes", list);
}
System.out.println("accountDetailsNodes = " + list);
response.addHeader("Access-Control-Allow-Origin", "*");
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().print(json.toString());
response.getWriter().flush();
// System.out.println("Response Completed... ");
} catch (Exception ex) {
Logger.getLogger(SourecAccountDetailsSV.class.getName()).log(Level.SEVERE, null, ex);
}
Sending And Getting response from Mobile App:
I am sending and getting the response using the following code:
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
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"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(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();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
System.out.println(json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
I have printed the string received in this method . Surprisingly, the full string is not received in this method.
How can I overcome this limitation of tomcat ?
Tomcat can send arbitrary length strings, and even if there was a limit, it wouldn't be measured in kilobytes but in orders of magnitude more. There is no tomcat limitation that you need to overcome. If your browser receives the full string, so can any other app.
As you're using json.toString() anyways, you could explicitly set the Content-Length header and see if this makes a difference. Stop worrying about Tomcat and double check if your Android App has some problems parsing a json response of this size, or if any network component in between limits your response in some way.
Edit: It's not Tomcat's problem, it's on the Android side and your answer is in the comments to the question.
The first problem is in what's proposed as "duplicate" question: You must not compare String with == as you do. Add else System.out.print("unexpected"); to your first if/else block to illustrate.
The second problem is that we have no clue where you get is from. As it looks now, it could be overridden by parallel requests (it's probably a class member?) - or due to the wrong string comparison never be initialized at all (leading to your problem that you can't see any content at all on the Android side, despite tomcat sending it). Make it a local variable, as proposed by EJP in his/her comment.
I think there may be some limitation on sending response from Tomcat.
There isn't.
How can I overcome this limitation of Tomcat?
There is no such limitation.
I am sending and getting the response using the following code:
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
Here you are incorrectly comparing strings. You should use equals(), not ==.
// ...
}else if(method == "GET"){
Ditto.
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
Here you are using is which may not have been initialized at all. It appears to be a member variable, so it is probably still null, so at this point I would expect a NullPointerException. is should of course be a local variable in this method.
I have printed the string received in this method. Surprisingly, the full string is not received in this method.
What is surprising is that anything is received, if that's what you're claiming. I would have expected an NPE.
I am having serious trouble on fetching my data from the server.
My url is this:
server_url = http://serverurl/_all
If I call that from my browser, I can see the data being printed. So I guess it has to do with how I make the request. I have used that part of code before, when making a post request for example in a php file. But now my server is setup differently and I know that the server works fine because I can fetch my data in the browser and in an IOS app.
I have tried this:
try {
HttpClient httpclient = new DefaultHttpClient();
#SuppressWarnings("deprecation")
//HttpPost httppost = new HttpPost(URLEncoder.encode(server_url));
HttpPost httppost = new HttpPost(server_url);
//httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
System.out.println("Result:" + result);
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
and I get this:
Result : Error 404 not found
Then, searching on the SO I have tried the following:
Remove the http://
change the HttpPost line into this
HttpPost httppost = new HttpPost(URLEncoder.encode(server_url));
In this case I get this error:
12-01 21:41:11.772: E/log_tag(28340): Error in http connection java.lang.IllegalStateException: Target host must not be null, or set in parameters. scheme=null, host=null, path=http://ec2-54-194-95-194.eu-west-1.compute.amazonaws.com/backend2/index.php/skicenter/_all
12-01 21:41:11.772: E/log_tag(28340): Error converting result java.lang.NullPointerException: lock == null
12-01 21:41:11.772: E/log_tag(28340): Error parsing data org.json.JSONException: End of input at character 0 of
There should be something wrong with the _ character os something else that I am missing.
Can you help me on that?
Are you sure, you are using the correct HTTP verb for the request? Maybe it's a GET request and you are trying with POST.
I'm working on creating an android app that will pull down user data from a MySQL database stored on a web server. I've read a few tutorials on HTTP Post that allows me to connect to the database, which I got working. However, I am unable to process the data that gets sent from the php.
The error I receive is: org.apache.http.MalformedChunkCodingException: Chunked stream ended unexpectedly.
This is the code I have written:
String name = username.getText().toString(); //username is a TextView field
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("user",name));
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(location);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}
catch(Exception e)
{
Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG).show();
Log.e("log_tag", "Error in http connection"+e.toString());
}
//Convert response to string
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.i("log_tag", result);
}
catch(Exception e)
{
Toast.makeText(getBaseContext(),e.toString() ,Toast.LENGTH_LONG).show();
Log.e("log_tag", e.toString());
}
The error seems to appear in the convert response to string section. I've looked up several issues regarding similar errors to the one I received but what I read didn't seem to help much or I just don't know enough about http client coding...probably the latter. Any help would be greatly appreciated, thanks!
Here is the PHP as well:
<?php
$con = mysqli_connect("/**connection*/");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: ".mysqli_connect_error();
}
$result = mysqli_query($con, "SELECT * FROM userNames WHERE user='".$_POST['name']."')";
if ($result == NULL)
{
die();
}
else
{
//TODO:get row to java
$rows = array();
while($r = mysql_fetch_assoc($result))
{
$rows[] = $r;
}
print json_encode($rows);
mysql_close();
}
mysqli_close($con);
}
?>
The end goal of this is to convert the JSON response from the database into separate variables, the buffered reader stuff is just a middle step before the JSON conversion. Again , I just followed a tutorial so if anyone knows a different way of going about this I'm open to suggestions.
I am trying to connect to mysql db using PHP web service. This is the way I am forming the request
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://localhost/android_connect/getbrowsedata.php");
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){}
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF8"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
System.out.println("result::"+sb.toString());
}catch(Exception e){
// Log.e("log_tag", "Error converting result "+e.toString());
}
When i run this from a normal java application, I am getting the appropriate result as JSON, which i am able to parse.I am also able to launch it from my browser. When i use this same code in android project,response returns a html with 403 you dont have permission to access .php file on this server (instead of local host i am using my ip address). I have included the user permission in android manifest file. I have also modified the httpd.conf in my WAMP server, changing all the denied to granted as found in the other posts.Is this an issue with any other configuration of the WAMP server.
Any one faced this issue? Any suggestion would be of great help
actually i have a correct code that makes a http petition to twitter and get's some tweets from a user codified with JSON (it gets a file .json)
It's ok, it works fine, but it takes a loooooooooooooot of time making the request, debugging i can see that the problem is on the line HttpResponse response = httpclient.execute(httpget);
On that line it gets stuck a lot of seconds when the number of tweets is more than 3 or 4 tweets. If you are requesting 20 tweets it takes 10-15 seconds to get them.
It is a problem of the java/android http get method i am using, because if i make the request by url on firefox, then, it is super fast.
How to make this http get request by a faster way?
This is my actual and slow code:
public List<String> RetrieveTweets(String name, int num) //da todas las posiciones dado un email
{
// https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_name=charliesheen&count=2
List<String> tweetsList= new ArrayList<String>();
String result = "";
//http get
InputStream is=null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_name=" + name +"&count="+ num);
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//parse json data
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++)
{
JSONObject json_data = jArray.getJSONObject(i);
tweetsList.add(json_data.getString("text")); //text es el nombre del campo del tweet
}
}
catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
return tweetsList;
}
Are you required to use https version to get the statuses? Https will be slower than http because of two things:
Initial connect requires a handshake negotiation for deciding cipter algorithm + session key
Once the handshake is established, each way of communication requires encryption/decryption of the message.
If you are required to us SSL, you could try instantiating the HttpClient once and not instantiating every time in the method. Hopefully, it will keep the session alive and thus avoiding the handshake which can be costly if you initiate it every time.