the problem is that i don't receive any $_POST['registerationID'] from android webview
i have this code in android java ::
#Override
protected void onRegistered(Context context, String registrationId) {
String URL_STRING = "http://mysite.org/mysite/index.php/user/notification/";
Log.i(MyTAG, "onRegistered: registrationId=" + registrationId);
// notification
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("registrationId",registrationId));
try{
HttpPost httppost = new HttpPost(URL_STRING);
httppost.setHeader("Content-Type","text/plain");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setBooleanParameter("http.protocol.expect-continue", false);
HttpResponse response = httpclient.execute(httppost);
Log.i("LinkPOST:", httppost.toString());
Log.i("postData", response.getStatusLine().toString());
HttpEntity httpEntity = response.getEntity();
if (httpEntity != null){
//System.out.println("Not Empty");
String responseBody = EntityUtils.toString(httpEntity);
System.out.println(responseBody);
} else {
System.out.println("Empty");
}
}
catch(Exception e)
{
Log.e("log_tag", "Error in http connection "+e.toString());
}
}
and i handle the httprequest post in php (using codeigniter) as the following :
function notification() {
$registrationId = $_POST['registrationId'];
if($this->session->userdata('emailid')) {
//echo 'working from inside the if statement'.$this->session->userdata('emailid');
//$query = $this->db->query('INSERT INTO user (`deviceid`) VALUES ('.$_GET['registerationID'].') where `emailid`='.$this->session->userdata('emailid').';');
$data = array(
'deviceid' => $registrationId,
);
$this->db->where('emailid', $this->session->userdata('emailid'));
$this->db->update('user', $data);
if($this->db->affected_rows() == 1) {
// some code
}
else {
// some code
}
}
Try with the function bellow. It works for me.
Just Fill a HashMap for your post params
private static void post(String url, Map<String, String> params)
throws IOException {
URL url;
try {
url = new URL(endpoint);
} catch (MalformedURLException e) {
throw new IllegalArgumentException("invalid url: " + endpoint);
}
StringBuilder bodyBuilder = new StringBuilder();
Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
// constructs the POST body using the parameters
while (iterator.hasNext()) {
Entry<String, String> param = iterator.next();
bodyBuilder.append(param.getKey()).append('=')
.append(param.getValue());
if (iterator.hasNext()) {
bodyBuilder.append('&');
}
}
String body = bodyBuilder.toString();
Log.v(TAG, "Posting '" + body + "' to " + url);
byte[] bytes = body.getBytes();
HttpURLConnection conn = null;
try {
Log.e("URL", "> " + url);
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setFixedLengthStreamingMode(bytes.length);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
// post the request
OutputStream out = conn.getOutputStream();
out.write(bytes);
out.close();
// handle the response
int status = conn.getResponseCode();
if (status != 200) {
throw new IOException("Post failed with error code " + status);
}
} finally {
if (conn != null) {
conn.disconnect();
}
}
}
Try replacing
httppost.setHeader("Content-Type","text/plain")
by
httppost.setHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8")
which is expected by your php code.
For more detail please see this SO question
Related
i need to pass to this URL a parameter http://192.168.1.15:8888/android_login_api/getsPreferiti.php?id="+mParam1
where mParam1 contains this String 5a325bc1b214c5.50816853
how can i do?
PS:now i get this: Response from url: {"error":false,"message":"VIDEOs fetched successfully.","pdfs":[]} but pdfs array have pdfs
Add parameters to HTTPURL Connection using HTTPPost
URL url = new URL("http://yoururl.com");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("parameter1", parameterValue1));
params.add(new BasicNameValuePair("parameter2", parameterValue2));
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getQuery(params));
writer.flush();
writer.close();
os.close();
conn.connect();
private String getQuery(List<NameValuePair> params) throws
UnsupportedEncodingException
{
StringBuilder result = new StringBuilder();
boolean first = true;
for (NameValuePair pair : params)
{
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
}
return result.toString();
}
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
String response = null;
int GET = 1;
int POST = 2;
try {
// http client
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();
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
And you can call this method by using AsyncTask as follow:
try {
JSONObject jData = new JSONObject();
String mParam = "5a325bc1b214c5.50816853";
jData.put("id", mParam);
List<NameValuePair> params1 = new ArrayList<NameValuePair>(2);
params1.add(new BasicNameValuePair("data", jData.toString()));
response = makeServiceCall("http://192.168.1.15:8888/android_login_api/getsPreferiti.php", 1, params1);
} catch (JSONException e) {
e.printStackTrace();
}
I am implementing azure for my web application and trying to get access token by following there openId connect tutorial
https://learn.microsoft.com/en-us/azure/active-directory/develop/active-directory-protocols-oauth-code
And when i am requesting to get the access token, i am always getting bad request 400
Request to get access token :
POST /{tenant}/oauth2/token HTTP/1.1
Host: https://login.microsoftonline.com
Content-Type: application/x-www-form-urlencoded
grant_type=authorization_code
&client_id=2d4d11a2-f814-46a7-890a-274a72a7309e
&code=AwABAAAAvPM1KaPl.......
&redirect_uri=https%3A%2F%2Flocalhost%2Fmyapp%2F
&resource=https%3A%2F%2Fservice.contoso.com%2F
&client_secret=p#ssw0rd
here is my code :
public static String post( String endpoint,
Map<String, String> params) {//YD
StringBuffer paramString = new StringBuffer("");
//if(!Utilities.checkInternetConnection(context)){
// return XMLHandler.getXMLForErrorCode(context, JSONHandler.ERROR_CODE_INTERNET_CONNECTION);
//}
Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
StringBuffer tempBuffer = new StringBuffer("");
String paramval;
while (iterator.hasNext()) {
Entry<String, String> param = iterator.next();
if (param != null) {
if (paramString.length() > 0) {
paramString.append("&");
}
System.out.println( "post key : " + param.getKey());
String value;
try {
paramval = param.getValue();
if(paramval!=null)
value = URLEncoder.encode(paramval, "UTF-8");
else
value = "";
} catch (UnsupportedEncodingException e) {
value = "";
e.printStackTrace();
}
paramString.append(param.getKey()).append("=")
.append(value);
}
}
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(endpoint);
String data = "";
try {
// Add your data
// httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs))
//httppost.addHeader("Host", host);
httppost.addHeader("Content-Type",
"application/x-www-form-urlencoded");
if (!paramString.equals("")) {
if (tempBuffer.length() > 0) {
data = data + tempBuffer.toString();
}
data = data + paramString.toString();
if (data.endsWith("&")) {
data = data.substring(0, data.length() - 1);
}
httppost.setEntity(new ByteArrayEntity(data.getBytes()));
}
System.out.println( "post Stringbuffer : " + data);
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
int statuscode = response.getStatusLine().getStatusCode();
System.out.println("Response code : " + statuscode);
if (statuscode != 200) {
return null;
}
HttpEntity entity = response.getEntity();
InputStream in = null;
if (entity != null) {
in = entity.getContent();
}
if (in != null) {
StringBuilder builder = new StringBuilder();
String line;
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(in, "UTF-8"));
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} finally {
in.close();
}
String response2 = builder.toString();
System.out.println("response :" + response2);
retrycount = 0;
return response2;
}
}
catch(UnknownHostException e){
e.printStackTrace();
return null;
}
catch (EOFException eof) {
if (retrycount < max_retry) {
eof.printStackTrace();
post( endpoint, params);
retrycount = 1;
}
} catch (Throwable th) {
throw new IOException("Error in posting :" + th.getMessage());
}
retrycount = 0;
return null;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
Please help me with this
Thanks in Advance
Have you ensured the redirect uri passed to /token is the same as the one you passed to /authorize
I believe, it will help if you can test the OAuth auth code flow with your current client id, secret and scope using Postman tool in order to rule out bad configuration.
Please refer to the code below to request AuthorizationCode.
public static void getAuthorizationCode() throws IOException {
String encoding = "UTF-8";
String params = "client_id=" + clientId
+ "&response_type=" + reponseType
+ "&redirect_uri=http%3A%2F%2Flocalhost%2Fmyapp%2F"
+ "&response_mode=query"
+ "&resource=https%3A%2F%2Fgraph.windows.net"
+ "&state=12345";
String path = "https://login.microsoftonline.com/" + tenantId + "/oauth2/authorize";
byte[] data = params.getBytes(encoding);
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(data.length));
conn.setConnectTimeout(5 * 1000);
OutputStream outStream = conn.getOutputStream();
outStream.write(data);
outStream.flush();
outStream.close();
System.out.println(conn.getResponseCode());
System.out.println(conn.getResponseMessage());
BufferedReader br = null;
if (conn.getResponseCode() != 200) {
br = new BufferedReader(new InputStreamReader((conn.getErrorStream())));
} else {
br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
}
System.out.println("Response body : " + br.readLine());
}
Then you could get access token using the AuthorizationCode you got and get refresh code using the code below.
public static void getToken(String refreshToken) throws IOException {
String encoding = "UTF-8";
String params = "client_id=" + clientId + "&refresh_token=" + refreshToken
+ "&grant_type=refresh_token&resource=https%3A%2F%2Fgraph.windows.net";
String path = "https://login.microsoftonline.com/" + tenantId + "/oauth2/token";
byte[] data = params.getBytes(encoding);
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(data.length));
conn.setConnectTimeout(5 * 1000);
OutputStream outStream = conn.getOutputStream();
outStream.write(data);
outStream.flush();
outStream.close();
System.out.println(conn.getResponseCode());
System.out.println(conn.getResponseMessage());
BufferedReader br = null;
if (conn.getResponseCode() != 200) {
br = new BufferedReader(new InputStreamReader((conn.getErrorStream())));
} else {
br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
}
System.out.println("Response body : " + br.readLine());
}
Hope it helps you.
I am trying to successfully send data across from an android app to a php web app and display that data and save into a mysql database. However i don't get an exception or anything just the data i send across does not get received on the server end. My code is below:
public void onClick(View view) {
String text = "None";
switch (view.getId()) {
case R.id.btnOne:
send();
text = "Response Submitted";
break;
case R.id.btnTwo:
text = "Two";
break;
case R.id.btnThree:
text = "Three";
break;
case R.id.btnFour:
text = "Four";
break;
}
Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
}
private void send() {
URL a = null;
try {
a = new URL("http://cce.swlgroup.com/json.php/");
} catch (Exception exception) {
exception.printStackTrace();
}
new URLTestTask().execute(a);
}
private class URLTestTask extends AsyncTask<URL, Integer, Void> {
#Override
protected void doInBackground(URL... urls) {
HttpURLConnection conn = null;
BufferedReader reader = null;
try {
URL url = new URL("http://cce.swlgroup.com/json.php/");
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
Log.e("", "" + conn.getResponseMessage());
conn.connect();
JSONObject obj = new JSONObject();
obj.put("Marge","Simpson");
HttpClient client = new DefaultHttpClient();
HttpGet post = new HttpGet(url.toURI());
post.setEntity(new ByteArrayEntity(obj.toString().getBytes("UTF8")));
post.setHeader("json",obj.toString());
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String responseBody = client.execute(post,
responseHandler);
HttpEntity ent = post.getEntity();
InputStream stream = ent.getContent();
String result = RestClient.convertStreamToString(stream);
BufferedReader red = new BufferedReader(new InputStreamReader(ent.getContent()));
String line;
StringBuilder lb = new StringBuilder();
while((line = red.readLine()) != null){
lb.append(red);
}
red.close();
Log.i("Read from server", result);
} catch (Exception e){
e.printStackTrace();
}finally {
if (conn != null)
conn.disconnect();
try{
if (reader != null)
reader.close();
} catch (Exception e){
e.printStackTrace();
}
}
return null;
}
}
my php code is below to get data and display:
$json = file_get_contents('php://input');
$obj = json_decode($json);
var_dump($obj);
var_dump($_POST);
var_dump($_GET);
HttpURLConnection conn = null;
BufferedReader reader = null;
try {
URL url = new URL("http://10.0.2.2/json.php/");
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
Log.e("", "" + conn.getResponseMessage());
conn.connect();
JSONObject obj = new JSONObject();
obj.put("Marge","Simpson");
HttpClient client = new DefaultHttpClient();
StringBuilder pat = new StringBuilder();
HttpGet post = new HttpGet(url.toURI());
post.setEntity(new ByteArrayEntity(obj.toString().getBytes("UTF8")));
post.setHeader("json", obj.toString());
post.setHeader("Content-Type", "application/json");
post.setHeader("accept-encoding","gzip, deflate");
post.setHeader("accept-language","en-US,en;q=0.8");
post.setHeader("FormData",obj.toString());
HttpResponse lazy = client.execute(post);
HttpEntity ent = lazy.getEntity();
String lb = EntityUtils.toString(ent);
pat.append(lb);
Log.i("Read from server", pat.toString());
} catch (Exception e){
e.printStackTrace();
}finally {
if (conn != null)
conn.disconnect();
try{
if (reader != null)
reader.close();
} catch (Exception e){
e.printStackTrace();
}
}
return null;
I made the change in accordance with that code but it doesnt seem to send a result across.
I need to good class for sending and handling the all request such as get , post
I researched anywhere but i could not find the good helper class for it , i am beginner in java and android , please share a good connection helper class with me
public class RRequestHelper
{
DefaultHttpClient httpClient;
HttpContext localContext;
private String ret;
HttpResponse response = null;
HttpPost httpPost = null;
HttpGet httpGet = null;
public RRequestHelper()
{
this.setDefaultOptions();
}
public void setDefaultOptions()
{
HttpParams myParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(myParams, RGeneralSettings.getInstance().getSettingInt(RConstants.CONNECTION_TIMEOUT, false));
HttpConnectionParams.setSoTimeout(myParams, RGeneralSettings.getInstance().getSettingInt(RConstants.CONNECTION_TIMEOUT, false));
httpClient = new DefaultHttpClient(myParams);
localContext = new BasicHttpContext();
}
public void clearCookies()
{
httpClient.getCookieStore().clear();
}
public void abort()
{
try
{
if (httpClient != null)
{
System.out.println("Abort.");
httpPost.abort();
}
}
catch (Exception e)
{
System.out.println("Your App Name Here" + e);
}
}
public String sendPost(String url, String data)
{
return sendPost(url, data, null);
}
public String sendJSONPost(String url, JSONObject data)
{
return sendPost(url, data.toString(), "application/json");
}
public String sendPost(String url, String data, String contentType)
{
ret = null;
httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109);
httpPost = new HttpPost(url);
response = null;
StringEntity tmp = null;
Log.d("Your App Name Here", "Setting httpPost headers");
httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:32.0) Gecko/20100101 Firefox/32.0");
httpPost.setHeader("Accept", "text/html,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
if (contentType != null)
{
httpPost.setHeader("Content-Type", contentType);
}
else
{
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
}
try
{
tmp = new StringEntity(data,"UTF-8");
}
catch (UnsupportedEncodingException e)
{
Log.e("Your App Name Here", "HttpUtils : UnsupportedEncodingException : "+e);
}
httpPost.setEntity(tmp);
Log.d("Your App Name Here", url + "?" + data);
try
{
response = httpClient.execute(httpPost,localContext);
if (response != null)
{
ret = EntityUtils.toString(response.getEntity());
}
}
catch (Exception e)
{
Log.e("Your App Name Here", "HttpUtils: " + e);
}
Log.d("Your App Name Here", "Returning value:" + ret);
return ret;
}
public String sendGet(String url) {
httpGet = new HttpGet(url);
try {
response = httpClient.execute(httpGet);
} catch (Exception e) {
Log.e("Your App Name Here", e.getMessage());
}
//int status = response.getStatusLine().getStatusCode();
// we assume that the response body contains the error message
try {
ret = EntityUtils.toString(response.getEntity());
} catch (IOException e) {
Log.e("Your App Name Here", e.getMessage());
}
return ret;
}
public InputStream getHttpStream(String urlString) throws IOException
{
InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
{
throw new IOException("Not an HTTP connection");
}
try
{
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
}
catch (Exception e)
{
throw new IOException("Error connecting");
} // end try-catch
return in;
}
}
I have an application that post data to a php file in an online server. When the post is done i get a garbage of html code. In it says I have a php error and that is Invalid argument supplied for each() on line 33. However this problem does not occur if I run it in localhost. I don't understand why this problem is occuring. So someone please help me to solve it.
The following is my jsonparser Class
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getandpostJSONFromUrl(String url, String method,JSONArray name) {
// Making HTTP request
try {
// defaultHttpClient
if (method == "POST") {
HttpParams params = new BasicHttpParams();
//params.setParameter("data", auth);
HttpClient httpclient = new DefaultHttpClient(params);
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> postParams = new ArrayList<NameValuePair>();
postParams.add(new BasicNameValuePair("json", name.toString()));
for (NameValuePair nvp : postParams) {
String name2 = nvp.getName();
String value = nvp.getValue();
Log.d("NameValue pair content", ""+name2+""+value);
}
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postParams,HTTP.UTF_8);
httpPost.setEntity(entity);
HttpResponse response = httpclient.execute(httpPost);
String responseBody = EntityUtils.toString(response.getEntity());
Log.d("",responseBody);
}
if (method == "GET") {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (method == "POST") {
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
} catch (Exception e) {
Log.e("Buffer error", "Buffer error" + e);
}
} else if (method == "GET") {
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);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
}
// return JSON String
return jObj;
}
}
The following is the php file on the server
<?php
header('Content-type: application/json');
/*define('DB_NAME', 'a1422982_sshop');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');*/
define('DB_NAME', 'onlineshop');
define('DB_USER', 'shop');
define('DB_PASSWORD', 'pass');
define('DB_HOST', 'mysql28.000webhost.com');
$link = mysql_connect(DB_HOST,DB_USER,DB_PASSWORD);
if(!$link){
die('could not connect: '.msql_error());
}
$db_selected=mysql_select_db(DB_NAME, $link);
if(!$db_selected){
die('Can not use '.DB_NAME.':'.mysql_error());
}
//var_dump(json_decode ($_POST['json'])));
if($_POST['json']){
$parsed = json_decode($_POST['json'],TRUE);
$i=0;
foreach ($parsed as $obj) {
$ProductName = $obj['Name'];
$ProductQuantity= $obj['Quantity'];
$sql="Update productlist Set Quantity='$ProductQuantity' where Name='$ProductName';";
$retval = mysql_query( $sql, $link );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
$i++;
echo $ProductName." ".$ProductQuantity;
}
}else{
echo "empty";
}
?>
there's a missing options on your HttpPost request set the entity metadata and the resulting entity as string.
In your java code you can do this:
Map<String, String> postData = new HashMap<String, String>();
postData.put("KEY", "yourvalue");
JSONObject holder = new JSONObject(postData);
StringEntity jsonStringEntity = new StringEntity(holder.toString());
httpost.setEntity(jsonStringEntity);
httpost.setHeader("Accept", "application/json");
httpost.setHeader("Content-type", "application/json");
in that way your PHP code could actually parse your post data since json_decode() expecting json as parameter.