HTTP post from android to PHP not working - php

I am trying to get a Android device to send some information to a local host. I believe I have the Android sending the information, but my PHP code is not accepting or not displaying the code. I have attached my code, is there something I have missed? I am running wamp server also, and have put the permissions into the manifest.
Java Code: #
HttpPost httppost;
HttpClient httpclient;
// List with arameters and their values
List<NameValuePair> nameValuePairs;
String serverResponsePhrase;
int serverStatusCode;
String bytesSent;
String serverURL = "http://10.0.2.2/test/index.php";
httppost = new HttpPost(serverURL);
httpclient = new DefaultHttpClient();
nameValuePairs = new ArrayList<NameValuePair>(2);
// Adding parameters to send to the HTTP server.
nameValuePairs.add(new BasicNameValuePair("parameterName1", "git"));
nameValuePairs.add(new BasicNameValuePair("parameterName2", "git"));
// Send POST message with given parameters to the HTTP server.
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
InputStream is = response.getEntity().getContent();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(20);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
bytesSent = new String(baf.toByteArray());
// Response from the server
serverResponsePhrase = response.getStatusLine().getReasonPhrase();
serverStatusCode = response.getStatusLine().getStatusCode();
System.out.println("COMPLETE");
} catch (Exception e) {
// Exception handling
System.out.println("Problem is " + e.toString());
}
PHP Code:
<?php
echo "param1 value: ".$_POST['parameterName1']."\n";
echo "param2 value: ".$_POST['parameterName2']."\n";
?>
I also tried this code, but it did not work with my PHP
HttpPost httppost;
HttpClient httpclient;
// List with arameters and their values
List<NameValuePair> nameValuePairs;
String serverResponsePhrase;
int serverStatusCode;
String bytesSent;
String serverURL = "http://10.0.2.2/test/index.php";
httppost = new HttpPost(serverURL);
httpclient = new DefaultHttpClient();
nameValuePairs = new ArrayList<NameValuePair>(2);
// Adding parameters to send to the HTTP server.
nameValuePairs.add(new BasicNameValuePair("'parameterName1'", "git"));
nameValuePairs.add(new BasicNameValuePair("'parameterName2'", "git"));
// Send POST message with given parameters to the HTTP server.
try {
HttpEntity entity = new UrlEncodedFormEntity(nameValuePairs);
httppost.addHeader(entity.getContentType());
httppost.setEntity(entity);
HttpResponse response = httpclient.execute(httppost);
InputStream is = response.getEntity().getContent();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(20);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
bytesSent = new String(baf.toByteArray());
// Response from the server
serverResponsePhrase = response.getStatusLine().getReasonPhrase();
serverStatusCode = response.getStatusLine().getStatusCode();
System.out.println("response" + response.toString());
System.out.println("COMPLETE");
} catch (Exception e) {
// Exception handling
System.out.println("Problem is " + e.toString());
}

Make sure the Content-Type HTTP header is getting set. Try replacing
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
with this
HttpEntity entity = new UrlEncodedFormEntity(nameValuePairs);
httppost.addHeader(entity.getContentType());
httppost.setEntity(entity);
Also, instead of response.toString(), try EntityUtils.toString(response.getEntity()) if you want to see the body of the response

Related

Android Json to Server sends not data

I got a problem. I read a lot here but unfortunately I can't get an answer for my problem.
I want to send a Json post to my Server. The Server should then save the string in my database.
This is my server code so far:
<?php
include('db_connect.php');
$db = new _DB_Connect();
$db->connect();
if(isset($_POST['regid'])){
$data = json_decode($_POST['regid']);
$save_entry = "insert into gcm_users (gcm_regid) values ('$data')";
mysql_query($save_entry) or die (mysql_error());
}else{
echo 'no data get';
}
?>
And this is my method on my android phone.
public String sendJson(View view){
InputStream inputStream = null;
String result = "";
String url2 = "http://192.168.0.5/control_center/functions/incomming.php";
TextView textView_result;
textView_result = (TextView) findViewById(R.id.textView_result);
//strict mode for networking
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url2);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-Type" , "application/json");
JSONObject jsonObject = new JSONObject();
jsonObject.put("regid", "blablabla");
String json = jsonObject.toString();
StringEntity se = new StringEntity(json);
httpPost.setEntity(se);
HttpResponse httpResponse = httpClient.execute(httpPost);
inputStream = httpResponse.getEntity().getContent();
if(inputStream != null) {
System.out.println(convertInputStreamToString(inputStream));
}
else {
result = "Did not work!";
}
textView_result.setText(httpResponse.toString());
System.out.println(jsonObject.toString());
}catch(JSONException e){
e.printStackTrace();
}catch(UnsupportedEncodingException e){
e.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
return result;
}
Now the
System.out.println(convertInputStreamToString(inputStream));
tells me that I got no data
echo 'no data get';
So I get a response form the server but I could find my error, why the post data could not be retrieved.
Would appreciate any help or hints. Thank you.
try this...
JSONObject jsonObject = new JSONObject();
jsonObject.put("regid", "blablabla");
String json = jsonObject.toString();
MultipartEntityBuilder multiPart = MultipartEntityBuilder.create();
multiPart.addTextBody("regid",json);
or
multiPart.addTextBody("regid","blablabla");
httpPost.setEntity(multiPart.build());

