Xutils请求网络数据

时间:2022-04-30 02:42:13
package com.bwie.xutils;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

public void btnGet(View view) {

xutilsGet("http://japi.juhe.cn/health_knowledge/categoryList?key=eb033dfcf95c03f9f451f6973049e6be");

}

public void btnPost(View view) {
xutilsPost("http://japi.juhe.cn/health_knowledge/categoryList");
}

public void xutilsGet(String url) {
HttpUtils utils = new HttpUtils();
utils.send(HttpRequest.HttpMethod.GET, url, new RequestCallBack<String>() {

@Override
public void onStart() {
super.onStart();
//开始的时候 做一些加载进度条的
}

@Override
public void onCancelled() {
super.onCancelled();
//取消加载的
}

@Override
public void onSuccess(ResponseInfo<String> responseInfo) {
Toast.makeText(MainActivity.this, "success" + responseInfo.result.toString(), Toast.LENGTH_SHORT).show();
}

@Override
public void onFailure(HttpException e, String s) {
Toast.makeText(MainActivity.this, "fail", Toast.LENGTH_SHORT).show();

}
});
}

public void xutilsPost(String url) {
HttpUtils utils = new HttpUtils();
RequestParams params = new RequestParams();
//别忘了把params放进去
params.addQueryStringParameter("key", "eb033dfcf95c03f9f451f6973049e6be");
utils.send(HttpRequest.HttpMethod.POST, url, params,new RequestCallBack<String>() {
@Override
public void onSuccess(ResponseInfo<String> responseInfo) {

Toast.makeText(MainActivity.this, "success" + responseInfo.result.toString(), Toast.LENGTH_SHORT).show();

}

@Override
public void onFailure(HttpException e, String s) {

}
});

}
}