gpt4 book ai didi

php - 将 $_POST ['whatever' 的参数发送到 PHP 文件时出现问题

转载 作者:行者123 更新时间:2023-11-28 23:13:50 25 4
gpt4 key购买 nike

我正在尝试将 POST 发送到文件 php 以在 mysql 数据库中插入一些值。当我发送参数时, if($_POST['nombre']){...} 收到带有空值的 $_POST。我卡住了。这是代码

JSONParse.java

public class JSONParser {

HttpURLConnection urlConnection= null;
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

public JSONParser() {

}

public JSONObject makeHttpRequest(String url, String method, ContentValues params) {

try {
if(method == "POST"){
URL url1= new URL(url);
urlConnection=(HttpURLConnection) url1.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.connect();
is = urlConnection.getInputStream();
}else if(method == "GET"){
url += "?" + params;
URL url1= new URL(url);
urlConnection=(HttpURLConnection) url1.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
is = urlConnection.getInputStream();
}

} catch (UnsupportedEncodingException 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 {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}

return jObj;

}
}

AltaUserFragment.java`

public class AltaUserFragment extends Fragment {

private ProgressDialog pDialog;

private static final String TAG_SUCCESS = "success";
private static final String TAG_USERS = "usuarios";
private static final String TAG_USER = "usuario";
private static final String TAG_CONTRA = "contrasena";

JSONArray users = null;
private ContentValues params;

JSONParser jParser = new JSONParser();

private static String url_alta_user = "https://serverhost/android/create_user.php";

public AltaUserFragment() {
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_alta_user, container, false);
Button btnAlta = (Button) view.findViewById(R.id.btnAltaUser);
btnAlta.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new AltaUsario().execute();
}
});
return view;
}

class AltaUsario extends AsyncTask<String, String, String> {

TextView txtNombre = (TextView) getView().findViewById(R.id.txtNombre);
TextView txtUsuario = (TextView) getView().findViewById(R.id.txtUsuario);
TextView txtEmail = (TextView) getView().findViewById(R.id.txtEmail);
TextView txtContra1 = (TextView) getView().findViewById(R.id.txtContra1);
TextView txtContra2 = (TextView) getView().findViewById(R.id.txtContra2);

String nombre = txtNombre.getText().toString();
String usuario = txtUsuario.getText().toString();
String email = txtEmail.getText().toString();
String contra1 = txtContra1.getText().toString();
String contra2 = txtContra2.getText().toString();

@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Checking user. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}

@Override
protected String doInBackground(String... strings) {
params = new ContentValues();
params.put("nombre",nombre );
params.put("usuario",usuario );
params.put("contrasena", contra1 );
params.put("email",email);

JSONObject json = jParser.makeHttpRequest(url_alta_user, "POST", params);

try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);

if (success == 1) {
// successfully created product
Intent i = new Intent(getContext(), MainActivity.class);
startActivity(i);

// closing this screen
getActivity().getSupportFragmentManager().popBackStack();

} else {

}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}

protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
}
`

create_user.php

<?php

/*
* Following code will create a new product row
* All product details are read from HTTP Post Request
*/

// array for JSON response
$response = array();

// include db connect class
require_once __DIR__ . '/db_connect.php';

// connecting to db
$con = new DB_CONNECT();
$con->connect();

// check for required fields
if (isset($_POST['nombre']) && isset($_POST['usuario']) && isset($_POST['contrasena']) && isset($_POST['email'])) {

$nombre = $_POST['nombre'];
$usuario = $_POST['usuario'];
$contrasena = $_POST['contrasena'];
$email = $_POST['email'];

// mysql inserting a new row
$result = mysqli_query($con->myconn, "INSERT INTO users(nombre, usuario, contrasena, email) VALUES('$nombre', '$usuario', '$contrasena', '$email')");

// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "User 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);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";

// echoing JSON response
echo json_encode($response);
}
?>

最佳答案

我对“POST”有同样的问题。您应该考虑使用 volley 库 https://developer.android.com/training/volley/index.html ,我认为它可以解决你的问题。在您的应用程序 gradle 中添加所需的依赖项并在单击按钮时使用 volley 方法

insert.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
final String feedback = feed.getText().toString();
if(feedback.equals("")){
Toast.makeText(getBaseContext(),"please fill all fields",Toast.LENGTH_SHORT).show();

}

final ProgressDialog loading =
ProgressDialog.show(feedbackPage.this, "Setting up connection...", null, true, true);
//delay insertion by x sec so that course code can be properly fetched
mhandler.postDelayed(new Runnable() {
@Override
public void run() {
if(loading.isShowing())
loading.dismiss();
StringRequest request = new StringRequest(Request.Method.POST, insert_url,
new Response.Listener<String>() {

@Override
public void onResponse(String response) {

dialog.setTitle("Server Response");
dialog.setMessage(response);
dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {

feed.setText("");
}
});
AlertDialog alert = dialog.create();
alert.show();
}
}
, new Response.ErrorListener() {

@Override
public void onErrorResponse(VolleyError error) {

Toast.makeText(feedbackPage.this, "error...." + error.toString()
, Toast.LENGTH_SHORT).show();
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {

Map<String, String> params = new HashMap<String, String>();
params.put("uid", uid);
params.put("name", userName);
params.put("feed", feedback);
return params;
}
};

request.setRetryPolicy(new DefaultRetryPolicy(3000, 5,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

Singleton.getInstance(feedbackPage.this).addTorequestqueue(request);
}
},3000);
}
});

您需要一个单例类来获取返回的请求队列:

public class Singleton {

private static Singleton single_instance;
private RequestQueue queue;
private static Context ctx;

private Singleton(Context ctx){
this.ctx=ctx;
queue = getQueue();
}

public static synchronized Singleton getInstance( Context ctx){
if(single_instance == null){
single_instance = new Singleton(ctx);
}
return single_instance;

}

public RequestQueue getQueue(){
if(queue==null){
queue = Volley.newRequestQueue(ctx.getApplicationContext());
return queue;
}

return queue;
}

public <T>void addTorequestqueue(Request<T> request){
queue.add(request);
}

你可以更好地理解它:https://www.youtube.com/watch?v=FL37oah1k8k

希望对您有所帮助!

关于php - 将 $_POST ['whatever' 的参数发送到 PHP 文件时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44775193/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com