【问题标题】:How to send data to php server and receive data in php server using POST and httpurl connection [closed]如何使用POST和httpurl连接将数据发送到php服务器并在php服务器中接收数据[关闭]
【发布时间】:2014-10-20 09:03:06
【问题描述】:

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

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

public class EventServiceHandler
{
    String data;
    DoSomething d = new DoSomething();

    public EventServiceHandler() {
    // TODO Auto-generated constructor stub
    d.execute();
}
public void getObject()
{   
    String s = "http://www.example.com/thisisthis.php";
    try {
        URL url = new URL(s);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");

        connection.setConnectTimeout(100000);
        connection.setReadTimeout(100000);
        connection.connect();

        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
        response=connection.getResponseCode();
        String name="sateesh";
        String testing=URLEncoder.encode("name", "utf-8")
                + "=" + URLEncoder.encode(name, "utf-8");
        out.write(testing);     
    } 
    catch (MalformedURLException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e)

    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } 

}

private  class DoSomething extends AsyncTask<Void, Void, Void>
{

    @Override
    protected Void doInBackground(Void... params)
    {
        // TODO Auto-generated method stub
        getObject();
        return 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 类。
提前致谢。

【问题讨论】:

  • 等待您的回复。提前致谢。

标签: php android httpurlconnection


【解决方案1】:
  1. 将此 JSONParser.java 文件复制并粘贴到您的 src 文件夹中

    json parser class

  2. 在您的 android 项目的活动中编写以下代码。

公共类 CreateDailyReports 扩展 Activity 实现 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();


    }



  }

} 3.php脚本

<?php

$value1 = $_REQUEST["rtitle"]; $value2 = $_REQUEST["rdesc"];

// 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);

}

?>

【讨论】:

  • 我的php代码对吗?
  • 查看我的帖子,我已编辑,它会将值插入您的表中,然后将响应发送到 json
  • 不,您的 php 代码不正确,因为它应该将 json 发送到您的 android 应用程序。
  • 什么是我现在没有数据库?你能告诉我没有数据库的方法吗?更重要的是,是否有必要发送和接收 JSon 对象?
  • 没有数据库,你的数据将保存在哪里?是的,有必要发送和接收 JSON 对象,没有 JSON 你不能。如果您不想使用 JSON,其他选项是 XML。
猜你喜欢
  • 2015-03-31
  • 2014-04-27
  • 1970-01-01
  • 1970-01-01
  • 2020-05-01
  • 2012-07-02
  • 1970-01-01
  • 2012-08-17
  • 2017-07-11
相关资源
最近更新 更多