2015-12-03 3 views
2

Я бы хотел использовать volley для отправки данных.Опубликовать данные с помощью volley php

Это мой PHP скрипт:

<?php header('Content-Type: application/json; charset=utf-8'); 

/* 
* Following code will update a product information 
* A product is identified by product id (pid) 
*/ 

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

// check for required fields 
if (isset($_POST['quotes_id']) && isset($_POST['quote']) && isset($_POST['uid']) && isset($_POST['imageName']) && isset($_POST['nameOfCreator'])) { 

    $quotes_id = $_POST['quotes_id']; 
    $quote = $_POST['quote']; 
    $uid = $_POST['uid']; 
    $imageName = $_POST['imageName']; 
    $nameOfCreator = $_POST['nameOfCreator']; 

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

    // connecting to db 
    $db = new DB_CONNECT(); 

    // mysql update row with matched pid 
    $result = mysql_query("INSERT INTO quotes SET quote = '$quote', uid = '$uid', imageName = '$imageName', nameOfCreator = '$nameOfCreator'"); 

    // check if row inserted or not 
    if ($result) { 
     // successfully updated 
     $response["success"] = 1; 
     $response["message"] = "Product successfully updated."; 

     // echoing JSON response 
     echo json_encode($response); 
    } else { 

    } 
} else { 
    // required field is missing 
    $response["success"] = 0; 
    $response["message"] = "Required field(s) is missing"; 

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

и следующий мой метод, который я назвал на кнопку мыши:

private void setData() { 
     Map<String, String> jsonParams = new HashMap<String, String>(); 
     jsonParams.put(StaticVariables.QUOTES_ID, null); 
     jsonParams.put(StaticVariables.QUOTE, "ööö"); 
     jsonParams.put(StaticVariables.UID, "112"); 
     jsonParams.put(StaticVariables.IMAGE_NAME, "112v1.jpg"); 
     jsonParams.put("nameOfCreator", "aa"); 

     JsonObjectRequest myRequest = new JsonObjectRequest(
       Request.Method.POST, 
       StaticVariables.url_insert_quote, 
       new JSONObject(jsonParams), 

       new Response.Listener<JSONObject>() { 
        @Override 
        public void onResponse(JSONObject response) { 
//      verificationSuccess(response); 
         Log.e("JA", "nice"); 
        } 
       }, 
       new Response.ErrorListener() { 
        @Override 
        public void onErrorResponse(VolleyError error) { 
//      verificationFailed(error); 
        } 
       }) { 

      @Override 
      public Map<String, String> getHeaders() throws AuthFailureError { 
       HashMap<String, String> headers = new HashMap<String, String>(); 
       headers.put("Content-Type", "application/json; charset=utf-8"); 
       headers.put("User-agent", "My useragent"); 
       return headers; 
      } 
     }; 
     AppController.getInstance().addToRequestQueue(myRequest, "tag"); 
    } 

Но ни одна строка не будет вставлена ​​в моей базе данных MySQL .. Кроме того, я установил INTERNET PERMISSION и все, что необходимо для подключения к Интернету.

+0

Сначала проверьте, если ваш код PHP правильно. Это может помочь: http://stackoverflow.com/questions/29442977/volley-jsonobjectrequest-post-parameters-no-longer-work – rafid059

+0

Да, что было полезно, спасибо, я проверил свой php-скрипт – fabiruu111

ответ

2

Попробуйте этот код он работал для меня в андроид приложение, и вы должны использовать другой URL, чтобы оставлять сообщения:

private void registerUser(){ 
     final String username = editTextUsername.getText().toString().trim(); 
     final String password = editTextPassword.getText().toString().trim(); 


     StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL, 
       new Response.Listener<String>() { 
        @Override 
        public void onResponse(String response) { 
         //do stuffs with response of post 
        } 
       }, 
       new Response.ErrorListener() { 
        @Override 
        public void onErrorResponse(VolleyError error) { 
         //do stuffs with response erroe 
        } 
       }){ 
      @Override 
      protected Map<String,String> getParams(){ 
       Map<String,String> params = new HashMap<String, String>(); 

       params.put(KEY_PASSWORD,password); 
       params.put(KEY_EMAIL, email); 
       return params; 
      } 

     }; 

     RequestQueue requestQueue = Volley.newRequestQueue(this); 
     requestQueue.add(stringRequest); 
    } 

Я не уверен, что с вами PHP-код, но выше андроид часть работ,

вы знаете, что у вас есть,

Добавить разрешение Интернет:

<uses-permission android:name="android.permission.INTERNET" /> 

Добавить залп в build.gradle:

compile 'com.mcxiaoke.volley:library:1.0.19' 

Благодаря

+0

Да, большое вам спасибо ! – fabiruu111

Смежные вопросы