无法在Android中向服务器发送数据

时间:2017-08-18 06:24:54

标签: java php database server

我是Android新手。不知道哪个部分出了问题。问题是我无法将数据发送到Android Studio中的服务器。

这是我面临的错误

  

致命错误:未捕获错误:在C:\ xampp \ htdocs \ students \ connection.php中调用未定义函数mysql_connect():6堆栈跟踪:#0 C:\ xampp \ htdocs \ students \ add_employee.php(2 ):在第6行的C:\ xampp \ htdocs \ students \ connection.php中抛出include()#1 {main}

代码就是这样......

主要活动

public class MainActivity extends AppCompatActivity  {

Button b1;
EditText e1;
private ProgressDialog pDialog;
private JSONObject json;
private int success=0;
private HTTPURLConnection service;
private String strname ="";
//Initialize webservice URL
private String path = "http://localhost/student/add_employee.php";





@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    b1 = (Button) findViewById(R.id.button);
    e1 = (EditText) findViewById(R.id.editText9);

    service=new HTTPURLConnection();


    b1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!e1.getText().toString().equals("") ) {
                strname = e1.getText().toString();

                //Call WebService
                new PostDataTOServer().execute();
            } else {
                Toast.makeText(getApplicationContext(), "Please Enter all fields", Toast.LENGTH_LONG).show();
            }


            Intent intent = new Intent(MainActivity.this, Student1.class);
            startActivity(intent);

    }
});
}

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

String response = "";
//Create hashmap Object to send parameters to web service
HashMap<String, String> postDataParams;
@Override
protected void onPreExecute() {
    super.onPreExecute();

    pDialog = new ProgressDialog(MainActivity.this);
    pDialog.setMessage("Please wait...");
    pDialog.setCancelable(false);
    pDialog.show();
}
@Override
protected Void doInBackground(Void... arg0) {
    postDataParams=new HashMap<String, String>();
    postDataParams.put("name", strname);

    //Call ServerData() method to call webservice and store result in response
    response= service.ServerData(path,postDataParams);
    try {
        json = new JSONObject(response);
        //Get Values from JSONobject
        System.out.println("success=" + json.get("success"));
        success = json.getInt("success");

    } catch (JSONException e) {
        e.printStackTrace();
    }
    return null;
}
@Override
protected void onPostExecute(Void result) {
    super.onPostExecute(result);
    if (pDialog.isShowing())
        pDialog.dismiss();
    if(success==1) {
        Toast.makeText(getApplicationContext(), "Employee Added successfully..!", Toast.LENGTH_LONG).show();
    }
}
}
}

HttpURLConnection类

public class HTTPURLConnection {
String response="";
URL url;
public String ServerData(String path,HashMap<String, String> params) {
    try {
        url = new URL(path);

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(15000);
        conn.setConnectTimeout(15000);
        conn.setRequestMethod("POST");
        conn.setDoInput(true);
        conn.setDoOutput(true);


        OutputStream os = conn.getOutputStream();
        BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(os, "UTF-8"));
        writer.write(getPostDataString(params));

        writer.flush();
        writer.close();
        os.close();
        int responseCode = conn.getResponseCode();

        if (responseCode == HttpsURLConnection.HTTP_OK) {
            String line;
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            //Log.d("Output",br.toString());
            while ((line = br.readLine()) != null) {
                response += line;
                Log.d("output lines", line);
            }
        } else {
            response = "";
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return response;
}

private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
    StringBuilder result = new StringBuilder();
    boolean first = true;
    for(Map.Entry<String, String> entry : params.entrySet()){
        if (first)
            first = false;
        else
            result.append("&");

        result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
        result.append("=");
        result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
    }

    return result.toString();
}}

我的PHP代码

add_employee.php

<?php
include('connection.php');
$emp_name=$_POST["name"];
$success=0;
$status="Active";
$sql = "INSERT INTO  `employee` (`emp_name`) 
VALUES ('$emp_name')";
if(mysql_query($sql))
{
$success=1;
}
$response["success"]=$success;
die(json_encode($response));
mysql_close($con);
?>

connection.php

<?php
 $dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);    
if(!$conn) {
    die('Could not connect: ' . mysql_error());
}
mysql_select_db('student');
?>

0 个答案:

没有答案