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"];
Related
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());
I'm using a JSONParser class to create JSON to be sended to the server, but I need to use it for receive information now, but I don't know how to do it, I'm a noob, sorry. I create the json with the next part of code, and the following class.
// Building Parameters
params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("userid", thought.getUser()));
params.add(new BasicNameValuePair("timestamp", "" + thought.getTimestamp()));
params.add(new BasicNameValuePair("message", thought.getMessage()));
params.add(new BasicNameValuePair("address", thought.getAddress()));
params.add(new BasicNameValuePair("latitude", "" + thought.getLatitude()));
params.add(new BasicNameValuePair("longitude", "" + thought.getLongitude()));
// getting JSON Object
// Note that create product url accepts POST method
JSONParser jsonParser = new JSONParser();
JSONObject json = jsonParser.makeHttpRequest(url_create_thought, "POST", params);
JSONParser.class
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method, List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method.equalsIgnoreCase("POST")){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method.equalsIgnoreCase("GET")){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
The part in the server I think that it's ok.
Server get values part
<?php
/*
* Following code will list all the products
*/
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// get all products from products table
$result = mysql_query("SELECT * FROM thoughts") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
// products node
$response["thoughts"] = array();
echo '<center><div class="datagrid"><table>';
echo '<thead><tr><th>ID</th><th>USERID</th><th>TIMESTAMP</th><th>MESSAGE</th><th>ADDRESS</th><th>LATITUDE</th><th>LONGITUDE</th></tr></thead><tbody>';
while ($row = mysql_fetch_array($result)) {
// temp user array
$thought = array();
$thought["id"] = $row["id"];
$thought["userid"] = $row["userid"];
$thought["timestamp"] = $row["timestamp"];
$thought["message"] = $row["message"];
$thought["address"] = $row["address"];
$thought["latitude"] = $row['latitude'];
$thought["longitude"] = $row['longitude'];
echo '<tr><td>'.$row['id'].'</td><td>'.$row['userid'].'</td><td>'.$row['timestamp'].'</td><td>'.$row['message'].'</td><td>'.$row['address'].'</td><td>'.$row['latitude'].'</td><td>'.$row['longitude'].'</td></tr>';
// push single product into final response array
array_push($response["thoughts"], $thought);
}
// success
$response["success"] = 1;
// echoing JSON response
//echo json_encode($response);
echo '</table></center>';
} else {
// no products found
$response["success"] = 0;
$response["message"] = "No events found";
// echo no users JSON
echo json_encode($response);
}
?>
What it's the correct way to get data in android?? What I need to put in params?
JSONParser jsonParser = new JSONParser();
JSONObject json = jsonParser.makeHttpRequest(url_create_thought, **"GET"**, params);
Thanks for your help.
here is a simple way to get what u want from json-return url :
String sURL = "http://freegeoip.net/json/"; //just a string
// Connect to the URL using java's native library
URL url = new URL(sURL);
HttpURLConnection request = (HttpURLConnection) url.openConnection();
request.connect();
// Convert to a JSON object to print data
JsonParser jp = new JsonParser(); //from gson
JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); //convert the input stream to a json element
JsonObject rootobj = root.getAsJsonObject(); //may be an array, may be an object.
zipcode=rootobj.get("zipcode").getAsString();//just grab the zipcode
I am going to implement the client-to-Server module which request is sent from Android devices to php . When it comes to the implementation , I have no clue why the server side cannot receive the json sent from Android device . As for the server, the database insert module is OK but cannot catch the json values . Would you please tell me what is wrong with the client side ?
The below is my code
Client side Android
public String postData(String argument , String url) {
String result="";
// Create a new HttpClient and Post Header
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 60000 * 20;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
int timeoutSocket = 60000 * 20;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
HttpProtocolParams.setVersion(httpParameters, HttpVersion.HTTP_1_1);
HttpConnectionParams.setSocketBufferSize(httpParameters, 8*1024);
DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters);
//Log.d("url" , url);
HttpPost httppost = new HttpPost(url);
try {
System.out.println("Response:"+ "start execute");
JSONObject json = new JSONObject();
json.put("userid","loka");
json.put("password","yoor");
json.put("email","johnsmith#example.com");
//Log.d("test" , jsonString);
httppost.setEntity(new ByteArrayEntity(json.toString().getBytes("UTF8")));
httppost.setHeader( "Content-Type", "application/json" );
//httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = httpclient.execute(httppost);
int status = response.getStatusLine().getStatusCode();
//If php json response required
if(status==200){
HttpEntity getResponseEntity = response.getEntity();
InputStream httpResponseStream = getResponseEntity.getContent();
result = slurp(httpResponseStream , 8192);
System.out.println("result: "+ result);
}else{
System.out.println("2");
result = String.valueOf(status);
HttpEntity getResponseEntity = response.getEntity();
InputStream httpResponseStream = getResponseEntity.getContent();
result = slurp(httpResponseStream , 8192);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
return e.getMessage();
} catch (ConnectTimeoutException e){
e.printStackTrace();
return e.getMessage();
}catch (IOException e) {
e.printStackTrace();
return e.getMessage();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
Server side php
<?php
header('Content-type: application/json');
ini_set('display_errors','On');
require_once 'lib_mysql/insert.php';
$json = file_get_contents('php://input');
$result =insertUser($json);
if($result) {
echo "success";
}
else{
echo "fail";
}
?>
include_once("connection.php");
function insertUser($jsonString){
$usern = $jsonString->userid; //Undefined Variables
$pass = $jsonString->password; //Undefined Variables
$email = $jsonString->email; //Undefined Variables
$conn = getDBConn();
$data = false;
You need to use json_decode() function in php. header('Content-type: application/json'); would not help in this case
Try this way hope this helps you
Relpace
httppost.setEntity(new ByteArrayEntity(json.toString().getBytes("UTF8")));
with
httppost.setEntity(new StringEntity(json.toString(), HTTP.UTF_8));
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) );
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