2013-03-08 2 views
0

현재 안드로이드 프로그래밍에 익숙해지기 위해 일부 코드를 테스트 중입니다. 여기에 몇 가지 testproject를 찾았습니다. http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/Android : GET works, POST doesnt

하지만 문제는 데이터베이스를 문제없이 읽을 수 있지만 POST만으로는 기능이 작동하지 않습니다. 그래서 내가 새로운 제품을 추가하려고하면 그것은 내 PHP 스크립트에 요청을하지만 전혀 POST 데이터가 없다. 나는이 방법으로 그것을 테스트했다.

<?php 
header("content-type:application/json; charset=UTF-8"); 
//print("fda"); 
/* 
* Following code will create a new product row 
* All product details are read from HTTP Post Request 
*/ 

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

// check for required fields 
//if (isset($_POST['name']) && isset($_POST['price']) && isset($_POST['description'])) { 
//if (isset($_POST['name'])){ 
    $name = "test";//$_POST['name']; 
    $price = 123; //$_POST['price']; 
    $description = "desc"; //$_POST['description']; 

foreach ($_POST as $key => $value) 
$data = $data." Field ".htmlspecialchars($key)." is ".htmlspecialchars($value); 
    // include db connect class 
//echo $data; 
$url = $_SERVER['REQUEST_URI']; 
    require_once __DIR__ . '/db_connect.php'; 

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

    // mysql inserting a new row 
    $result = mysql_query("INSERT INTO products(name, price, description, url) VALUES('$name', '$price', '$description','$data')"); 

    // check if row inserted or not 
    if ($result) { 
     // successfully inserted into database 
     $response["success"] = 1; 
     $response["message"] = "Product 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 데이터를 게시한다. 내 웹 기반 테스트 스크립트를 사용할 때 완벽하게 작동하며 데이터베이스에 POST 데이터를 표시합니다.

그래서 내 안드로이드 코드는 POST 데이터를 전송하는 것처럼 보입니다. 왜냐하면 제품을 추가 할 때 데이터베이스에 행을 추가하기 때문입니다.하지만 testvars 오프 코스를 추가하면됩니다. 문제는 내가 휴대 전화에서 실행할 때 데이터베이스의 마지막 필드 (URL 또는 더 나은 매개 변수)가 비어있게된다는 것입니다.

package com.example.androidhive; 

import java.io.IOException; 
import java.io.UnsupportedEncodingException; 
import java.util.ArrayList; 
import java.util.List; 

import org.apache.http.HttpResponse; 
import org.apache.http.NameValuePair; 
import org.apache.http.client.ClientProtocolException; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.entity.UrlEncodedFormEntity; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.http.message.BasicNameValuePair; 
import org.json.JSONException; 
import org.json.JSONObject; 

import android.app.Activity; 
import android.app.ProgressDialog; 
import android.content.Intent; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.View; 
import android.widget.Button; 
import android.widget.EditText; 

public class NewProductActivity extends Activity { 

    // Progress Dialog 
    private ProgressDialog pDialog; 

    JSONParser jsonParser = new JSONParser(); 
    EditText inputName; 
    EditText inputPrice; 
    EditText inputDesc; 

    // url to create new product 
    private static String url_create_product = "http://www.supergeilebus.nl/android_connect/create_product.php/"; 

    // JSON Node names 
    private static final String TAG_SUCCESS = "success"; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.add_product); 

     // Edit Text 
     inputName = (EditText) findViewById(R.id.inputName); 
     inputPrice = (EditText) findViewById(R.id.inputPrice); 
     inputDesc = (EditText) findViewById(R.id.inputDesc); 

     // Create button 
     Button btnCreateProduct = (Button) findViewById(R.id.btnCreateProduct); 

     // button click event 
     btnCreateProduct.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View view) { 
       // creating new product in background thread 
       new CreateNewProduct().execute(); 
      } 
     }); 
    } 

    /** 
    * Background Async Task to Create new product 
    * */ 
    class CreateNewProduct extends AsyncTask<String, String, String> { 
     /** 
     * Before starting background thread Show Progress Dialog 
     * */ 
     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      pDialog = new ProgressDialog(NewProductActivity.this); 
      pDialog.setMessage("Creating Product.."); 
      pDialog.setIndeterminate(false); 
      pDialog.setCancelable(true); 
      pDialog.show(); 
     } 

     /** 
     * Creating product 
     * */ 
     protected String doInBackground(String... args) { 
      String name = inputName.getText().toString(); 
      String price = inputPrice.getText().toString(); 
      String description = inputDesc.getText().toString(); 

      // Building Parameters 
      List<NameValuePair> params = new ArrayList<NameValuePair>(); 
      params.add(new BasicNameValuePair("name", name)); 
      params.add(new BasicNameValuePair("price", price)); 
      params.add(new BasicNameValuePair("description", description)); 

      // getting JSON Object 
      // Note that create product url accepts POST method 


      JSONObject json = jsonParser.makeHttpRequest(url_create_product,"POST", params); 
      // check log cat fro response 
      Log.d("Create Response", json.toString()); 

      // check for success tag 
      try { 
       int success = json.getInt(TAG_SUCCESS); 

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

        // closing this screen 
        finish(); 
       } else { 
        // failed to create product 
       } 
      } catch (JSONException e) { 
       e.printStackTrace(); 
      } 

      return null; 
     } 

     /** 
     * After completing background task Dismiss the progress dialog 
     * **/ 
     protected void onPostExecute(String file_url) { 
      // dismiss the dialog once done 
      pDialog.dismiss(); 
     } 

    } 
} 

