Following redirects in HTTPResponse Android - java

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

Related

PHP Post Android Post

I want to make a post from my android application and insert into my database. My first approach was to send a post from my application and just show the value but it did not work.
My code from the application is
public void postData() {
HttpClient Client = new DefaultHttpClient();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("regid", "sID"));
nameValuePairs.add(new BasicNameValuePair("etc", "sETC"));
try {
String SetServerString = "";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://your-url.com/script.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
ResponseHandler<String> responseHandler = new BasicResponseHandler();
SetServerString = httpclient.execute(httppost, responseHandler);
} catch(Exception ex) {
// failed
}
}
The php code is
<?php
include 'db.inc.php';
$device_token = urldecode($_POST['regid']);
echo $device_token;
?>
Replace your lines
ResponseHandler<String> responseHandler = new BasicResponseHandler();
SetServerString = httpclient.execute(httppost, responseHandler);
By
HttpResponse response = httpclient.execute(httppost);
You can check response in android side using
String responseStr = EntityUtils.toString(response.getEntity());
System.out.println(responseStr);
Use following PHP code to get values.
<?php
$value1 = $_POST["regid"];
$value2 = $_POST["etc"];
echo $value1;
?>

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.

Create a json string with List<NameValuePair> in android

I want to send a http request to a url with Android.
I am an iOS developer and now trying to learn Android.
I used to send the JSON string in iOS like below
{"function":"login", "parameters": {"username": "nithin""password": "123456"}}
How can I send this in Android?
I tried List<NameValuePair> but can't find the proper solution.
Full code of what I tried -
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("function", "login"));
nameValuePairs.add(new BasicNameValuePair("username", "nithin"));
nameValuePairs.add(new BasicNameValuePair("password", "123456"));
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
}
I think JsonStringer is easy and useful for you here..
Try this:
HttpPost request = new HttpPost(URL);
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
JSONStringer vm;
try {
vm = new JSONStringer().object().key("function")
.value(login).key("parameters").object()
.key("username")
.value(nithin).key("password").value("123456")
.endObject().endObject();
StringEntity entity = new StringEntity(vm.toString());
request.setEntity(entity);
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);

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

Android post request

I have javascript code that i am trying to mimic in an android application:
Here is the javascript code:
text = '{"username":"Hello","password":"World"}';
x.open("POST", url);
x.setRequestHeader("Content-type", "application/json");
x.setRequestHeader("Content-length", text.length);
x.send(text);
and here is what i have so far for the android application(doesnt work):
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.setHeader("Content-type", "application/json");
String text = "\"{\"username\":\"Hello\",\"password\":\"World\"}\"";
httppost.setHeader("Content-length",Integer.toString(text.length()));
httppost.setEntity(new StringEntity(text));
HttpResponse response = httpclient.execute(httppost);
when i try to debug this code on eclipse the emulater keeps running while the debugger hangs. Thanks!
Note: its hanging on httpclient.execute(httppost)
Here is the code I use for Android post requests:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("fullurl");
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("parameter", "variable");
post.setEntity (new UrlEncodedFormEntity(pairs));
HttpResponse response = client.execute(post);
...and so on.
Try it out:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
JSONObject json = new JSONObject();
try{
json.put("username", "Hello");
json.put("password", "World");
StringEntity se = new StringEntity(json.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
HttpResponse response = httpclient.execute(httppost);
/*Checking response */
if(response!=null){
InputStream in = response.getEntity().getContent(); //Get the data in the entity
}
catch(Exception e){
e.printStackTrace();
}
Did you mean to set your HttpPost path to just path. I think your hanging because you haven't given the HttpPost a valid URL. You'll need to modify this line:
HttpPost httppost = new HttpPost("path");
to something like
HttpPost httppost = new HttpPost("actual/url/path");
You have extra speech marks within the start and end of your text string compared to the JS version?
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(StringUrl);
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);
System.out.println("rep => " + response);
} catch (IOException e) {
System.out.println(e);
}
}

Categories

Resources