【发布时间】:2020-03-06 15:05:12
【问题描述】:
我正在尝试使用 retrofit2 库从 android 应用程序发送数据(POST 请求)并在用 nodejs(使用 express 框架)编写的服务器上接收它,但我无法检索从应用程序。
我对 GsonConverterfactory 进行了改造,并向“/temp”路由发送了一个 POST 请求。
Index.js(处理路由请求):-
var express = require("express");
var bodyParser = require("body-parser");
var app = express();
app.use(bodyParser.urlencoded({extended:true}));
app.use('/public',express.static('public'));
app.post("/temp",function(req,res){
console.log(req.body);
obj = {
orgName : "Got the message ",
address : "on the server"
}
res.json(obj);
})
app.listen(8000,function(){
console.log("Server Started at port 8000");
})
Shop.java
package com.example.myapplication;
public class Shop {
private String orgName;
private String address;
public Shop(String orgName, String address) {
this.orgName = orgName;
this.address = address;
}
public String getOrgName() {
return orgName;
}
public String getAddress() {
return address;
}
}
ShopApi.java
package com.example.myapplication;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.POST;
public interface ShopApi {
@POST("temp")
Call<Shop> create(@Body Shop shop);
}
postData() - 从 MainActivity.java 发布数据的方法
public void postData(View view){
String BASE_URL = "http://10.0.2.2:8000/";
String org = orgName.getText().toString();
String address = add.getText().toString();
//Toast.makeText(getApplicationContext(),org+" "+address,Toast.LENGTH_SHORT).show();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
ShopApi shopApi = retrofit.create(ShopApi.class);
Shop shop = new Shop(org,address);
Call<Shop> shopCall = shopApi.create(shop);
shopCall.enqueue(new Callback<Shop>() {
@Override
public void onResponse(Call<Shop> call, Response<Shop> response) {
if(!response.isSuccessful()){
Toast.makeText(getApplicationContext(),response.code(),Toast.LENGTH_LONG).show();
}
Shop shopResponse = response.body();
String content = shopResponse.getOrgName() + shopResponse.getAddress();
Toast.makeText(getApplicationContext(),content,Toast.LENGTH_SHORT).show();
}
@Override
public void onFailure(Call<Shop> call, Throwable t) {
Toast.makeText(getApplicationContext(),t.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
req.body 中需要一个 json 对象,该对象应该在终端中打印,但会被打印出来:-
Server Started at port 8000
{}
请帮我检索服务器上的数据。
【问题讨论】:
标签: android node.js express retrofit2