楼主心累呀,自己写了个项目玩都是get请求,还没玩过post,还要json参数。现在补充上来,坑都一个个填了
然后出现请求服务器一直404,各种找代码,各种看文档,各种走debug,最后发现是地址有问题。
“404,不是服务器问题么?”
此处省略一万字。。。。。
android kotlin retrofit https post请求json参数请求服务器 rxjava+retrofit2
1.配置环境
//配置Retrofit
compile 'com.google.code.gson:gson:2.2.4'
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
//rxjava+retrofit2
compile 'io.reactivex:rxjava:1.3.0'
compile 'io.reactivex:rxandroid:1.2.1'
compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
2.重点来了===上代码====
参数:{"service":"login","phoneNum":"17xxxxx2918"}
{
"service": "login",
"phoneNum": "17xxxxx2918"
}
val mMMService: MMMService
init {
val retrofit = Retrofit.Builder()
.baseUrl("http://192.168.18x.0x:8080/xxx/";)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build()
mMMService = retrofit.create(MMMService::class.java!!)
}
#封装json数据 方法1#
val parm = JSONObject()
parm.put("service", "login")
parm.put("phoneNum", phone)
val requestBody = RequestBody.create(MediaType.parse("application/json"),
parm.toString())
// val paramBody = RequestBody.create(MediaType.parse("application/json;charset=UTF-8"),
// parm.toString())//将参数包装成RequestBody
val phoneCode = mMMService.getPhoneCodes(requestBody)
phoneCode.enqueue(callback)
@Headers("Content-Type: application/json", "Accept: */*")//需要添加头
@POST("user.do")
fun getPhoneCodes(@Body route: RequestBody): Call //传入的参数为RequestBody
#封装json数据 创建bean 方法2#
class LogonNetBean(private val service: String, private val phoneNum: String){
override fun toString(): String {
return "LogonNetBean(service='$service', phone='$phoneNum')"
}
}
val bean = LogonNetBean("login", phone)
val toString = bean.toString()
Log.e("rexjava", "rexjava::" + toString)
val gson = Gson()
val route = gson.toJson(bean)//通过Gson将Bean转化为Json字符串形式
val paramBody = RequestBody.create(MediaType.parse("application/json;charset=UTF-8"),
route)//将参数包装成RequestBody
val phoneCode = mMMService.getPhoneCodes(paramBody)
phoneCode.enqueue(callback)
#附加第二种请求方法#
val bean = LogonNetBean("login", phone)
val gson = Gson()
val route = gson.toJson(bean)//通过Gson将Bean转化为Json字符串形式
val paramBody = RequestBody.create(MediaType.parse("application/json;charset=UTF-8"),
route)//将参数包装成RequestBody
val orderObservable: Observable = mMMService.getPhoneCodes(paramBody)
orderObservable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
.subscribe({
parserJson(it.status)
}, {
Log.e("rxjava", it.localizedMessage);
}, {
Log.e("rxjava", "onComplete!");
})
interface MMMService {
@Headers("Content-Type: application/json", "Accept: */*")//需要添加头
@POST("user.do")
fun getPhoneCodes(@Body route: RequestBody): Observable //传入的参数为RequestBody
}
val parm = JSONObject()
parm.put("service", "login")
parm.put("phoneNum", phone)
var gson = Gson();
val o = gson.fromJson(parm.toString(), Any::class.java)
val phoneCode = mMMService.getPhoneCodes(o)
phoneCode.enqueue(callback)
@Headers("Content-Type: application/json", "Accept: */*")//需要添加头
@POST("user.do")
fun getPhoneCodes(@Body route: Any): Call //传入的参数为RequestBody
val orderObservable: Observable = mMMService.getPhoneCodes("registerNote", phone)
orderObservable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
.subscribe({
parserJson(it.data)
}, {
Log.e("rxjava", it.localizedMessage);
}, {
Log.e("rxjava", "onComplete!");
})
@POST("user.do")
@FormUrlEncoded
fun getPhoneCodes(@Field("service") type: String,
@Field("phoneNum") version: String): Observable
interface MMMService {
//测试代码
@GET("home")
// fun getHomeInfo(): Call
fun getHomeInfo(): Observable
@Headers("Content-Type: application/json", "Accept: */*")//需要添加头
@POST("user.do")
fun getPhoneCode(@Body route: RequestBody): Call //传入的参数为RequestBody
}
abstract class NetPresenter(val activity: AppCompatActivity) {
val mMMService: MMMService
init {
val retrofit = Retrofit.Builder()
.baseUrl("http://192.168.18x.0x:8080/xxx/";)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build()
mMMService = retrofit.create(MMMService::class.java!!)
}
val callback = object : Callback {
override fun onResponse(call: Call?, response: Response?) {
Log.e("rxjava", "服务器code::" + response?.code())
if (response == null) {
Log.e("rxjava", "服务器没有成功返回")
} else {
if (response.isSuccessful) {
val body = response.body()
if (body.status == 0 || body.status == 203) {
val data = body.data
Log.e("rxjava", "data::" + data.toString());
parserJson(data, body.status)
} else {
Log.e("rxjava", "errormsg::" + body.errorMsg);
activity.toast("${body.status} :${body.errorMsg}")
}
} else {
Log.e("rxjava", "服务器代码错误")
}
}
}
override fun onFailure(call: Call?, t: Throwable?) {
//没有连上服务器
Log.e("home", "没有连接上服务器")
}
}
abstract fun parserJson(data: ResponseInfo.Data?, status: Int)