繁体   English   中英

从Android向php发送对象

[英]Send object to php from Android

我是Android的新手,我想将一些变量从我的Android应用程序传递到php页面。 我使用了页面中的代码,并尝试使其适应我的需要,但是目前,变量未传递。 我想做的是ID为“ button_wp”的按钮激活功能“ run”。 我使用的代码如下:

Android XML

<Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Go to webpage"
        android:id="@+id/button_wp"
        android:onClick="wp" />

Android Java

public class Main3Activity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main3);

    }

public void wp(View v) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                OutputStream os = null;
                InputStream is = null;
                HttpURLConnection conn = null;
                try {
                    //constants
                    URL url = new URL("https://www.mypage.com/login_app.php");
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("precio", "5000€");
                    String message = jsonObject.toString();

                    conn = (HttpURLConnection) url.openConnection();
                    conn.setReadTimeout( 10000 /*milliseconds*/ );
                    conn.setConnectTimeout( 15000 /* milliseconds */ );
                    conn.setRequestMethod("POST");
                    conn.setDoInput(true);
                    conn.setDoOutput(true);
                    conn.setFixedLengthStreamingMode(message.getBytes().length);

                    //make some HTTP header nicety
                    conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
                    conn.setRequestProperty("X-Requested-With", "XMLHttpRequest");

                    //open
                    conn.connect();

                    //setup send
                    os = new BufferedOutputStream(conn.getOutputStream());
                    os.write(message.getBytes());
                    //clean up
                    os.flush();

                    //do somehting with response
                    is = conn.getInputStream();
                    //String contentAsString = readIt(is,len);
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                } finally {
                    //clean up
                    try {
                        os.close();
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    conn.disconnect();
                }
            }
        }).start();
    }
}

PHP

$json = file_get_contents('php://input');
$obj = json_decode($json);
$precio = $obj->{'precio'};

调试后的错误:

08-18 04:28:02.021 31463-31463/com.example.+++.+++W/dalvikvm: VFY: unable to resolve interface method 16209: Landroid/view/Window$Callback;.onProvideKeyboardShortcuts (Ljava/util/List;Landroid/view/Menu;I)V

08-18 04:28:02.021 31463-31463/com.example.+++.+++W/dalvikvm: VFY: unable to find class referenced in signature (Landroid/view/SearchEvent;)

08-18 04:28:02.021 31463-31463/com.example.+++.+++W/dalvikvm: VFY: unable to resolve interface method 16211: Landroid/view/Window$Callback;.onSearchRequested (Landroid/view/SearchEvent;)Z

08-18 04:28:02.021 31463-31463/com.example.+++.+++W/dalvikvm: VFY: unable to resolve interface method 16215: Landroid/view/Window$Callback;.onWindowStartingActionMode (Landroid/view/ActionMode$Callback;I)Landroid/view/ActionMode;

08-18 04:28:02.021 31463-31463/com.example.+++.+++W/dalvikvm: VFY: unable to resolve virtual method 532: Landroid/content/res/TypedArray;.getChangingConfigurations ()I

08-18 04:28:02.021 31463-31463/com.example.+++.+++W/dalvikvm: VFY: unable to resolve virtual method 554: Landroid/content/res/TypedArray;.getType (I)I

08-18 04:28:02.211 31463-31463/com.example.+++.+++W/dalvikvm: VFY: unable to resolve virtual method 16639: Landroid/widget/FrameLayout;.startActionModeForChild (Landroid/view/View;Landroid/view/ActionMode$Callback;I)Landroid/view/ActionMode;

08-18 04:28:02.271 31463-31463/com.example.+++.+++W/dalvikvm: VFY: unable to resolve virtual method 495: Landroid/content/res/Resources;.getDrawable (ILandroid/content/res/Resources$Theme;)Landroid/graphics/drawable/Drawable;

08-18 04:28:02.271 31463-31463/com.example.+++.+++W/dalvikvm: VFY: unable to resolve virtual method 497: Landroid/content/res/Resources;.getDrawableForDensity (IILandroid/content/res/Resources$Theme;)Landroid/graphics/drawable/Drawable;

08-18 04:28:02.271 31463-31463/com.example.+++.+++W/dalvikvm: VFY: unable to resolve virtual method 321: Landroid/content/Context;.getColorStateList (I)Landroid/content/res/ColorStateList;

