- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
我尝试使用 Retrofit 库在 Android 上使用 API 未成功,但在使用 POSTMAN 时,我可以看到预期的结果。
postman 设置
api url (base+controller)
HTTP 方法设置为 POST
点击了 from-data 或 x-www-form-urlencoded
然后我在键/值字段上传递两个参数。
安卓改造设置
@POST("/GetDetailWithMonthWithCode")
void getLandingPageReport(@Query("code") String code,
@Query("monthact") String monthact,
Callback<LandingPageReport> cb);
@FormUrlEncoded
@POST("/GetDetailWithMonthWithCode")
void getLandingPageReport(@Field("code") String code,
@Field("monthact") String monthact,
Callback<LandingPageReport> cb);
这些选项都不起作用。但结果是 {}。
更新
使用标准 HttpClient
进行相同设置(和 HttpPost
)类工作正常。
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("code", "testcode"));
urlParameters.add(new BasicNameValuePair("monthact", "feb-2015"));
post.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse response = client.execute(post);
为什么我不能执行这个请求并在 Retrofit 中得到正确的响应?
更新 2
@POST("/GetDetailWithMonthWithCode")
void getLandingPageReport(@Query("code") String code,
@Query("monthact") String monthact,
Callback<List<LandingPageReport>> cb);
@FormUrlEncoded
@POST("/GetDetailWithMonthWithCode")
void getLandingPageReport(@Field("code") String code,
@Field("monthact") String monthact,
Callback<List<LandingPageReport>>> cb);
玩了一圈之后,我想我找到了问题的根源。我已更新我的 retrofit 代码以接收 List<LandingPageReport>
.但是现在出现这个错误
retrofit.RetrofitError: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $
原因是我消耗了 2 个 api(webapi 和 wcf)。我所有的其他json
响应是对象数组。 [{},{}] 但在这次通话中我收到了这个
{
"GetDetailWithMonthWithCodeResult": [
{
"code": "test",
"field1": "test",
}
]
}
但我仍然无法解析响应。
最佳答案
compile 'com.google.code.gson:gson:2.6.2'
compile 'com.squareup.retrofit2:retrofit:2.1.0'// compulsory
compile 'com.squareup.retrofit2:converter-gson:2.1.0' //for retrofit conversion
登录API放两个参数
{
"UserId": "1234",
"Password":"1234"
}
登录响应
{
"UserId": "1234",
"FirstName": "Keshav",
"LastName": "Gera",
"ProfilePicture": "312.113.221.1/GEOMVCAPI/Files/1.500534651736E12p.jpg"
}
APIClient.java
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
class APIClient {
public static final String BASE_URL = "Your Base Url ";
private static Retrofit retrofit = null;
public static Retrofit getClient() {
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
APIInterface接口(interface)
interface APIInterface {
@POST("LoginController/Login")
Call<LoginResponse> createUser(@Body LoginResponse login);
}
登录Pojo
package pojos;
import com.google.gson.annotations.SerializedName;
public class LoginResponse {
@SerializedName("UserId")
public String UserId;
@SerializedName("FirstName")
public String FirstName;
@SerializedName("LastName")
public String LastName;
@SerializedName("ProfilePicture")
public String ProfilePicture;
@SerializedName("Password")
public String Password;
@SerializedName("ResponseCode")
public String ResponseCode;
@SerializedName("ResponseMessage")
public String ResponseMessage;
public LoginResponse(String UserId, String Password) {
this.UserId = UserId;
this.Password = Password;
}
public String getUserId() {
return UserId;
}
public String getFirstName() {
return FirstName;
}
public String getLastName() {
return LastName;
}
public String getProfilePicture() {
return ProfilePicture;
}
public String getResponseCode() {
return ResponseCode;
}
public String getResponseMessage() {
return ResponseMessage;
}
}
MainActivity
package com.keshav.retrofitloginexampleworkingkeshav;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import pojos.LoginResponse;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import utilites.CommonMethod;
public class MainActivity extends AppCompatActivity {
TextView responseText;
APIInterface apiInterface;
Button loginSub;
EditText et_Email;
EditText et_Pass;
private Dialog mDialog;
String userId;
String password;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
apiInterface = APIClient.getClient().create(APIInterface.class);
loginSub = (Button) findViewById(R.id.loginSub);
et_Email = (EditText) findViewById(R.id.edtEmail);
et_Pass = (EditText) findViewById(R.id.edtPass);
loginSub.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (checkValidation()) {
if (CommonMethod.isNetworkAvailable(MainActivity.this))
loginRetrofit2Api(userId, password);
else
CommonMethod.showAlert("Internet Connectivity Failure", MainActivity.this);
}
}
});
}
private void loginRetrofit2Api(String userId, String password) {
final LoginResponse login = new LoginResponse(userId, password);
Call<LoginResponse> call1 = apiInterface.createUser(login);
call1.enqueue(new Callback<LoginResponse>() {
@Override
public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
LoginResponse loginResponse = response.body();
Log.e("keshav", "loginResponse 1 --> " + loginResponse);
if (loginResponse != null) {
Log.e("keshav", "getUserId --> " + loginResponse.getUserId());
Log.e("keshav", "getFirstName --> " + loginResponse.getFirstName());
Log.e("keshav", "getLastName --> " + loginResponse.getLastName());
Log.e("keshav", "getProfilePicture --> " + loginResponse.getProfilePicture());
String responseCode = loginResponse.getResponseCode();
Log.e("keshav", "getResponseCode --> " + loginResponse.getResponseCode());
Log.e("keshav", "getResponseMessage --> " + loginResponse.getResponseMessage());
if (responseCode != null && responseCode.equals("404")) {
Toast.makeText(MainActivity.this, "Invalid Login Details \n Please try again", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Welcome " + loginResponse.getFirstName(), Toast.LENGTH_SHORT).show();
}
}
}
@Override
public void onFailure(Call<LoginResponse> call, Throwable t) {
Toast.makeText(getApplicationContext(), "onFailure called ", Toast.LENGTH_SHORT).show();
call.cancel();
}
});
}
public boolean checkValidation() {
userId = et_Email.getText().toString();
password = et_Pass.getText().toString();
Log.e("Keshav", "userId is -> " + userId);
Log.e("Keshav", "password is -> " + password);
if (et_Email.getText().toString().trim().equals("")) {
CommonMethod.showAlert("UserId Cannot be left blank", MainActivity.this);
return false;
} else if (et_Pass.getText().toString().trim().equals("")) {
CommonMethod.showAlert("password Cannot be left blank", MainActivity.this);
return false;
}
return true;
}
}
CommonMethod.java
public class CommonMethod {
public static final String DISPLAY_MESSAGE_ACTION =
"com.codecube.broking.gcm";
public static final String EXTRA_MESSAGE = "message";
public static boolean isNetworkAvailable(Context ctx) {
ConnectivityManager connectivityManager
= (ConnectivityManager)ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
public static void showAlert(String message, Activity context) {
final AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(message).setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
try {
builder.show();
} catch (Exception e) {
e.printStackTrace();
}
}
}
activity_main.xml
<LinearLayout android:layout_width="wrap_content"
android:layout_height="match_parent"
android:focusable="true"
android:focusableInTouchMode="true"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android">
<ImageView
android:id="@+id/imgLogin"
android:layout_width="200dp"
android:layout_height="150dp"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:padding="5dp"
android:background="@mipmap/ic_launcher_round"
/>
<TextView
android:id="@+id/txtLogo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/imgLogin"
android:layout_centerHorizontal="true"
android:text="Holostik Track and Trace"
android:textSize="20dp"
android:visibility="gone" />
<android.support.design.widget.TextInputLayout
android:id="@+id/textInputLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="@dimen/box_layout_margin_left"
android:layout_marginRight="@dimen/box_layout_margin_right"
android:layout_marginTop="8dp"
android:padding="@dimen/text_input_padding">
<EditText
android:id="@+id/edtEmail"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:ems="10"
android:fontFamily="sans-serif"
android:gravity="top"
android:hint="Login ID"
android:maxLines="10"
android:paddingLeft="@dimen/edit_input_padding"
android:paddingRight="@dimen/edit_input_padding"
android:paddingTop="@dimen/edit_input_padding"
android:singleLine="true"></EditText>
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="@+id/textInputLayout2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/textInputLayout1"
android:layout_marginLeft="@dimen/box_layout_margin_left"
android:layout_marginRight="@dimen/box_layout_margin_right"
android:padding="@dimen/text_input_padding">
<EditText
android:id="@+id/edtPass"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:focusable="true"
android:fontFamily="sans-serif"
android:hint="Password"
android:inputType="textPassword"
android:singleLine="true" />
</android.support.design.widget.TextInputLayout>
<RelativeLayout
android:id="@+id/rel12"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textInputLayout2"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp"
>
<Button
android:id="@+id/loginSub"
android:layout_width="wrap_content"
android:layout_height="45dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:background="@drawable/border_button"
android:paddingLeft="30dp"
android:paddingRight="30dp"
android:layout_marginRight="10dp"
android:text="Login"
android:textColor="#ffffff" />
</RelativeLayout>
</LinearLayout>
关于android - 使用 Retrofit 发送带有参数的 Post 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30180957/
我正在尝试迁移我的应用程序以使用 RxJava。我已经在使用 Retrofit,因此我正在尝试使用方法返回 Observables 的 Retrofit 接口(interface)。但是我现在在针对它
我想 post 数据如下: { "user_id":"14545646", "list":["4545645","4545645","4545645","4545645"]
我是改造新手。我向网站发出 POST 请求。网站以 HTML 形式返回响应。所以我会解析它。但是 Retrofit 尝试将其解析为 JSON。怎么办? @FormUrlEncoded @POST("/
我想异步执行 2 个网络调用 - 我正在使用 Retrofit+RxJava 来完成这个。这个逻辑来自一个简单的 Runner 类来测试解决方案。注意:这主要涉及服务器端的 RxJava。 我的代码如
我最近在改造的存储库中使用 Flow。 Result 的密封类 enum class ApiStatus{ SUCCESS, ERROR, LOADING } sealed c
我目前正在开发 Retrofit2 客户端的错误处理部分(使用 Retrofit 的 Rx 实现)。 找了一段时间,没有找到简单的方法将Retrofit返回的ResponseBody反序列化到我报错的
我从 retrofit 更新到 retrofit2 后出现此错误。 FATAL EXCEPTION: OkHttp Dispatcher Process: nz.co.datacom.mars.jun
在使用 RxJava 和 Retrofit 2 时,我正在尝试创建单元测试来覆盖我的应用何时收到特定响应。 我遇到的问题是,在 Retrofit 2 中,我看不到在不使用反射的情况下创建 retrof
在 Retrofit 1.9.x 中有一个 RetrofitError.Kind.NETWORK这让您可以轻松确定故障是否由网络错误引起。在新的 2.0 API 中,我们不再有 RetrofitErr
有没有办法用Refit动态输入参数? 我的 Refit 界面中有这段代码: [Get("/click?{parm}")] Task> SaveClick(string parm
有没有办法用Refit动态输入参数? 我的 Refit 界面中有这段代码: [Get("/click?{parm}")] Task> SaveClick(string parm
我知道,Retrofit 在内部使用 OkHttp。但是,我可以看到一些开发人员提供了以下方法的应用 return new Retrofit.Builder() .baseUrl(Bu
在项目上安装这个库之后: compile 'io.reactivex.rxjava2:rxandroid:2.0.1' compile 'io.reactivex.rxjava2:rxjava:2.0
在 Retrofit 1.x 中,我使用以下模式创建 API 服务类,该类模拟某些构建变体的不良网络连接。 // Retrofit 1 private T create(Class apiServi
Retrofit请求API格式(Android): @POST("getOrderStatus") @Headers("Content-Type:application/json") Obser
当我实例化 RestAdapter 时,我的应用程序总是崩溃 private void submitForm(SignupForm form){ RestAdapter adapter = n
我正要从 retrofit 1.9 迁移到最新版本并遇到问题... 我的设置: 三星 Galaxy S7 Edge(Android 7) 改造 2.3 OkHttp 3.8 迁移后突然遇到这个问题:
我正在尝试在 2.5.1-SNAPSHOT 中使用 retrofit 的协程支持,但我不断收到一个奇怪的异常。 我的改造服务类有: @GET("weather") suspend fun getFor
我正在尝试 Ktor通过转换一些当前正在使用的现有项目 Retrofit . 虽然我可以很容易地将请求转换为: client.get { url("$BASE_URL/something/so
使用改造 2,如何为上传的文件设置动态名称? 目前是这样的: @Part("avatar\"; filename=\"image\" ") RequestBody image, 但是,上传的文件名将是
我是一名优秀的程序员,十分优秀!