gpt4 book ai didi

Android 应用程序与服务器发布通信

转载 作者:行者123 更新时间:2023-11-29 11:13:48 25 4
gpt4 key购买 nike

我最近发现了一个很棒的教程,将应用程序与 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方法

关于Android 应用程序与服务器发布通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40088695/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com