08-18 04:28:02.651 31463-31463/com.example.+++.+++E/dalvikvm: Could not find class 'android.graphics.drawable.RippleDrawable', referenced from method android.support.v7.widget.AppCompatImageHelper.hasOverlappingRendering

08-18 04:28:02.651 31463-31463/com.example.+++.+++W/dalvikvm: VFY: unable to resolve instanceof 152 (Landroid/graphics/drawable/RippleDrawable;) in Landroid/support/v7/widget/AppCompatImageHelper;

08-18 04:35:38.731 31463-31463/com.example.+++.+++W/dalvikvm: VFY: unable to resolve virtual method 16912: Landroid/widget/Spinner;.getPopupContext ()Landroid/content/Context;

08-18 04:35:38.731 31463-31463/com.example.+++.+++E/dalvikvm: Could not find class 'android.widget.ThemedSpinnerAdapter', referenced from method android.support.v7.widget.AppCompatSpinner$DropDownAdapter.<init>

08-18 04:35:38.731 31463-31463/com.example.+++.+++W/dalvikvm: VFY: unable to resolve instanceof 2085 (Landroid/widget/ThemedSpinnerAdapter;) in Landroid/support/v7/widget/AppCompatSpinner$DropDownAdapter;

08-18 04:37:23.001 31463-31463/com.example.+++.+++W/dalvikvm: VFY: unable to resolve virtual method 196: Landroid/app/Notification$Builder;.setLocalOnly (Z)Landroid/app/Notification$Builder;

08-18 04:37:23.001 31463-31463/com.example.+++.+++W/dalvikvm: VFY: unable to resolve virtual method 453: Landroid/content/pm/PackageManager;.getPackageInstaller ()Landroid/content/pm/PackageInstaller;

08-18 04:37:32.901 31463-31463/com.example.+++.+++W/dalvikvm: method Landroid/support/v7/widget/ListViewCompat;.lookForSelectablePosition incorrectly overrides package-private method with same name in Landroid/widget/ListView;

08-18 04:37:32.901 31463-31463/com.example.+++.+++W/dalvikvm: VFY: unable to resolve virtual method 14245: Landroid/support/v7/widget/DropDownListView;.drawableHotspotChanged (FF)V

08-18 04:37:32.901 31463-31463/com.example.+++.+++W/dalvikvm: VFY: unable to resolve virtual method 15841: Landroid/view/View;.drawableHotspotChanged (FF)V

08-18 04:37:39.821 31463-31463/com.example.+++.+++W/InputEventReceiver: Attempted to finish an input event but the input event receiver has already been disposed.

感谢您的时间

如果我理解你的问题正确你想POST数据到PHP页面。 首先,我建议使用ASyncTask因为它比较容易理解,并且是在Android中运行后台任务的推荐方式。

要将数据发布到PHP页面,可以使用org.apache.http.client.methods.HttpPostorg.apache.http.client.*

在我的应用程序中,我是通过这种方式完成的,但是我不确定这是否是正确的处理方式。 这段代码是通用的,只是我对PHP脚本进行后请求的方式的实现。

class PostRequest extends ASyncTask<String, Void, String>{

    @Override
    protected String doInBackground(String... params){
        String data = "test data";

        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost("http://url.to.post.to");

        BasicNameValuePair dataPair = new BasicNameValuePair("data", data);

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

        nameValuePairList.add(dataPair);

        try{

            UrlEncodedFormEntity uefe = new UrlEncodedFormEntity(nameValuePairList);
            httpPost.setEntity(uefe);

            try {
                HttpResponse httpResponse = httpClient.execute(httpPost);

                InputStream inputStream = httpResponse.getEntitiy().getContent();


                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

                StringBuilder stringBuilder = new StringBuilder();

                String bufferedStrChunk = null;

                while((bufferedStrChunk = bufferedReader.readLine()) != null){
                    stringBuilder.append(bufferedStrChunk);
                }

                return stringBuilder.toString();

            } catch(ClientProtocolException cpe){
                Log.e("app", "Exception occurred: ", cpe);
            } catch(IOException e){
                Log.e("app", "Exception occurred: ", e);
            }
        } catch(UnsupportedEncodingException e){
            Log.e("app", "Exception occurred: ", e);
        }
        return null;
    }
}

PHP脚本位于url.to.post.to地方, data是必填的POST字段

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM