HTTP get and post in android - java

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
}

Related

HTTP response being cached in Android client

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.

Sending HttpPost to Server; No Response needed

I want to do an HttpPost on Android to update a single row in a database. I do not need any response, verification, etc. So I am trying to simplify my code because I think what I have may be redundant.
This is what I have:
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url_select);
httpPost.setEntity(new UrlEncodedFormEntity(param));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
httpEntity.getContent();
} catch (Exception e) {
e.printStackTrace();
}
Do I need all of this? It seems I can just have
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url_select);
httpPost.setEntity(new UrlEncodedFormEntity(param));
httpClient.execute(httpPost);
} catch (Exception e) {
e.printStackTrace();
}
Is this correct?
I won't eat when I'm not hungry :)
Yes. The second part is good enough. No need to get the response object there if you don't really need it. That is fine.
You may also want to check AQuery library which simplifies Http connections:
https://code.google.com/p/android-query/

Android sending data to restful webservices

I am trying to send data from android smartphone to a restful webservice made in java using jersey library.
I saw the following answer on how to do it:
public void postData() {
// 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", "Hi"));
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
}
}
Although this seems about right i have a doubt in the nameValuePairs variable.
Particularly in this part:
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
If i have a webservice that has the following signature:
#POST
#Path("/post/location")
#Consumes(MediaType.APPLICATION_JSON)
public Response createLocation(Loc location)
what would be the "id" part in the nameValuePairs variable, it would be location or Loc?.
try this
//
String url = 'url_to_you_server_api.dev/postservice'
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost(url);
JSONObject params = new JSONObject();
params.put("id","id");
params.put("hi","hi");
StringEntity jsonEntity = new StringEntity( params.toString() );
HttpPost request = new HttpPost(url);
request.addHeader("Content-Type","application/json");
request.setEntity(jsonEntity);
response = client.execute(request);
if you service receive a entity it might be a json or something not just key-value params that correspond to form-data.

Sending a http post request is not working

I'm making an android app and run it on the simulator. All post parameters on the server are empty when I send a http post request. This is code in the android app:
public void run() {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(page);
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);
InputStreamReader inreader = new InputStreamReader(response.getEntity().getContent());
BufferedReader reader = new BufferedReader(inreader);
String line = "";
while((line = reader.readLine()) != null){
System.out.println(line);
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
}
And this is the code on the server:
<?php
print_r($_POST);
?>
It returns an empty php array when I run it on the simulator.
Put www in the request url and it was solved. There was a htaccess file that corrected all url`s without www.
Volley Library(sim-official from google) is better, http, https etc.
https://developers.google.com/live/shows/474338138
There's a very mini sample here:https://github.com/ogrebgr/android_volley_examples/blob/master/src/com/github/volley_examples/Act_SimpleRequest.java
There's the same question like you here: Optimizing HTTP requests in android

Following redirects in HTTPResponse Android

I need to follow redirects given to me by HTTPost. When I make an HTTPost, and try to read the response, I get the redirect's page html. How can I fix this? Code:
public void parseDoc() {
final HttpParams params = new BasicHttpParams();
HttpClientParams.setRedirecting(params, true);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"https://secure.groupfusion.net/processlogin.php");
String HTML = "";
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add(new BasicNameValuePair("referral_page",
"/modules/gradebook/ui/gradebook.phtml?type=student_view"));
nameValuePairs.add(new BasicNameValuePair("currDomain",
"beardenhs.knoxschools.org"));
nameValuePairs.add(new BasicNameValuePair("username", username
.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("password", password
.getText().toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
String g = httppost.getURI().toString();
HttpResponse response = httpclient.execute(httppost);
HTML = EntityUtils.toString(response.getEntity());
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String ResponseBody = httpclient.execute(httppost, responseHandler);
sting.setText(HTML);
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
}
When a server sends a redirect, it is actually sending a 3xx response code (usually 301 or 302) that indicates the redirect, and a Location header that tells you the new location.
So, in your case, you can get the Location header from the HttpResponse object and use that to send another request to retrieve the actual content after you've logged in. For example:
String newUrl = response.getFirstHeader("Location").getValue();
So long as you reuse the same HttpClient object for both requests, it should use any cookies set by the login request in your subsequent request(s).
Try using the HttpGet method
GetMethods will follow redirect requests from the http server by default. This behavour can be disabled by calling setFollowRedirects(false).
For more info refer this
Hope it helps,
Cheers

Categories

Resources