Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/281.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/195.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用POST和httpurl连接将数据发送到php服务器并在php服务器中接收数据_Php_Android_Httpurlconnection - Fatal编程技术网

如何使用POST和httpurl连接将数据发送到php服务器并在php服务器中接收数据

如何使用POST和httpurl连接将数据发送到php服务器并在php服务器中接收数据,php,android,httpurlconnection,Php,Android,Httpurlconnection,我正在制作一个应用程序,在该应用程序中,我需要将数据发送到php服务器,并在php服务器上接收数据,反之亦然。我无法从android应用程序向php服务器发送数据?你能告诉我怎么做吗 这是我向服务器发送数据的代码。 公共类EventServiceHandler { 字符串数据; DoSomething d=新的DoSomething(); publicEventServiceHandler(){ //TODO自动生成的构造函数存根 d、 执行(); } public void getObjec

我正在制作一个应用程序,在该应用程序中,我需要将数据发送到php服务器,并在php服务器上接收数据,反之亦然。我无法从android应用程序向php服务器发送数据?你能告诉我怎么做吗

这是我向服务器发送数据的代码。

公共类EventServiceHandler
{
字符串数据;
DoSomething d=新的DoSomething();
publicEventServiceHandler(){
//TODO自动生成的构造函数存根
d、 执行();
}
public void getObject()
{   
字符串s=”http://www.example.com/thisisthis.php";
试一试{
URL=新的URL;
HttpURLConnection connection=(HttpURLConnection)url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(真);
connection.setRequestMethod(“POST”);
连接。设置连接超时(100000);
连接。setReadTimeout(100000);
connection.connect();
OutputStreamWriter out=新的OutputStreamWriter(connection.getOutputStream());
response=connection.getResponseCode();
String name=“sateesh”;
字符串测试=URLEncoder.encode(“名称”,“utf-8”)
+“=”+URLEncoder.encode(名称,“utf-8”);
写出(测试);
} 
捕获(格式错误)
{
//TODO自动生成的捕捉块
e、 printStackTrace();
}捕获(IOE异常)
{
//TODO自动生成的捕捉块
e、 printStackTrace();
} 
}
私有类DoSomething扩展了异步任务
{
@凌驾
受保护的Void doInBackground(Void…参数)
{
//TODO自动生成的方法存根
getObject();
返回null;
}
}
}

这是php服务器上用于在服务器上接收数据的代码。

<?php

if($_POST)
{
    $name = urldecode($_POST['name']);
    echo $name;
    error_log($name,0);
    echo "  ok";
}

else if(is_null($_POST) OR empty($_POST))
{
    error_log("empty or null",0);
    echo "in else if";

}

else
{
    echo "<br>";
    echo "in else";
}
echo "just";

我如何知道我正在接收数据,如何确保数据正在接收。
我是php新手,从未在android中使用过http类。
提前谢谢

  • 将这个JSONParser.java文件复制并粘贴到您的src文件夹中

  • 在您的android项目活动中编写以下代码

  • 公共类CreateDailyReports扩展了活动实现OnClickListener{

    EditText edRTitle,edRDesc;
    Button btnCreateReport;
    
    String userId,cmid;
    
    private ProgressDialog pdialog;
    
    // Creating JSON Parser object
    JSONParser jsonParser = new JSONParser();
    int success=0;
    
    private static String url_create_daily_reports = "";
    
    private static String url_send_message = "";
    
    
    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_daily_reports);
    
        initializeControls();
    
        btnCreateReport.setOnClickListener(this);
    
    
    
    }
    
    
    public void initializeControls(){
    
    
        edRTitle = (EditText)findViewById(R.id.editTextOfReportTitle);
        edRDesc = (EditText)findViewById(R.id.editTextOfReportDescription);
        btnCreateReport = (Button)findViewById(R.id.buttonOfCreateReport);
    
    
    
    }
    
    
    
    
    public class CreateDReports extends AsyncTask<String,String,String>
    {
    
    
        @Override
        protected void onPreExecute() 
        {
            // TODO Auto-generated method stub
            super.onPreExecute();
    
            pdialog = new ProgressDialog(CreateDailyReports.this);
            pdialog.setMessage("Wait... ");
            pdialog.setProgressStyle(android.R.style.Widget_ProgressBar_Small);
            pdialog.setIndeterminate(false);
            pdialog.setCancelable(false);
            pdialog.show();
        }
    
    
    
        @Override
        protected String doInBackground(String... args) 
        {
    
            String empid = userId;
            String sRtitle = edRTitle.getText().toString();
            String sRdesc = edRDesc.getText().toString();
    
    
    
            // Building Parameters
    
            List<NameValuePair> params = new ArrayList<NameValuePair>();
    
            params.add(new BasicNameValuePair("eid",empid));
            params.add(new BasicNameValuePair("rtitle",sRtitle));
            params.add(new BasicNameValuePair("rdesc",sRdesc));
            params.add(new BasicNameValuePair("cid",cmid));
    
    
            // getting JSON string from URL
            JSONObject json = jsonParser.makeHttpRequest(url_create_daily_reports, "POST", params);
    
                //Log.i("login", json.toString());
    
                try 
                {
                    // Checking for SUCCESS TAG
    
                    success = json.getInt("success");
    
    
    
    
                } 
                catch (JSONException e) 
                {
                    // TODO: handle exception
                    e.printStackTrace();
                }
    
                return null;
    
            } // doinbackground ends
    
    
    @Override
    protected void onPostExecute(String file_url) 
    {
        pdialog.dismiss();
    
    
            if(success==1){
    
            Toast myToast = Toast.makeText(CreateDailyReports.this, "Your Report has been Created", 10);
                  myToast.setGravity(Gravity.CENTER_HORIZONTAL, 0, 0);
                  myToast.show();   
    
                  new SendDailyReports().execute();
    
    
            }
            else
            {
                Toast myToast = Toast.makeText(CreateDailyReports.this, "Your Reprot has not been Created", 10);
                  myToast.setGravity(Gravity.CENTER_HORIZONTAL, 0, 0);
                  myToast.show();
    
            }
    
    
            }
    
        } // update status of product auction over
    
    
    
    
    @Override
    public void onClick(View v) {
    
        int id = v.getId();
    
        if(id==btnCreateReport.getId()){
    
    
    
            new CreateDReports().execute();
    
    
        }
    
    
    
      }
    

    ?>

    等待您的回复。提前谢谢。我的php代码正确吗?检查我的帖子,我已经编辑过了,它会将值插入到您的表中,然后将响应发送到json。不,您的php代码不对,因为它应该将json发送到您的android应用程序。我现在没有数据库。您能告诉我一种没有数据库的方法吗?一个还有一件事,是否有必要发送和接收JSon对象?如果没有数据库,您的数据将保存在哪里?是的,有必要发送和接收JSon对象,如果没有JSon,您就不能。如果您不想使用JSon,另一个选项是XML。
    EditText edRTitle,edRDesc;
    Button btnCreateReport;
    
    String userId,cmid;
    
    private ProgressDialog pdialog;
    
    // Creating JSON Parser object
    JSONParser jsonParser = new JSONParser();
    int success=0;
    
    private static String url_create_daily_reports = "";
    
    private static String url_send_message = "";
    
    
    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_daily_reports);
    
        initializeControls();
    
        btnCreateReport.setOnClickListener(this);
    
    
    
    }
    
    
    public void initializeControls(){
    
    
        edRTitle = (EditText)findViewById(R.id.editTextOfReportTitle);
        edRDesc = (EditText)findViewById(R.id.editTextOfReportDescription);
        btnCreateReport = (Button)findViewById(R.id.buttonOfCreateReport);
    
    
    
    }
    
    
    
    
    public class CreateDReports extends AsyncTask<String,String,String>
    {
    
    
        @Override
        protected void onPreExecute() 
        {
            // TODO Auto-generated method stub
            super.onPreExecute();
    
            pdialog = new ProgressDialog(CreateDailyReports.this);
            pdialog.setMessage("Wait... ");
            pdialog.setProgressStyle(android.R.style.Widget_ProgressBar_Small);
            pdialog.setIndeterminate(false);
            pdialog.setCancelable(false);
            pdialog.show();
        }
    
    
    
        @Override
        protected String doInBackground(String... args) 
        {
    
            String empid = userId;
            String sRtitle = edRTitle.getText().toString();
            String sRdesc = edRDesc.getText().toString();
    
    
    
            // Building Parameters
    
            List<NameValuePair> params = new ArrayList<NameValuePair>();
    
            params.add(new BasicNameValuePair("eid",empid));
            params.add(new BasicNameValuePair("rtitle",sRtitle));
            params.add(new BasicNameValuePair("rdesc",sRdesc));
            params.add(new BasicNameValuePair("cid",cmid));
    
    
            // getting JSON string from URL
            JSONObject json = jsonParser.makeHttpRequest(url_create_daily_reports, "POST", params);
    
                //Log.i("login", json.toString());
    
                try 
                {
                    // Checking for SUCCESS TAG
    
                    success = json.getInt("success");
    
    
    
    
                } 
                catch (JSONException e) 
                {
                    // TODO: handle exception
                    e.printStackTrace();
                }
    
                return null;
    
            } // doinbackground ends
    
    
    @Override
    protected void onPostExecute(String file_url) 
    {
        pdialog.dismiss();
    
    
            if(success==1){
    
            Toast myToast = Toast.makeText(CreateDailyReports.this, "Your Report has been Created", 10);
                  myToast.setGravity(Gravity.CENTER_HORIZONTAL, 0, 0);
                  myToast.show();   
    
                  new SendDailyReports().execute();
    
    
            }
            else
            {
                Toast myToast = Toast.makeText(CreateDailyReports.this, "Your Reprot has not been Created", 10);
                  myToast.setGravity(Gravity.CENTER_HORIZONTAL, 0, 0);
                  myToast.show();
    
            }
    
    
            }
    
        } // update status of product auction over
    
    
    
    
    @Override
    public void onClick(View v) {
    
        int id = v.getId();
    
        if(id==btnCreateReport.getId()){
    
    
    
            new CreateDReports().execute();
    
    
        }
    
    
    
      }
    
    <?php
    
    // connect to your database
    
    
    $result = mysql_query(" insert into table(field1,field2) values('$value1','$value2' )" );   
    if($result == 1)
    {
        // successfully inserted
        $response["success"] = 1;
        $response["message"] = "Product successfully created.";
    
        // echoing JSON response
        echo json_encode($response);
    }
    else
    {
        // failed to insert row
        $response["success"] = 0;
        $response["message"] = "Oops! An error occurred.";
    
        // echoing JSON response
        echo json_encode($response);
    
    }