2014-10-20 179 views
-2

我正在製作一個應用程序,並在該應用程序中,我需要發送數據到php服務器和接收數據在php服務器,反之亦然。我無法將數據從android應用程序發送到php服務器?你能告訴我該怎麼做嗎?

這是我發送數據到服務器的代碼。

如何發送數據到php服務器和使用POST和httpurl連接在php服務器接收數據

public class EventServiceHandler 
{ 
    String data; 
    DoSomething d = new DoSomething(); 

    public EventServiceHandler() { 
    // TODO Auto-generated constructor stub 
    d.execute(); 
} 
public void getObject() 
{ 
    String s = "http://www.example.com/thisisthis.php"; 
    try { 
     URL url = new URL(s); 
     HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
     connection.setDoInput(true); 
     connection.setDoOutput(true); 
     connection.setRequestMethod("POST"); 

     connection.setConnectTimeout(100000); 
     connection.setReadTimeout(100000); 
     connection.connect(); 

     OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream()); 
     response=connection.getResponseCode(); 
     String name="sateesh"; 
     String testing=URLEncoder.encode("name", "utf-8") 
       + "=" + URLEncoder.encode(name, "utf-8"); 
     out.write(testing);  
    } 
    catch (MalformedURLException e) 
    { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (IOException e) 

    { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

} 

private class DoSomething extends AsyncTask<Void, Void, Void> 
{ 

    @Override 
    protected Void doInBackground(Void... params) 
    { 
     // TODO Auto-generated method stub 
     getObject(); 
     return null; 
    } 
} 

}

這是PHP服務器上的代碼用於在服務器上接收數據。

<?php 

if($_POST) 
{ 
    $name = urldecode($_POST['name']); 
    echo $name; 
    error_log($name,0); 
    echo " ok"; 
} 

else if(is_null($_POST) OR empty($_POST)) 
{ 
    error_log("empty or null",0); 
    echo "in else if"; 

} 

else 
{ 
    echo "<br>"; 
    echo "in else"; 
} 
echo "just"; 

?>

我知道我在接收數據時,我如何確保正在接收的數據怎麼辦。
我是新來的PHP,並從未在android中使用過http類。
在此先感謝。

+0

等待你的答覆。提前致謝。 – Sateesh 2014-10-20 09:26:13

回答

1
  1. 複製並粘貼JSONParser.java文件到您的src文件夾

    json parser class

  2. 下面寫在你的Android項目的活動代碼。

公共類CreateDailyReports延伸活動實現OnClickListener {

EditText edRTitle,edRDesc; 
Button btnCreateReport; 

String userId,cmid; 

private ProgressDialog pdialog; 

// Creating JSON Parser object 
JSONParser jsonParser = new JSONParser(); 
int success=0; 

private static String url_create_daily_reports = ""; 

private static String url_send_message = ""; 


@SuppressLint("NewApi") 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_create_daily_reports); 

    initializeControls(); 

    btnCreateReport.setOnClickListener(this); 



} 


public void initializeControls(){ 


    edRTitle = (EditText)findViewById(R.id.editTextOfReportTitle); 
    edRDesc = (EditText)findViewById(R.id.editTextOfReportDescription); 
    btnCreateReport = (Button)findViewById(R.id.buttonOfCreateReport); 



} 




public class CreateDReports extends AsyncTask<String,String,String> 
{ 


    @Override 
    protected void onPreExecute() 
    { 
     // TODO Auto-generated method stub 
     super.onPreExecute(); 

     pdialog = new ProgressDialog(CreateDailyReports.this); 
     pdialog.setMessage("Wait... "); 
     pdialog.setProgressStyle(android.R.style.Widget_ProgressBar_Small); 
     pdialog.setIndeterminate(false); 
     pdialog.setCancelable(false); 
     pdialog.show(); 
    } 



    @Override 
    protected String doInBackground(String... args) 
    { 

     String empid = userId; 
     String sRtitle = edRTitle.getText().toString(); 
     String sRdesc = edRDesc.getText().toString(); 



     // Building Parameters 

     List<NameValuePair> params = new ArrayList<NameValuePair>(); 

     params.add(new BasicNameValuePair("eid",empid)); 
     params.add(new BasicNameValuePair("rtitle",sRtitle)); 
     params.add(new BasicNameValuePair("rdesc",sRdesc)); 
     params.add(new BasicNameValuePair("cid",cmid)); 


     // getting JSON string from URL 
     JSONObject json = jsonParser.makeHttpRequest(url_create_daily_reports, "POST", params); 

      //Log.i("login", json.toString()); 

      try 
      { 
       // Checking for SUCCESS TAG 

       success = json.getInt("success"); 




      } 
      catch (JSONException e) 
      { 
       // TODO: handle exception 
       e.printStackTrace(); 
      } 

      return null; 

     } // doinbackground ends 


@Override 
protected void onPostExecute(String file_url) 
{ 
    pdialog.dismiss(); 


     if(success==1){ 

     Toast myToast = Toast.makeText(CreateDailyReports.this, "Your Report has been Created", 10); 
       myToast.setGravity(Gravity.CENTER_HORIZONTAL, 0, 0); 
       myToast.show(); 

       new SendDailyReports().execute(); 


     } 
     else 
     { 
      Toast myToast = Toast.makeText(CreateDailyReports.this, "Your Reprot has not been Created", 10); 
       myToast.setGravity(Gravity.CENTER_HORIZONTAL, 0, 0); 
       myToast.show(); 

     } 


     } 

    } // update status of product auction over 




@Override 
public void onClick(View v) { 

    int id = v.getId(); 

    if(id==btnCreateReport.getId()){ 



     new CreateDReports().execute(); 


    } 



    } 

} 3. PHP腳本

<?php 

$值1 = $ _REQUEST [ 「rtitle」]; $ value2 = $ _REQUEST [「rdesc」];

// connect to your database 


$result = mysql_query(" insert into table(field1,field2) values('$value1','$value2')"); 
if($result == 1) 
{ 
    // successfully inserted 
    $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); 

} 

?>

+0

我在php上的代碼是正確的嗎? – Sateesh 2014-10-20 09:27:30

+0

檢查我的文章,我已編輯,它會插入值到您的表,然後將響應發送到json – 2014-10-20 09:31:10

+0

和不,你的php代碼是不正確的,因爲它應該發送json到你的android應用程序。 – 2014-10-20 09:32:30

相關問題