Strange Log.i() behavior Android Studio - java

I'm seeing something really weird. Im making a http post request
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = null;
try {
response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
String strResponse = null;
if (entity != null) {
strResponse = EntityUtils.toString(entity);
Log.i("SetupAutoCardResponse",String.valueOf(strResponse));
Log.i("otherTest","test");
Log.i("otherTest",strResponse);
return true;
}
} catch (IOException e) {
e.printStackTrace();
return false;
}
The only output I see in the log is otherTest : Test.
The logs with strResponse dont show up at all, and by that I mean, nothing shows. It does not look like this SetupAutoCardResponse : null or otherTest: null. Absolutly nothing shows up. But I know I am getting a response. The expression returns true

In Log, if the Messsage is Null or Blank or Empty, Log will not write down.
Example: Log.i(TAG, MSG);
To make sure it works, we can add some text to MSG
Log.i(TAG, String.format("%s %s", "MSG>" , MSG));

Related

Correct JSON object can't be read

I have an object that I want to parse to a JSON string. When I want to read it out, it says it can't parse it back to an object (i think). This is the error:
As you can see at the top of the console, the JSON object is set properly with the right brackets. What I understand from the JSONSyntaxException is that it doesn't recognize it as a JSON object. I've copied this code from my school and in a different project it does work. I don't know why it doesn't work in my Maven project.
EDIT
This is the code for RESTcontroller.java.
public PlayerDTO addPlayer(String name, String password) {
PlayerDTO playerRequest = new PlayerDTO(NOTDEFINED, name, password);
String queryPost = "/player";
PlayerResponse response = executeQueryPost(playerRequest, queryPost);
return response.getPlayers().get(0);
}
private PlayerResponse executeQueryPost(PlayerDTO playerRequest, String queryPost) {
final String query = url + queryPost;
log.info("[Query POST] : " + query);
HttpPost httpPost = new HttpPost(query);
httpPost.addHeader("content-type", "application/json");
StringEntity params;
try{
params = new StringEntity(gson.toJson(playerRequest));
System.out.println(gson.toJson(playerRequest));
httpPost.setEntity(params);
} catch (UnsupportedEncodingException e) {
Logger.getLogger(SeaBattleGame.class.getName()).log(Level.SEVERE, null, e);
}
return executeHttpUriRequest(httpPost);
}
private PlayerResponse executeHttpUriRequest(HttpUriRequest httpUriRequest) {
// Execute the HttpUriRequest
try (CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = httpClient.execute(httpUriRequest)) {
log.info("[Status Line] : " + response.getStatusLine());
HttpEntity entity = response.getEntity();
final String entityString = EntityUtils.toString(entity);
log.info("[Entity] : " + entityString);
return gson.fromJson(entityString, PlayerResponse.class);
} catch (IOException e) {
log.info("IOException : " + e.toString());
PlayerResponse playerResponse = new PlayerResponse();
playerResponse.setSuccess(false);
return playerResponse;
} catch (JsonSyntaxException e) {
log.info("JsonSyntaxException : " + e.toString());
PlayerResponse playerResponse = new PlayerResponse();
playerResponse.setSuccess(false);
return playerResponse;
}
}
Keep in mind that the code gave me this code and it does work in their project!
It would seem to me that your request is failing with this error: Problem accessing /seabattle/player Reason: request failed. It's not very discriptive, but it's something.
Your code is then failing with a NullPointerException, I'm guessing response.getPlayers() is returning a null.
You should really try and send a similar JSON to this endpoint from a curl command or via Postman app and see if it works. Or if you can, see the webserver logs to find out what the actual problem is.
EDIT: You should really also check the response status before trying to parse it. This will get rid of the NullPointerException and will make your code better in general.
A couple of things to fix the issue:
In the method executeQueryPost you have to add the following headers for the request:
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
And the code should look like the following:
private PlayerResponse executeQueryPost(PlayerDTO playerRequest, String queryPost) {
final String query = url + queryPost;
log.info("[Query POST] : " + query);
HttpPost httpPost = new HttpPost(query);
httpPost.addHeader("content-type", "application/json");
StringEntity params;
try{
params = new StringEntity(gson.toJson(playerRequest));
System.out.println(gson.toJson(playerRequest));
httpPost.setEntity(params);
// Need to add the following headers
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
} catch (UnsupportedEncodingException e) {
Logger.getLogger(SeaBattleGame.class.getName()).log(Level.SEVERE, null, e);
}
return executeHttpUriRequest(httpPost);
}
In case the the code continue failing is because it can't create the new player. You must handle the exception in addPlayer() method. Before the return check if the object returned by executeQueryPost is not null.
Update:
The code may be failing just because the service in: http://localhost:8090 isn't running that's why it getting 500 as response.

