Android 应用发布与服务器的通信

Android app posting communication with server

我最近发现了一个很棒的教程,该教程将应用程序与 WAMP (http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/) 连接起来。问题是图书馆贬值了。因此,我开始尝试将我在那里学到的知识与推荐的 okHTTP 结合起来。我是 android 开发的这一部分的新手,无法弄清楚发生了什么,也找不到关于此事的任何好的文献。如有任何帮助,我们将不胜感激。

private static String url_create_product = "http://my_ip_address/create_product.php";

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



    name = (EditText) findViewById(R.id.name);
    price = (EditText) findViewById(R.id.price);
    description = (EditText) findViewById(R.id.descrption);
    created = (EditText) findViewById(R.id.created);
    updated = (EditText) findViewById(R.id.updated);

    submit = (Button) findViewById(R.id.submit);
    submit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            String test = testEntry(name.getText().toString(), price.getText().toString(), description.getText().toString());
            try{
                post(url_create_product, test);
            }catch (IOException e){

            }

        }
    });

}

String post(String url, String json) throws IOException {
    RequestBody body = RequestBody.create(JSON, json);
    Request request = new Request.Builder()
            .url(url)
            .post(body)
            .build();
    try (Response response = client.newCall(request).execute()){
        return response.body().string();
    }
}

String testEntry(String name, String price, String description){
    return "{'name' :" + name +
            "'price' :" +price +
            "'description' :" + description + "}";
}

}

为此您需要使用 Asynctask

private class AsyncCaller extends AsyncTask<Void, Void, Void>
{
@Override
protected void onPreExecute() {
    super.onPreExecute();

}
@Override
protected Void doInBackground(Void... params) {

    try{
            post(url_create_product, test);
        }catch (IOException e){

        }
    return null;
}

@Override
protected void onPostExecute(Void result) {
    super.onPostExecute(result);

}

}

并从 doInBackground

调用 post 方法