从Android应用程序发送请求到PHP并接收响应

时间:2014-05-14 11:58:33

标签: php android mysql httpresponse

所以我试图从Android应用程序发送一个请求(带有一个参数)到PHP文件,该文件从MySQL数据库中提取数据并需要将产品信息返回到Android应用程序。

Android应用程序有3个活动。 Main活动只显示一个按钮。单击此按钮,将启动一个新活动,该活动从后端提取产品数据(仅限品牌和型号)并显示它。单击一个,我需要向后端发送请求并提取特定于所选产品的数据。产品名称是主键。数据在PHP和Android应用程序之间以JSON格式发送。

以下是Android应用程序的代码,该应用程序仅发送一个特定产品的请求。

ViewProductActivity.class

public class ViewProductActivity extends Activity {

private ProgressDialog pDialog;

TextView make;
TextView model;
TextView type;

private String url_get = "http://10.0.1.57/pull_product.php?";

String make_get;
private static final String TAG_MAKE = "Make";
private static final String TAG_MODEL = "Model";
private static final String TAG_TYPE = "Type";

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.view_product);

    make = (TextView) findViewById(R.id.Make);
    model = (TextView) findViewById(R.id.Model);
    type = (TextView) findViewById(R.id.Type);

    Intent i = getIntent();

    make_get = i.getStringExtra(TAG_MAKE);

    new GetProductDetails().execute();

}

class GetProductDetails extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(ViewProductActivity.this);
        pDialog.setMessage("Loading Product details. Please wait...");
        pDialog.setIndeterminate(true);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    /**
     * Getting product details in background thread
     * */
    protected String doInBackground(String... params) {

        // updating UI from Background Thread
        runOnUiThread(new Runnable() {
            public void run() {
                // Building Parameters

                List<NameValuePair> params = new LinkedList<NameValuePair>();
                params.add(new BasicNameValuePair("make", make_get));
                String paramString = URLEncodedUtils.format(params,"utf-8");
                HttpClient client = new DefaultHttpClient();
                url_get+=paramString;
                HttpGet get = new HttpGet(url_get);
                HttpResponse response = null;
                //ResponseHandler<String> responseHandler = new BasicResponseHandler();
                try {
                    response = client.execute(get);
                } catch (ClientProtocolException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                JSONObject test = null;
                try {
                    test = new JSONObject(response.toString());
                } catch (JSONException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                Log.d("Single Product Details", test.toString());
                try {
                    make.setText(test.getString(TAG_MAKE));
                    model.setText(test.getString(TAG_MODEL));
                    type.setText(test.getString(TAG_TYPE));
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
        return null;
    }

    protected void onPostExecute(String file_url) {
        // dismiss the dialog once got all details
        pDialog.dismiss();
    }
}

}

我也粘贴了我的AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.test"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk android:minSdkVersion="8" 
          android:targetSdkVersion="19"/>

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

<application
    android:configChanges="keyboardHidden|orientation"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:allowBackup="true" android:enabled="true">

    <activity
        android:name="com.example.test.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <!-- All Products Activity -->
    <activity
        android:name="com.example.test.AllProductsActivity"
        android:label="All Products" >
    </activity>

    <activity
        android:name="com.example.test.ViewProductActivity"
        android:label="View Product Details">
    </activity>

</application>

<!--  Internet Permissions -->


</manifest>

和pull_product.php文件

<?php
  mysql_connect("127.0.0.1","root","admin");
  mysql_select_db("test");

  $product=mysql_real_escape_string($_GET["make"]);
  $query="SELECT * FROM products WHERE `Make` = '$product'";
  $q=mysql_query($query);
  $result = mysql_fetch_array($q);

        $product = array();
        $product["Make"] = $result["Make"];
        $product["Model"] = $result["Model"];
        $product["Type"] = $result["Type"];

  print(json_encode($product));
  mysql_close();
  ?>

这是我试图从

中提取的表格的示例

品牌型号类型价格
三星Galaxy S4手机50000
LG Nexus 5手机29000
Apple iPad 4平板电脑40000


这是我在LogCat中收到的错误消息:

05-14 18:05:19.001: D/AbsListView(19846): unregisterIRListener() is called 
05-14 18:05:19.026: D/AbsListView(19846): unregisterIRListener() is called 
05-14 18:05:19.031: E/ViewRootImpl(19846): sendUserActionProduct() mView == null
05-14 18:05:23.011: D/AbsListView(19846): unregisterIRListener() is called 
05-14 18:05:23.021: E/MoreInfoHPW_ViewGroup(19846): Parent view is not a TextView
05-14 18:05:23.086: D/ProgressBar(19846): updateDrawableBounds: left = 0
05-14 18:05:23.086: D/ProgressBar(19846): updateDrawableBounds: top = 0
05-14 18:05:23.086: D/ProgressBar(19846): updateDrawableBounds: right = 102
05-14 18:05:23.086: D/ProgressBar(19846): updateDrawableBounds: bottom = 102
05-14 18:05:23.126: I/System.out(19846): main calls detatch()
05-14 18:05:23.126: D/AndroidRuntime(19846): Shutting down VM
05-14 18:05:23.126: W/dalvikvm(19846): threadid=1: thread exiting with uncaught exception (group=0x418aec08)
05-14 18:05:23.131: E/AndroidRuntime(19846): FATAL EXCEPTION: main
05-14 18:05:23.131: E/AndroidRuntime(19846): Process: com.example.test, PID: 19846
05-14 18:05:23.131: E/AndroidRuntime(19846): android.os.NetworkOnMainThreadException
05-14 18:05:23.131: E/AndroidRuntime(19846):    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1156)
05-14 18:05:23.131: E/AndroidRuntime(19846):    at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
05-14 18:05:23.131: E/AndroidRuntime(19846):    at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
05-14 18:05:23.131: E/AndroidRuntime(19846):    at libcore.io.IoBridge.connect(IoBridge.java:112)
05-14 18:05:23.131: E/AndroidRuntime(19846):    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
05-14 18:05:23.131: E/AndroidRuntime(19846):    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
05-14 18:05:23.131: E/AndroidRuntime(19846):    at java.net.Socket.connect(Socket.java:843)
05-14 18:05:23.131: E/AndroidRuntime(19846):    at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
05-14 18:05:23.131: E/AndroidRuntime(19846):    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:165)
05-14 18:05:23.131: E/AndroidRuntime(19846):    at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:167)
05-14 18:05:23.131: E/AndroidRuntime(19846):    at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:125)
05-14 18:05:23.131: E/AndroidRuntime(19846):    at org.apache.http.impl.client.DefaultRequestDirector.executeOriginal(DefaultRequestDirector.java:1179)
05-14 18:05:23.131: E/AndroidRuntime(19846):    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:644)
05-14 18:05:23.131: E/AndroidRuntime(19846):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
05-14 18:05:23.131: E/AndroidRuntime(19846):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
05-14 18:05:23.131: E/AndroidRuntime(19846):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
05-14 18:05:23.131: E/AndroidRuntime(19846):    at com.example.test.ViewProductActivity$GetProductDetails$1.run(ViewProductActivity.java:112)
05-14 18:05:23.131: E/AndroidRuntime(19846):    at android.os.Handler.handleCallback(Handler.java:733)
05-14 18:05:23.131: E/AndroidRuntime(19846):    at android.os.Handler.dispatchMessage(Handler.java:95)
05-14 18:05:23.131: E/AndroidRuntime(19846):    at android.os.Looper.loop(Looper.java:157)
05-14 18:05:23.131: E/AndroidRuntime(19846):    at android.app.ActivityThread.main(ActivityThread.java:5356)
05-14 18:05:23.131: E/AndroidRuntime(19846):    at java.lang.reflect.Method.invokeNative(Native Method)
05-14 18:05:23.131: E/AndroidRuntime(19846):    at java.lang.reflect.Method.invoke(Method.java:515)
05-14 18:05:23.131: E/AndroidRuntime(19846):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
05-14 18:05:23.131: E/AndroidRuntime(19846):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
05-14 18:05:23.131: E/AndroidRuntime(19846):    at dalvik.system.NativeStart.main(Native Method)
05-14 18:05:25.521: W/ApplicationPackageManager(20272): getCSCPackageItemText()

