Android第九讲——网络(六)xUtils

xUtils
需要导包。xUtils-2.6.14.jar
.result是返回的结果 GET POST

public class XUtilsActivity extends AppCompatActivity implements View.OnClickListener {
    //使用注解去除findViewById
    @ViewInject(R.id.button_xutils_get)
    private Button mBtnXUtilsGet;
    @ViewInject(R.id.textview_xutils)
    private TextView mTextView;
    @ViewInject(R.id.button_xutils_post)
    private Button mBtnXUtilsPost;

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

        ViewUtils.inject(this);//用注解去除findViewById后必须调用此方法
    }

    @OnClick({R.id.button_xutils_get, R.id.button_xutils_post})//注册点击事件(放在方法外边)

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button_xutils_get:
                utilDoGet();
                break;
            case R.id.button_xutils_post:
                utilsDoPost();
                break;
            default:
                break;
        }
    }

    /**
     * 用Post方法提交服务器
     */
    private void utilsDoPost() {
        HttpUtils utils_Post = new HttpUtils();
        RequestParams params = new RequestParams();//添加提交参数
        params.addBodyParameter("username", "『唐』↹『人』");
        utils_Post.send(HttpRequest.HttpMethod.POST, "http://192.168.***.*:8080/HTTpTest_Servelet/ServeletTest", params, new RequestCallBack() {
            @Override
            public void onSuccess(ResponseInfo responseInfo) {
                mTextView.setText(responseInfo.result);//responseInfo.result表示返回的结果
            }

            @Override
            public void onFailure(HttpException e, String s) {
                mTextView.setText("网络连接错误");
            }
        });
    }

    /**
     * 用Get方法向服务器提交数据
     */
    private void utilDoGet() {
        HttpUtils utils_Get = new HttpUtils();
        utils_Get.send(HttpRequest.HttpMethod.GET, "http://192.168.***.*:8080/HTTpTest_Servelet/ServeletTest?username=Queue", new RequestCallBack() {
            @Override
            public void onSuccess(ResponseInfo responseInfo) {
                mTextView.setText(responseInfo.result);//responseInfo.result表示返回的结果
            }

            @Override
            public void onFailure(HttpException e, String s) {
                mTextView.setText("网络连接错误");
            }
        });
    }
}

你可能感兴趣的:(Android)