【发布时间】:2020-05-04 18:49:13
【问题描述】:
我正在尝试使用 Retrofit rest 客户端在 android 中使用用 asp.net core 2.2 编写的 web api。成功从 Api 获取数据,但无法使用 Retrofit 将数据发布到服务器。 webapi 通过邮递员和 Javascript 运行良好。
以下是我尝试过的..
我的活动课
private Retrofit retrofit = new Retrofit.Builder().baseUrl("https://sga.somee.com/api/")
.addConverterFactory(ScalarsConverterFactory.create()).addConverterFactory(GsonConverterFactory.create()).build();
private ShopApi _shopsApi;
//constructor
public MainActivity2(){
//api classes must be initialized in constructors
_shopsApi = retrofit.create(ShopApi.class);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Shop _shop = new Shop();
_shop.shop_name = "Starbucks";
_shop.shop_owner = "Unknown";
_shop.shop_longitude = 49545.3455;
_shop.shop_latitude = 55353.554;
_shop.shop_image = "path/path.png";
PostShop(_shop);
}
public void PostShop(Shop shop){
/*
JsonObject obj = new JsonObject();
obj.addProperty("shop_name",shop.shop_name);
obj.addProperty("shop_owner",shop.shop_owner);
obj.addProperty("shop_longitude",shop.shop_longitude);
obj.addProperty("shop_latitude",shop.shop_latitude);
obj.addProperty("shop_image",shop.shop_image);
Log.d(TAG, obj.toString());
*/
Call<ResponseBody> AddShop = _shopsApi.AddShop(shop);
AddShop.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
Toast.makeText(MainActivity2.this,response.raw().body().toString(),Toast.LENGTH_LONG).show();
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(MainActivity2.this,"Failded to add new shop",Toast.LENGTH_LONG).show();
}
});
}
我的 ShopApi 类
package com.example.madee.sga.API;
import com.example.madee.sga.Models.Shop;
import java.util.List;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.Headers;
import retrofit2.http.POST;
import retrofit2.http.Path;
public interface ShopApi {
@GET("Shops/GetAll/{page}")
Call<List<Shop>> GetAllShops(@Path("page") int page );
@Headers({"Content-Type: application/json"})
@POST("Shops/AddNew")
Call<ResponseBody> AddShop(@Body Shop _shop);
}
您还可以看到,我也尝试在 MainActivity 中使用 JsonObject 发布数据,但同样失败 400 Bad Requset
【问题讨论】:
标签: android retrofit retrofit2 webapi