我是一个刚开始编程不久的初学者。 我刚刚开始使用 Java 和 Android studio,并且陷入了一个需要从 http 服务器发送和接收数据的项目中。 有人告诉我,Retrofit 是可行的方法,但我无法接收数据(老实说,我不知道从哪里开始)。
但是,我实现了向服务器发送数据(一个字符串和一个整数),这是我使用的代码。
我为我的错误和如此缺乏经验而道歉。提前致谢。
改造:https://square.github.io/retrofit/
主要
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
Button button = (Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final TextView hora = (TextView) findViewById(R.id.hora);
final int sharehora = Integer.valueOf(hora.getText().toString());
final TextView missatge = (TextView) findViewById(R.id.text);
final String shareMissatge = missatge.getText().toString();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://www.google.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();
CostumBody costumBody = new CostumBody();
costumBody.setMsg(shareMissatge);
costumBody.setTime(sharehora);
giapi service = retrofit.create(giapi.class);
service.Calltomyserver(costumBody);
}
});
}
catch(Exception ex){
Log.e("error!", String.valueOf(ex.getMessage()));
}
}
}
GIAPI
public interface giapi {
@POST("/")
Call<Void> Calltomyserver (@Body CostumBody user);
}
客户主体
public class CostumBody {
public String msg;
public int time;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public int getTime() {
return time;
}
public void setTime(int time) {
this.time = time;
}
}
最佳答案
好吧,我用的是 Volley ,说实话我不知道为什么。但无论如何我都会帮忙!安装 volley 非常简单,只需添加
compile 'com.mcxiaoke.volley:library-aar:1.0.0'
到您的应用程序 gradle。那么您想从数据库中检索数据吗?并将数据发送到数据库?
step 1
设置您的服务器和数据库
创建一个 php 文件以将您想要的任何内容发送到数据库。
step 2
将数据库转换为json。 你可以找到一个很好的教程here!
step 3
你需要通过你的android项目解析json。 如果你想打印到 ListView ,你可以找到教程/示例 here 如果您只想存储数据,只需将解析到 ListView 的行取出即可! ...
好的...
要将数据发送到数据库,请按照以下视频操作:
How to Connect Android with PHP, MySQL - Best Android Studio Tutorial.
(YouTube)...
希望这有帮助!
关于java - 使用 Retrofit 从服务器接收数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39938034/