I have following situation:
Sending http post (post data contains json string) request to my remote server.
Getting http post response from my server in json: {"result":true}
Disconnecting all internet connections in my tablet.
Repeating post request described in step 1.
Getting the same cached "response" - {"result":true} which I didn't expected to get... I don't want that my http client would cache any data. I expect to get null or something like this.
How to prevent http client caching data?
My service handler looks like this:
public String makeServiceCall(String url, int method,
List<NameValuePair> params, String requestAction) {
try {
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) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
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();
// Toast.makeText(Globals.getContext(), "check your connection", Toast.LENGTH_SHORT).show();
}
return response;
}
I just noticed that response is a member variable. Why do you need a member variable to return this result. You're probably returning the same result on the 2nd try. Re-throw the exception that you catch instead and let the caller handle it.
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.
in my program I have http get which gets data from PHP script. This code is present in async task. This works fine.
But now I want to do HTTP post, where I, the android client, post data to the PHP script, it quires the DB and returns the result of that.
But this is what is confusing me.
Can I get a response from a HTTP post? Or do i need a combination of post and get?
This question I don't expect an answer but if anyone can advise on this would be great. I have one async task which does the HTTP get. Now i want to use the same async to do either HTTP get or post but not both. Is this possible?
Thank you
Here John. A small snippet. My problem is the HTTP StatusLine httpStatus and http entity it does not recognise any of the responses because they are in if statements so the compiler thinks they will not be defined.
if(params[1] == "GETRESULT")
{
HttpGet get = new HttpGet(params[0]);
HttpResponse r = client.execute(get);
}
else //we are posting
{
HttpPost post = new HttpPost(params[0]);
HttpResponse r = client.execute(post);
}
StatusLine httpStatus = r.getStatusLine();
HttpEntity e = r.getEntity();
You can get a response with post
You can use the same async method as long as you have some logic that changes the request type to POST or GET depending on what you want to do.
some info on HttpPost
// 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", "AndDev is Cool!"));
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
}
For your code to work you need to declare the Response outside of your if/blocks:
HttpResponse r = null;
if(params[1] == "GETRESULT")
{
HttpGet get = new HttpGet(params[0]);
r = client.execute(get);
}
else //we are posting
{
HttpPost post = new HttpPost(params[0]);
r = client.execute(post);
}
StatusLine httpStatus = r.getStatusLine();
HttpEntity e = r.getEntity();
Move your HttpResponse r above the if/else statement as HttpResponse someVariable; then you can access it inside your else, and read the result afterwards. You also have to check for NullPointerException, with a try / catch block.
For example like this :
HttpResponse r;
if(params[1] == "GETRESULT")
{
HttpGet get = new HttpGet(params[0]);
r = client.execute(get);
}
else //we are posting
{
HttpPost post = new HttpPost(params[0]);
r = client.execute(post);
}
StatusLine httpStatus = r.getStatusLine();
try {
HttpEntity e = r.getEntity();
} catch (NullPointerException e) {
//Error handling
}
Hi I want to send a json object to a web service , I have tried almost everything without success. When the webservice recives the data it returns "eureka" , so I want to be able to see the response too.
public void sendData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://pruebaproyectosmi.azurewebsites.net/home/Insert?data=");
try {
httppost.setEntity(new UrlEncodedFormEntity(json));
// 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
}
}
private void SendBookingData(final String SendCustomerId,final String SendCustomerName, final String BookingDate,
final String BookingTime, final String SendNetAmount,final String SendTotalAmount, final String SendTotalQuantity,
final String SendDeliveryDate, final String GetBranchId,final String Senduserid,final String Sendratelistid) {
HttpClient client = new DefaultHttpClient();
JSONObject json = new JSONObject();
try {
String SendBookingURL= "your url";
HttpPost post = new HttpPost(SendBookingURL);
HttpResponse response;
json.put("GetcustomerName", SendCustomerName);
json.put("GetBookingDate",BookingDate);
json.put("GetTotalCost", SendTotalAmount);
json.put("GetNetAmount", SendNetAmount);
json.put("GetTotalQuantity",SendTotalQuantity );
json.put("GetCustomerId", SendCustomerId);
json.put("GetDeliveryDate", SendDeliveryDate);
json.put("GetBookingtime", BookingTime);
json.put("GetBranchId", GetBranchId);
json.put("GetUserId", Senduserid);
json.put("GetRateListId", Sendratelistid);
StringEntity se = new StringEntity( json.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
try {
response = client.execute(post);
HttpEntity entity = response.getEntity();
if(entity != null) {
ResponseSummaryTable = EntityUtils.toString(entity);
System.out.println("body" + ResponseSummaryTable);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
catch(Exception e){
e.printStackTrace();
}
}
Send string entity instead
CODE:
HttpClient client = new DefaultHttpClient();
HttpUriRequest request;
request = new HttpPost(<-URL->);
StringEntity entity = new StringEntity(<-Your JSON string->);
((HttpPost) request).setEntity(entity);
((HttpPost) request).setHeader("Content-Type",
"application/json");
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
This code will send json as string entity to server and receives HttpEntity as response
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.
I've never really used http requests in Java, I'm trying to make a request that would basically recreate this http://supersecretserver.net:8080/http://whateverwebsite.com
This server takes whatever website and returns only the text of the page in the body of the response.
The code is as follows:
public String getText(String webPage) throws ParseException, IOException{
HttpResponse response = null;
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI("http://supersecretserver.net:8080/" + "http://www.androidhive.info/2012/01/android-text-to-speech-tutorial/"));
response = client.execute(request);
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String responseBody = "No text found on webpage.";
int responseCode = response.getStatusLine().getStatusCode();
switch(responseCode) {
case 200:
HttpEntity entity = response.getEntity();
if(entity != null) {
responseBody = EntityUtils.toString(entity);
}
}
System.out.println("Returning Response..");
System.out.println(responseBody);
return responseBody;
}
It seems to get stuck on
response = client.execute(request);
I'm not sure what the problems is, any insight would be helpful.
Seems likely that your HttpClient is not timing out, you can set a timeout value by following this example (from http://www.jayway.com/2009/03/17/configuring-timeout-with-apache-httpclient-40/)
You just to have to consider a timeout value that makes sense for you.
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpParams params = httpClient.getParams();
HttpConnectionParams.setConnectionTimeout(httpParams, connectionTimeoutMillis);
HttpConnectionParams.setSoTimeout(httpParams, socketTimeoutMillis);
Also as your HttpClient is not connecting (since it's getting stuck) you should also take into consideration why is that happening (maybe you need to configure a proxy?)