Issue in making rest call which actually works fine locally but not in production server

In my java code I'm calling third pary apis. In my local workspace it works pretty well and I'm getting proper response. But When I deploy the war in production, I see in logs, I'm calling the apis and didn't get any response. It sound wierd to me and got stuck with it. Please find the snippet and I'm completely calling api in plain old Java.
private void updateRetailerOrderStatus(String trackingId) {
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
System.out.println("Inside updateRetailerOrderStatus By Android");
Order order = orderDao.getOrdersByTrackingId(trackingId);
HttpPost httpPost = new HttpPost("http://SomeDomine/v1/order/delivered");
httpPost.addHeader("Some Key", "Some Value");
httpPost.addHeader("Content-Type", "application/json");
JSONObject json = new JSONObject();
json.put("awb_no", order.getTrackingId());
json.put("order_no", order.getOrderId());
json.put("delivered_date", order.getDeliveredDate().toString());
json.put("status", "delivered");
json.put("carrier", "Delivery");
StringEntity entity = new StringEntity(json.toString());
httpPost.setEntity(entity);
System.out.println(json.toString());
HttpResponse response = httpclient.execute(httpPost);
BufferedReader buffReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer respBuffer = new StringBuffer();
String line = "";
while ((line = buffReader.readLine()) != null) {
System.out.println(line);
respBuffer.append(line);
}
System.out.println("API Response: "+ respBuffer.toString());
} catch(Exception ex) {
System.out.println("Error in fetchToken :"+ ex.getMessage());
System.out.println(ex.getStackTrace());
} finally {
try {
httpclient.close();
} catch(Exception ex) {
System.out.println(ex.getMessage());
}
}
}
My Questions are:
1) Is there a possibility of happening this? If So, Why?
2) Should I call this in saparate thread? But, I didn't see any suggestions of doing it in most of the examples.

HTTPResponse's string from Play is empty

