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
Related
I am using the apache httpClient post method to call a rest client API, but API is giving incorrect response so I want to debug the method and want to print the request in json format.
below is the code I am using-
private String baseUrl = "myIPAddress";
private HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(baseUrl + "app/registration");
try {
String line = "";
for (int rIndex = 0; rIndex < goodAuthenticationPairs.length; rIndex++) {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
1);
nameValuePairs.add(new BasicNameValuePair("email","myEmail#test.com"));
nameValuePairs.add(new BasicNameValuePair("password","myPassword"));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//post.setHeader("Content-type", "application/json");
System.out.println(post);
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
line = rd.readLine();
System.out.println(line);
JSONObject json = (JSONObject) new JSONParser().parse(line);
String actualResult = json.get("return_code").toString();
assertTrue("0".equals(actualResult));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
client.getConnectionManager().shutdown();
}
I got the answer.
The code above is sending request in Content-Type: application/x-www-form-urlencoded but the server API expects Content-Type: application/json
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.
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
}
I've tried several things but my android app is not sending post parameters. I run the app on a virtual device. This is the code:
#Override
public void run() {
try{
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(page);
HttpParams httpParams = client.getParams();
httpParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 20000);
post.setHeader("Content-type", "application/json");
post.setHeader("Accept", "application/json");
JSONObject obj = new JSONObject();
obj.put("username", "abcd");
obj.put("password", "1234");
post.setEntity(new StringEntity(obj.toString(), "UTF-8"));
HttpResponse response = client.execute(post);
InputStreamReader isr = new InputStreamReader(response.getEntity().getContent());
BufferedReader reader = new BufferedReader(isr);
String line = "";
while((line = reader.readLine()) != null){
System.out.println(line);
}
}catch(Exception e){
e.printStackTrace();
}
}
It should send a post request to a PHP page. This page displays the output of the POST array:
<?php
print_r($_POST);
?>
When I run the app, it displays an empty array.
thats because you're sending JSON
standard php $_POST is build from key-value pairs
so you should post key1=value1&key2=value2
or you should read from
$HTTP_RAW_POST_DATA
or
<?php $postdata = file_get_contents("php://input"); ?>
and use
json_decode( $postdata );
PHP will not automatically decode json for you
you can also use another approach and POST your json like data=YourJsonCode
and then decode it using json_decode( $_POST['data'] );
Try sending url encoded name/value pairs. You can also use EntityUtils to convert the response to a String for you.
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(page);
HttpParams httpParams = client.getParams();
httpParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 20000);
post.setHeader("Content-Type","application/x-www-form-urlencoded");
List<NameValuePair> formParams = new ArrayList<NameValuePair>();
formParams.add(new BasicNameValuePair("username", "abcd"));
formParams.add(new BasicNameValuePair("password", "1234"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams,HTTP.UTF_8);
post.setEntity(entity);
HttpResponse httpResponse = client.execute(post);
System.out.println(EntityUtils.toString(httpResponse.getEntity()));
Problem solved. There was a htaccess file that redirected all non www pages.
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