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.
Related
I have a problem by my json post request. I created a JsonObject and want to post it to the server but the body of the post request which is received by the server contains nothing and I don't know why...
public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
String contentType = "application/json";
public ServiceHandler() {
}
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
public String makeServiceCall(String url, int method, List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
JSONObject jsonObj = new JSONObject();
jsonObj.put("name", "your name");
jsonObj.put("message", "your message");
StringEntity entity = new StringEntity(jsonObj.toString(), HTTP.UTF_8);
httpPost.setEntity(entity);
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return response;
}
Provide "Content-Type" header to request with value "application/json". It seems server can't found proper message body mapper.
I am trying to post JSON data to my API. But after execution I'm getting the following result:
{"name":"Corporate","addr":"Unknown","area":"Unknown","cityId":10,"phone":"--","fax":"--","wooqStoreId":1}]
Response 2 >>{"message":"Blank String","result":"Error","resultCode":"RESULT_CODE_002"}
true
The first 2 lines show my JSON string and
response 2 is the message I'm getting. It should be a successful message as I'm getting status code 200.
public static boolean pushtoAPI(String url, String jsonObject) {
DefaultHttpClient client = new DefaultHttpClient();
HttpPost request = null;
HttpResponse response = null;
String postUrl = getHostUrl() + url;
try {
request = new HttpPost(postUrl);
StringEntity postingString = new StringEntity(jsonObject.toString());
postingString.setContentType("application/json;charset=UTF-8");
postingString.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json;charset=UTF-8"));
request.setEntity(postingString);
request.setHeader("Content-type", "application/json");
String custom_cookie = ConstantUtil.authCookie(ConstantUtil.getLoginJsessionId());
request.setHeader("Cookie", custom_cookie);
response = client.execute(request);
System.out.println("Response 2 >>" + EntityUtils.toString(response.getEntity()));
if (response.getStatusLine().getStatusCode() == 200) {
System.out.println("true");
return true;
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
} finally {
request.abort();
}
return false;
}
It looks like its a server side code issue.
Can you show where you are creating this string?
"message":"Blank
String","result":"Error","resultCode":"RESULT_CODE_002"
I have an app android that in an AsyncTask make 2 get request to a servlet.
I want to retrieve a String that contains a simple response.
This is my AsyncTask:
protected String doInBackground(Void... params) {
return uploadFile();
}
#SuppressWarnings("deprecation")
private String uploadFile() {
String responseString = null;
String responseStr = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Config.FILE_UPLOAD_URL);
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new ProgressListener() {
#Override
public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));
}
});
File sourceFile = new File(filePath);
// Adding file data to http body
entity.addPart("image", new FileBody(sourceFile));
totalSize = entity.getContentLength();
httppost.setEntity(entity);
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
// Server response
responseString = EntityUtils.toString(r_entity);
try {
HttpClient client = new DefaultHttpClient();
URI getURL = new URI("http://192.168.1.101:8080/MusaServlet?collection="+collection+"&name="+filename);
Log.i("QUERY",getURL.getQuery());
HttpGet get = new HttpGet(getURL);
HttpResponse responseGet = client.execute(get);
HttpEntity resEntityGet = responseGet.getEntity();
if (resEntityGet != null) {
Log.i("GET RESPONSE",EntityUtils.toString(resEntityGet));
}
responseStr = EntityUtils.toString(responseGet.getEntity());
} catch (Exception e) {
e.printStackTrace();
}
} else {
responseString = "Error occurred! Http Status Code: "
+ statusCode;
}
} catch (ClientProtocolException e) {
responseString = e.toString();
} catch (IOException e) {
responseString = e.toString();
}
return responseStr;
}
Instead the servlet code is:
PrintWriter out = response.getWriter();
out.println("HELLO STUPID APP!");
However the dialog showed by app is empty! No words!
What's the problem guys?
Thank's
At first check your GET request status code as
responseGet.getStatusLine().getStatusCode();
If is giving number 200 then GET is successfull.
Now if is 200 then you will get the response what you have sent by following code
HttpEntity resEntityGet = responseGet.getEntity();
and then
String result;
if(resEntityGet !=null ){
result= EntityUtils.toString(resEntityGet);
}
Now the most important thing is once you perform responseGet.getEntity() the data of GET response will be passed to the variable.. you assign.. and later on calling responseGet.getEntity() will always return empty...
That may be the reason you are getting empty response in your dialog
EDIT:
Ok I have modified my code and playing with logcat I'm sure that the responseCode is not 200.
What is the problem now? -.-"
I have a post request working successfully in Postman, but when I make the same request from my Android app, I get "Internal Server Error". Do you see any difference between these two requests?
Postman
Android App
class MakeRequest extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("https://sample.com/test");
httppost.setHeader("Content-type", "application/json");
httppost.setHeader("Authorization", getB64Auth("username", "password"));
try {
JSONObject identity = new JSONObject();
identity.put("type", "number");
identity.put("endpoint", "12345");
JSONObject options = new JSONObject();
options.put("num", "12345");
JSONObject body = new JSONObject();
body.put("identity", identity);
body.put("method", "test");
body.put("options", options);
StringEntity se = new StringEntity(body.toString());
httppost.setEntity(se);
} catch (IOException e) {
Log.d("IOException", e.toString());
} catch (JSONException e) {
Log.d("JSONException", e.toString());
}
try {
ResponseHandler handler = new BasicResponseHandler();
HttpResponse response = httpclient.execute(httppost);
Log.d("HttpResponse", handler.handleResponse(response).toString());
} catch (ClientProtocolException e) {
Log.d("ClientProtocolException", e.toString());
} catch (IOException e) {
Log.d("IOException", e.toString());
}
return null;
}
private String getB64Auth (String key, String secret) {
String source=key+":"+secret;
String ret="Basic "+Base64.encodeToString(source.getBytes(),Base64.URL_SAFE|Base64.NO_WRAP);
return ret;
}
}
Other thoughts/hints:
Authentication is working properly in the java code. I tried with wrong username & password, and I got "Invalid Authorization"
The JSON string is exactly the same as the one in postman. I printed body.toString(), copied and pasted into Postman, and the request worked fine in Postman.
you should change httppost.setHeader("Content-type", "application/json"); to httppost.setHeader("Content-type", "application/form-data"); or httppost.setHeader("Content-type", "application/x-www-form-urlencoded");
this should solve your issue.
I have noticed that my http requests tend to take alot of time compared apps communicating with same server. It makes my app feel sluggish and I was wondering if there is a better way of making these requests and updating the UI.
At the moment I use this method to make post requests
public String postRequest(List<NameValuePair> nameValuePairs, String method_name) {
String result = "";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.mysite.com/api/"+method_name);
httppost.setHeader("Accept", "application/json");
httppost.setHeader("Authorization", "Basic somestuff");
try {
// Add your data
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
BufferedReader rd = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
result = rd.readLine();
return result;
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return null;
}
And in my UI thread (i.e my Fragment classes) I use this in an Async Task like this
class MakeRequest extends AsyncTask<Integer, Integer, String> {
protected String doInBackground(Integer... counter) {
String result = "";
String method_name = "";
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", value));
nameValuePairs.add(new BasicNameValuePair("name", name));
method_name = "petition/setPetition";
result = fixr.postRequest(nameValuePairs, method_name);
JSONObject jsonFile = new JSONObject(result);
if(!jsonFile.has("error")){
//Parse JSON using GSON
return "success";
}else{
return jsonFile.getString("error");
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String jsonResult) {
try {
if(jsonResult != null){
//update UI
}else{
//Error message
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
I'd like to optimize this so users can have a really smooth experience on my application. I'm open to using third party http libraries or is there also an argument against using AysncTasks and maybe the runOnUiThread() instead.
Volley Library is better, http, https etc.
https://developers.google.com/live/shows/474338138
very mini sample here:https://github.com/ogrebgr/android_volley_examples/blob/master/src/com/github/volley_examples/Act_SimpleRequest.java
Try Volley mate! I changed from AsyncTasks to Volley library and i am pretty pleased from the overall experience!
Volley Library