以下是我用来向PHP发送数据的方法
public String createUser(String url,String method,List<Pair<String, String>> params){
//Making Http request
HttpURLConnection httpURLConnection = null;
StringBuffer response = null;
String lineEnd = "\r\n";
try{
if(method.equals("POST")){
URL urlPost = new URL(url);
httpURLConnection = (HttpURLConnection) urlPost.openConnection();
httpURLConnection.setDoOutput(true); //defaults request method to POST
httpURLConnection.setDoInput(true); //allow input to this HttpURLConnection
httpURLConnection.setUseCaches(false);
httpURLConnection.setRequestMethod("POST");
//httpURLConnection.setRequestProperty("Content-Type","application/json");
//httpURLConnection.setRequestProperty("Host", "192.168.0.101");
httpURLConnection.connect();
DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
wr.writeBytes(params.toString());
//wr.writeBytes("user_email="+userEmailText);
//wr.writeBytes(lineEnd);
wr.flush(); //flush the stream when we're finished writing to make sure all bytes get to their destination
wr.close();
InputStream is = httpURLConnection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
}
} catch (ProtocolException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response.toString();
}
在我的AsyncTask类中:
params.add(new Pair<>("user_name", userNameText));
params.add(new Pair<>("user_email", userEmailText));
HttpHandler sh = new HttpHandler();
String jsonStrUserCreation = sh.createUser(url,"POST",params);
System.out.println("userNameText: " + userNameText);
System.out.println("userEmailText: " + userEmailText);
Log.e(TAG, "Response from userCreationURL: " + jsonStrUserCreation);
try{
JSONObject jsonObj = new JSONObject(jsonStrUserCreation);
} catch (JSONException e) {
e.printStackTrace();
}
以下是我的PHP代码:
<?php
require_once 'connecttodb.php';
$db = new DB();
$con = $db->db_connect();
if(isset($_POST['user_name']) && isset($_POST['user_email'])){
$user_name = $_POST['user_name'];
$user_email = $_POST['user_email'];
$sql = "INSERT INTO user_details(user_name,user_email) VALUES('$user_name','$user_email')";
$run = mysqli_query($con,$sql);
if($run){
$response["success"] = 1;
$response["message"] = "Account successfully created";
echo json_encode($response);
}else{
$response["success"] = 0;
$response["message"] = "Account failed to be created";
echo json_encode($response);
}
}else{
$response["success"] = 2;
$response["message"] = "Failed to run inner code";
echo json_encode($response);
}
脚本总是返回&#34;无法运行内码&#34;当我传入user_name和user_email的值时。
答案 0 :(得分:0)
找到解决方案如下。确保您的字符串采用以下格式
String urlParameters = "user_name="+userNameText+"&user_email="+userEmailText;
然后按以下方式调用它:
sh.createUser(url,urlParameters);
你会看到魔力。