sending a value with HttpPost object

I would like to send a value to the end of a url.
ex:
if I have id=1;, I want to send this id to end of my url (to obtain id) :
www.example.com/get/id
id values ​​are different. (ex:id=2;id=3;id=4...).
is it possible ? how can I use HttpPost for this Scenario ?
I am using these functions but I always get this message :
no parametrs was sended !
inside my url :
www.example.com/get/id :
function get($id=0){
$id = (int)$id;
if(!$id) exit("no parametrs was sended !");
$trac = $this->m_general->get('tractions' , array('id' => $id ) , true );
if(!$trac ) $resp = "-1";
else
if($trac->expired != 0 || $trac->cradit_end_date < date('Y-m-d'))
{
$resp = 0;
}else
$resp = 1;
echo json_encode(array('response'=>$resp));
}
function set(){
$data = $this->input->post('data');
if(!$data) exit("no parametrs was sended !");
$message = $data;
$message = substr($message,7,-6);
list($qr,$date,$time) = explode("&",$message);
$insert = array(
'qr'=>$qr ,
'date'=>$date ,
'time'=>$time ,
'main'=>$message
);
$this->m_general->add('qr' , $insert );
}
private void postData(String valueIWantToSend) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(this.url_server_side);
HttpResponse response = null;
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("data", valueIWantToSend));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
response = httpclient.execute(httppost);
String res = EntityUtils.toString(response.getEntity());
Log.e("Response = ", res);
isok = 1 ;
} catch (ClientProtocolException e) {
e.printStackTrace();
// TODO Auto-generated catch block
isok = -1 ;
} catch (IOException e) {
e.printStackTrace();
// TODO Auto-generated catch block
isok = -1 ;
}
//Log.e("res", response.toString()) ;
}
As you mentioned above your web application expecting GET method to pass variables. In java code you are sending a POST request. You should use GET method to pass data.
String url = "http://www.example.com/id/YOUR_ID_DATA/data/YOUR_DATA";
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(url);
// add request header
request.addHeader("User-Agent", USER_AGENT);
HttpResponse response = client.execute(request);
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
Or send both id, data in a POST request and accept as a POST response from PHP side.
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.example.com");
HttpResponse response = null;
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("id", YOUR_ID_DATA));
nameValuePairs.add(new BasicNameValuePair("data", YOUR_DATA));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Then in PHP Side
$id = $_POST["id"];
$data = $_POST["data"];

Connect to php page using .htaccess with android application

