使用参数改造后的请求 [英] Retrofit post request with parameters
问题描述
我正在使用邮递员扩展名进行邮寄请求.我想用android发出相同的请求.我使用改造库来访问我的目标.但是我无法获得成功的结果.我的代码错误在哪里?
I am using postman extension for post request. I want to make same request with android. I used retrofit library for access my goal. But I can't get successful result. Where is my mistake in code ?
邮递员:
我的界面:
public interface Interfacem {
@FormUrlEncoded
@POST("/login")
Call<ResponseBody> getResponse(@Field("signin[username]") String username,@Field("signin[password]")String password );
}
和改造用途:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://myurl.com")
.build();
Interfacem service = retrofit.create(Interfacem.class);
Call<ResponseBody> result =service.getResponse("myUsername","myPassword");
result.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Response<ResponseBody> response) {
try {
System.out.println(response.body().string().toString());
} catch (IOException|NullPointerException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Throwable t) {
t.printStackTrace();
}
});
推荐答案
如果使用的是 Retrofit 2.x
,请尝试如下更改Retrofit对象的版本:
if you are using Retrofit 2.x
, Try to change your build of Retrofit object as below :
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://myurl.com/")
.build();
也许下面的事情会有所帮助
maybe the things below will help
前导 /
会覆盖API端点定义的末尾.从部分网址中删除/
并将其添加到基本网址中将会带来预期的结果.
the leading /
within the partial url overrides the end of API endpoint definition. Removing the /
from the partial url and adding it to the base url will bring the expected result.
示例:
API接口
public interface UserService {
@POST("/me")
Call<User> me();}
使用 baseUrl
Build Retrofit
with baseUrl
Retrofit retrofit = Retrofit.Builder()
.baseUrl("https://your.api.url/v2");
.build();
然后致电:
UserService service = retrofit.create(UserService.class);
-> 请求网址将为 https://your.api.url/me
(/v2
已消失)
--> The request Url will be https://your.api.url/me
(/v2
has been disapear)
专业提示
使用相对URL作为部分终结点URL,并结束您的基本网址,后跟
/
.
界面
public interface UserService {
@POST("me")
Call<User>me();
}
使用baseURL进行改进
Retrofit retrofit = Retrofit.Builder()
.baseUrl("https://your.api.url/v2/");
.build();
致电
UserService service = retrofit.create(UserService.class);
-> 请求URL将为 https://your.api.url/v2/me
这篇关于使用参数改造后的请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!