05-14 18:05:25.556: E/MoreInfoHPW_ViewGroup(20272): Parent view is not a TextView
你能告诉我我做错了什么吗? URL形成正常,但不会通过对PHP文件的请求。

非常感谢!

1 个答案:

答案 0 :(得分:0)

要摆脱module.my_bucket.aws_s3_bucket_policy.bucket_policy: id = my-bucket bucket = my-bucket policy = { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "AWS": "arn:aws:iam::____________:user/srv_my-bucket" }, "Action": [ "s3:*" ], "Resource": [ "arn:aws:s3:::my-bucket", "arn:aws:s3:::my-bucket/*" ] } ] } 异常,请从android.os.NetworkOnMainThreadException方法中删除调用runOnUiThread()方法:

doInBackground(String... params)

如果要更新UI,请使用protected JSONObject doInBackground(String... params) { List<NameValuePair> params = new LinkedList<NameValuePair>(); params.add(new BasicNameValuePair("make", make_get)); String paramString = URLEncodedUtils.format(params,"utf-8"); HttpClient client = new DefaultHttpClient(); url_get+=paramString; HttpGet get = new HttpGet(url_get); HttpResponse response = null; //ResponseHandler<String> responseHandler = new BasicResponseHandler(); try { response = client.execute(get); } catch (ClientProtocolException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } JSONObject test = null; try { test = new JSONObject(response.toString()); } catch (JSONException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } Log.d("Single Product Details", test.toString()); return test; } 方法:

onPostExecute