i've a locked php page (username and password) by .htaccess file, how can i do to connect to this php with my android application? My function to connect is :
String conn(JSONObject json,String page){
String result = "";
String stringaFinale = "";
InputStream is = null;
final int TIMEOUT_MILLISEC = 5000; // = 10 seconds
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
HttpClient client = new DefaultHttpClient(httpParams);
HttpPost request = new HttpPost("http://olbolb.org/Hihi/"+page);
//request result type
request.setHeader("Accept", "application/json; charset=utf-8");
try{ StringEntity se = new StringEntity(json.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json"));
request.setEntity(se);
HttpResponse response = client.execute(request);
temp= EntityUtils.toString(response.getEntity());
return temp;
}
catch(Exception e){
return null;
}
}
You can add this code for BASIC authentication in HttpPost object:
HttpPost request = new HttpPost("http://olbolb.org/Hihi/"+page);
request.setHeader("Authorization", "Basic " +
new Base64().encodeToString("username:password".getBytes("UTF-8"), Base64.DEFAULT) );

& converted into & when $_POST request is called?

We are working on an application which has 2 modules.
Android Application.
PHP Application
PHP backend application runs on an Apache Server with Centos Server.
Android application basically clicks images, send to the server along with gps coordinates etc form information.
Now the problem arises when the image file is created on the server. When android app calls the url the '&' character is replaced by & amp;, sometimes even by & amp;& amp; and this problem repeats in some of the cases. Once this conversion thing happens, image file is not created properly.
How it can be resolved?
Same code was working alright from past year, this problem begin to arise from last month only....
Following is the code for saving the images at server end :
foreach($_POST as $key => $value) {
$_POST[$x] = $value;
}
$base=$_REQUEST['image'];
$nm=$_REQUEST['name'];
$binary=base64_decode($base);
if(file_exists("uploaded_images/".$nm.".jpg")) {
unlink("uploaded_images/".$nm.".jpg");
}
header('Content-Type: bitmap; charset=utf-8');
$str="uploaded_images/".$nm.".jpg";
$file = fopen($str, 'wb');
fwrite($file, $binary);
fclose($file);
chmod($file,0777);
$ok=1;
echo $ok;
Following is the error log which is encountered if image is not properly saved.
PHP Notice: Undefined index: name in /var/www/html/cbd/def/filesubmitnew.php
Note : filesubmitnew.php is the file name of the above code.
In Android Application for this is how the url is called:
To Create image:
if(buttontext.equals("Img1")) {
Bitmap bitmap = (Bitmap) data.getExtras().get("data");
v.setImageBitmap(bitmap);
buttontext="";
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 20, stream);
byte [] byte_arr = stream.toByteArray();
String str1 = Base64.encodeBytes(byte_arr);
System.out.println(""+str1);
if(feuser.equals("offline_access")){
System.out.println("++==--SD CARD");
File externalStorage = Environment.getExternalStorageDirectory();
File folder = new File(externalStorage.getAbsolutePath() +mainFolder + caseId);
if (!folder.exists()) {
folder.mkdir();
}
File pictureFile = new File(externalStorage.getAbsolutePath()+mainFolder+caseId, "1.jpg");
System.out.println(pictureFile);
pictureFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(pictureFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(str1);
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),"Done writing SD "+pictureFile,Toast.LENGTH_SHORT).show();
}
else {
Intent i = new Intent ("com.keyboardlabs.newbankge.CameraUploadService");
try {
i.putExtra("imageparams", str1);
i.putExtra("ref_id", caseId);
i.putExtra("imageId", "1");
i.putExtra("CaseType",caseType);
}
catch (Exception e) {
e.printStackTrace();
}
getApplicationContext().startService(i);
}
Following is the camerauploadservice
protected void onHandleIntent(Intent arg0) {
String imageDataBase64encoded = arg0.getStringExtra("imageparams");
String caseID = arg0.getStringExtra("ref_id");
String imageId = arg0.getStringExtra("imageId");
String caseType =arg0.getStringExtra("CaseType");
System.out.println("image_ref="+caseID+"iamgeID="+imageId+"caseType="+caseType+" URL="+URL);
callWebService(imageDataBase64encoded,caseID,imageId,caseType);
}
public void callWebService(String imageData,String refId,String imageId,String caseType){
HttpClient httpclient = null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("image",imageData));
nameValuePairs.add(new BasicNameValuePair("ref_id",refId));
nameValuePairs.add(new BasicNameValuePair("imageId",imageId));
nameValuePairs.add(new BasicNameValuePair("CaseType",caseType));
try{
httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
String the_string_response = convertResponseToString(response);
System.out.println( "Response= " + the_string_response);
}catch(Exception e){
System.out.println( "0" + e.getMessage());
System.out.println("Error in http connection "+e.toString());
}
httpclient.getConnectionManager().shutdown();
}

Android: Uploading a file to a page along with other POST strings

I am trying to upload an image to a PHP page along with some other info about the image so the PHP page knows what to do with it. Currently, I am getting away with it using this:
URL url = new URL("http://www.tagverse.us/upload.php?authcode="+WEB_ACCESS_CODE+"&description="+description+"&userid="+userId);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
OutputStream os = connection.getOutputStream();
InputStream is = mContext.getContentResolver().openInputStream(uri);
BufferedInputStream bis = new BufferedInputStream(is);
int totalBytes = bis.available();
for(int i = 0; i < totalBytes; i++) {
os.write(bis.read());
}
os.close();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String serverResponse = "";
String response = "";
while((response = reader.readLine()) != null) {
serverResponse = serverResponse + response;
}
reader.close();
bis.close();
Is there a more elegant solution to this besides having a GET/POST hybrid? I feel as if this is sloppy, but for all I know it is a perfectly acceptable solution. If there is a better way of doing this, I'd appreciate being pointed in the right direction. Thanks!
PS: I am familiar with how you would, under normal conditions, interact with a PHP page via POST:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://www.tagverse.us/login.php");
try {
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("authcode", WEB_ACCESS_CODE));
pairs.add(new BasicNameValuePair("username", username));
pairs.add(new BasicNameValuePair("password", password));
post.setEntity(new UrlEncodedFormEntity(pairs));
client.execute(post);
}
Essentially what I'd like to do is combine these two methods, but because I work with an HttpURLConnection object rather than a HttpPost object, it isn't as simple as just merging the two.
Thank you!
You can try an take a look at the answer I added for this similar question:
https://stackoverflow.com/a/9003674/472747
Here is the code:
byte[] data = {10,10,10,10,10}; // better get this from a file or memory
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost("server url");
ByteArrayBody bab = new ByteArrayBody(data, "image.jpg");
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("image", bab);
FormBodyPart bodyPart=new FormBodyPart("formVariableName", new StringBody("formValiableValue"));
reqEntity.addPart(bodyPart);
bodyPart=new FormBodyPart("formVariableName2", new StringBody("formValiableValue2"));
reqEntity.addPart(bodyPart);
bodyPart=new FormBodyPart("formVariableName3", new StringBody("formValiableValue3"));
reqEntity.addPart(bodyPart);
postRequest.setEntity(reqEntity);
HttpResponse response = httpClient.execute(postRequest);
BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = null;
while((line = in.readLine()) != null) {
System.out.println(line);
}

Categories