나는 누군가가 나를 도울 수 있기를 바랍니다 : 여기에

은 안드로이드 응용 프로그램의 코드입니다. 나는 옵션이 없어. 내가 모든 것을 바꿀 때 완벽하게 작동합니다. 나는 그것이 SQL 인젝션 때문에 매우 가난하지만 단지 이것에 대해 배우고 싶어한다는 것을 안다.

접견 내 나쁜 영어

답변

0

안녕 사용자 죄송합니다 나는 웹 서비스에 게시물을 호출하는 코드를 다음 사용합니다. 너를 도울지도 모른다.

 

**public String doPost(Activity activity, String urlString, String method, String value) 
               throws ClientProtocolException, IOException 
    { 
     String responseString=""; 
     HttpURLConnection urlConnection = null; 
     retryCount++; 
     try 
     { 
      URL url = new URL(urlString+method); 
      urlConnection = (HttpURLConnection) url.openConnection(); 
      urlConnection.setRequestMethod("POST"); 
      urlConnection.setRequestProperty("Content-Type", "application/json"); 
      urlConnection.setRequestProperty("Content-Length",value.length()+""); 
      urlConnection.setDoInput(true); 
      urlConnection.setDoOutput(true); 
      DataOutputStream dos = new DataOutputStream(urlConnection.getOutputStream()); 
      byte[] bs = value.getBytes(); 
      Log.d(tag, "Sending JSON String ->"+new String(bs)); 
      dos.write(bs); 
      dos.flush(); 
      dos.close(); 
      Log.d(tag,"Responce ->"+urlConnection.getResponseMessage()); 
      if(urlConnection.getResponseMessage().toLowerCase().equals("ok")) 
      { 
       InputStream is = urlConnection.getInputStream(); 
       int ch; 
       StringBuffer b =new StringBuffer(); 
       while((ch = is.read()) != -1) 
       { 
        b.append((char)ch); 
       } 
       responseString = b.toString(); 
       Log.d(tag,method + "','" + responseString); 
       return method + "','" + responseString; 
      } 
      else 
      { 

       Log.d(tag, tag1+urlConnection.getResponseMessage()); 
      } 
      dos.close(); 
     } 
     catch (SocketException e) 
     { 

      Log.d(tag, tag1+e); 

    } 
     catch (Exception e) 
     { 

      Log.e(tag,"-->"+ e); 
     } 

     return ""; 
    }** 

여기 urlString 및 메서드는 웹 서비스 메서드의 전체 URL을 만듭니다.

+0

안녕하세요, thx는 나를 User (사용자)라고 부르겠습니다. 나는 그 이름을 알지 못했습니다. 하지만 주제로 돌아가 보았지만 실제로는 성공하지 못했습니다. 그것도 모든 POST 메시지를 보내는 것 같지 않습니다. 아마 어딘가에 여분의 파일을 가져올 필요가 있을까요? 어쩌면 그것은 잘못된 문장으로 보내질 수 있습니까? – LiquiDAciD

+0

안녕하세요 liquidacid, 유감스럽게도 사용자 bcoz에게 전화를 걸었습니다. 그것에 나는 json sting을 게시합니다. 이 호출을하기 위해 외부 파일이나 병이 필요하지 않습니다. –