I am using Play and Faye on my Server. Play is used for API calls, while Faye is used for communication with the clients.
So, I have this method in the server:
public static Result broadcast(String channel, String message)
{
try
{
FayeClient faye = new FayeClient("localhost");
int code = faye.send(channel, message);
// print the code (prints 200).
return ok("Hello"); <------------ This is what we care about.
}
catch(Exception e)
{
return ok("false");
}
}
this is the code on the client, which is an android phone.
(it's the HTTP post method, which sends something to the server and gets a response back
The problem is, I can't print the message of the response.
public static String post(String url, List<BasicNameValuePair> params)
{
HttpClient httpclient = new DefaultHttpClient();
String result = "";
// Prepare a request object
HttpPost httpPost;
httpPost = new HttpPost(url);
httpPost.setHeader("Content-type", "application/json");
httpPost.setHeader("Accept", "application/json");
JSONObject obj = new JSONObject();
try
{
for (NameValuePair pair : params)
obj.put(pair.getName(), pair.getValue());
}
catch (JSONException e)
{
return e.getMessage();
}
// Add your data
try
{
httpPost.setEntity(new StringEntity(obj.toString(), "UTF-8"));
}
catch (UnsupportedEncodingException e)
{
return e.getMessage();
}
HttpResponse httpResponse;
try
{
httpResponse = httpclient.execute(httpPost);
// Get hold of the response entity
HttpEntity entity = httpResponse.getEntity();
String str = EntityUtils.toString(entity);
Log.e("RestClient", "result = \"" + str + "\""); // hello should be printed here??
}
catch(Exception e)
{
// ...
}
The problem is that in logcat, what is printed is [result = ""]. Am I doing something wrong?
Thank you.
Use a tool such as Fiddler and see what the HTTP response contains.

Android Unable to Retrieve JSON response [SC_406]

I have the code which basically retrieving a list of search result based on given keyword from TMDB (API ver.3, new API).
public String getPersonSearchResult(String keywords){
String query = URLEncoder.encode(keywords);
String TMDB_API_URL = "http://api.themoviedb.org/3/search/person?";
String TMDB_LIMIT_LIST = "&page=1";
String TMDB_QUERY = "&query=" + query;
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try
{
// ATTEMPT HTTP REQUEST
String fullUrl = TMDB_API_URL + TMDB_API_KEY + TMDB_QUERY + TMDB_LIMIT_LIST;
Log.w(APP_TAG, "TRYING [" + fullUrl + "]");
response = httpclient.execute(new HttpGet(fullUrl));
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK)
{
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
}else{
// FAILED REQUEST - CLOSE THE CONNECTION
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
}catch(Exception e){
Log.w(APP_TAG, e.getLocalizedMessage());
Log.w(APP_TAG, "FAILED TO RETRIEVE JSON DATA");
}
return responseString;
}
The problem is that i always get 406 Status Code (Not Acceptable). When i tried to run the URL myself
http://api.themoviedb.org/3/search/person?api_key=<MY_API_KEY_HERE>&query=jennifer&page=1
It displays the JSON result correctly.
I am not sure why is this happening. Similar function is used to retrieve JSON value from other source and and it works perfectly.
this is their API docs regarding search: http://docs.themoviedb.apiary.io/#search
Can anyone points me to the right direction? Any help is appreciated.
I figure it out, by adding this:
HttpGet getObj = new HttpGet(fullUrl);
getObj.addHeader("Accept", "application/json");
Perhaps this is API specific requirement. Not sure though...
One way to do it
Try using builder.scheme
URIBuilder builder = new URIBuilder();
builder.setScheme("http").setHost("api.themoviedb.org").setPath("/3/search/person")
.setParameter("api_key", YOURAPIKEY)
.setParameter("page", 1)
.setParameter("query", query)
URI uri = builder.build();
HttpGet httpget = new HttpGet(uri);
.....
response = httpclient.execute(new HttpGet(httpget ));
I think its nothing to do with your code.. your code is perfect. The only problem might be with the API request method. Maybe they require some specific headers to be requested for in the request. Give a try with requesting headers like "("Accept", "application/json")" It might work..
try this
String ret = null; try {
response = httpClient.execute(httpGet);
} catch (Exception e) {
e.printStackTrace();
}
try {
ret = EntityUtils.toString(response.getEntity());
} catch (IOException e) {
Log.e("HttpRequest", "" + e.getMessage());
} catch (Exception e) {
e.printStackTrace();
}
return ret;

XML Parsing using Java not getting any Response

am trying to get the XML file from a URL but am getting no Response and the code stops later because the String xml is null, can you tell me whats the problem ?
public String getXmlFromUrl(String url) {
String xml = null;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
// I printed the response here but I got nothing !
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
return xml;
} catch (Exception e) {
e.printStackTrace();
}
Please be specific in you answers I appreciate your help
Why you are using HTTPPost?? You are not sending any data Even. Try with HttpGet.
Try This :
public String getXmlFromUrl(String url) throws Exception {
return new AsyncTask<String, Void, String>() {
#Override
protected String doInBackground(String... params) {
String xml = null;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpPost = new HttpGet(params[0]);
HttpResponse httpResponse = httpClient.execute(httpPost);
// I printed the response here but I got nothing !
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
Log.i("DEMO", xml);
} catch (Exception e) {
e.printStackTrace();
}
return xml;
}
}.execute(url).get();
}
Try to start your code from separate thread e.g.
new Thread(new Runnable()
{
#Override
public void run()
{
// TODO your code here
}
}).start();
try this:
try {
items = new ArrayList<String>();
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(new InputStreamReader(
getUrlData(" url")));
while (xpp.getEventType() != XmlPullParser.END_DOCUMENT) {
Log.i(TAG, "doc started");
if (xpp.getEventType() == XmlPullParser.START_TAG) {
if (xpp.getName().equals("entry")) {
items.add(xpp.getAttributeValue(0));
}
}
xpp.next();
}
} catch (Throwable t) {
Toast.makeText(this, "Request failed: " + t.toString(),
Toast.LENGTH_LONG).show();
}
for geturldata()
public InputStream getUrlData(String url) throws URISyntaxException,
ClientProtocolException, IOException {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet method = new HttpGet(new URI(url));
HttpResponse res = client.execute(method);
return res.getEntity().getContent();
}
You should understand Exceptions. The reason xml is null is because 'something' went wrong. This threw an Exception, probably with a good description of what went wrong. When this happens, the Exception is thrown 'up' until someone handles it.
Every subclass of Exception has a different 'flavor' and is thrown in specific cases. This enables you to 'react' on errors. For instance, you could tell the user what went wrong, or log something for debugging sake.
In your case, you 'catch' all exceptions in a single place, when an exception occurs, the code after catch (Exception e) is executed. You do nothing here but printing out some stuff (this will appear orange in your LogCat). Then you continue as if nothing happened. But xml will be null, which is bad for your program, and you apparently didn't notice the LogCat entry because your program crashes at a later point.
This time, Eldhose M Babu solved your problem. Next time, when something else goes wrong (and a lot can go wrong in htttp requests), your program will show the same behavior. Try and read up on exceptions and be careful when you handle them too silently.

Categories

Resources