我想从android向php发送一些数据并在php中进行一些操作。我的问题是我无法通过我的php文件发送数据。我想将rawJson发送到php。 请帮帮我,我该怎么做。我试过这种方式..
注册按钮
btnRegister.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
String name = inputFullName.getText().toString();
String phone = inputPhone.getText().toString();
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
String passwordrepeat = inputPasswordRepeat.getText().toString();
if (checkdata(name, phone, email, password, passwordrepeat))
{
RegistroSolicitud oUsuario = new RegiterRequest();
oUser.setName(name);
oUser.setEmail(email);
oUser.setPhone(phone);
oUser.setPassword(password);
Register(gson.toJson(oUser));
}
}
});
注册方法
private void Register(String rawJson) {
serviceAsyncService = new AsyncService(this, MyService.RegisterWebService, rawJson);
servicioAsyncService.setOnCompleteListener(new AsyncTaskListener() {
@Override
public void onTaskStart() {
}
@Override
public void onTaskDownloadedFinished(HashMap<String, Object> result) {
try {
int statusCode = Integer.parseInt(result.get("StatusCode").toString());
if (statusCode == 0) {
registerResult = gson.fromJson(result.get("Result").toString(), RegisterResult.class);
if ((!registerResult.isError()) && registerResult.getData() != null) {
userController.deleteAll();
userController.saveUser(registerResult.getData());
}
}
} catch (Exception error) {
}
}
@Override
public void onTaskUpdate(String result) {
}
@Override
public void onTaskComplete(HashMap<String, Object> result) {
}
@Override
public void onTaskCancelled(HashMap<String, Object> result) {
}
});
servicioAsyncService.execute();
}
AsyncService.java
public class ServicioAsyncService extends AsyncTask<String, String, HashMap<String, Object>> {
private static final String DEBUG_TAG = "Act";
private AsyncTaskListener asyncTaskListener;
private HashMap<String, Object> resultados;
private Context context;
private String servicioURL;
private String rawJson;
public ServicioAsyncService(Context prContext, String prUrl, String prRawJson) {
this.context = prContext;
this.servicioURL = prUrl;
this.rawJson = prRawJson;
resultados = new HashMap<String, Object>();
}
@Override
protected void onPreExecute() {
asyncTaskListener.onTaskStart();
super.onPreExecute();
}
@Override
protected HashMap<String, Object> doInBackground(String... params) {
disableConnectionReuseIfNecessary();
HttpURLConnection urlConnection = null;
try {
// create connection
//Thread.sleep(1000);
URL urlToRequest = new URL(servicioURL);
urlConnection = (HttpURLConnection)urlToRequest.openConnection();
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestMethod("POST");
if(rawJson != null) {
OutputStreamWriter osw = new OutputStreamWriter(urlConnection.getOutputStream());
osw.write(rawJson);
osw.flush();
osw.close();
}
// handle issues
int statusCode = urlConnection.getResponseCode();
if (statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
// handle unauthorized (if service requires user login)
} else if (statusCode != HttpURLConnection.HTTP_OK) {
// handle any other errors, like 404, 500,..
resultados.put("IsValid", false);
resultados.put("StatusCode", statusCode);
resultados.put("Resultado", null);
return resultados;
}
// create JSON object from content
InputStream in = new BufferedInputStream(
urlConnection.getInputStream());
String resultado = getResponseText(in);
resultados.put("IsValid", true);
resultados.put("StatusCode",0);
resultados.put("Resultado", resultado);
onTaskDownloadedFinished(resultados);
return resultados;
} catch (MalformedURLException e) {
// URL is invalid
resultados.put("IsValid", false);
resultados.put("Resultado", null);
resultados.put("StatusCode", 300);
} catch (SocketTimeoutException e) {
// data retrieval or connection timed out
resultados.put("IsValid", false);
resultados.put("Resultado", null);
resultados.put("StatusCode", 300);
} catch (IOException e) {
resultados.put("IsValid", false);
resultados.put("Resultado", null);
resultados.put("StatusCode", 300);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return resultados;
}
private static void disableConnectionReuseIfNecessary() {
// see HttpURLConnection API doc
if (Integer.parseInt(Build.VERSION.SDK)
< Build.VERSION_CODES.FROYO) {
System.setProperty("http.keepAlive", "false");
}
}
private static String getResponseText(InputStream inStream) {
String resultado = new Scanner(inStream).useDelimiter("\\A").next();
Log.d(DEBUG_TAG, resultado);
return resultado;
}
@Override
protected void onPostExecute(HashMap<String, Object> result) {
asyncTaskListener.onTaskComplete(result);
}
@Override
protected void onProgressUpdate(String... progress) {
super.onProgressUpdate(progress[0]);
asyncTaskListener.onTaskUpdate(progress[0]);
}
@SuppressLint("NewApi")
@Override
protected void onCancelled(HashMap<String, Object> result) {
asyncTaskListener.onTaskCancelled(null);
super.onCancelled(result);
}
public void setOnCompleteListener(AsyncTaskListener asyncTaskListener) {
this.asyncTaskListener = asyncTaskListener;
}
private void onTaskDownloadedFinished(HashMap<String, Object> result){
asyncTaskListener.onTaskDownloadedFinished(result);
}
}
Service.php
<?php
$json = $_REQUEST["rawJson"];
$user = json_decode($json);
$name = $user->Name;
$con=mysqli_connect("localhost","root","","db_users");
if (mysqli_connect_errno())
{
echo "fam_monitor_file(fam, filename)d to connect to MySQL: " . mysqli_connect_error();
}
else
{
//Insert in db
}
?>