Android异步线程OkHttp Post请求Json数据并解析

package com.wpl.http;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {
    private Button btn1;

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

    private void initUI() {
        btn1 = (Button) findViewById(R.id.login);
        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                login();
            }
        });
    }

    private void login() {
        new GetDataTask().execute();
    }

    private class GetDataTask extends AsyncTask {
        @Override
        protected String doInBackground(Void... params) {
            String result = null;
            OkHttpClient client = new OkHttpClient();
            FormBody.Builder builder = new FormBody.Builder();
            builder.add("name", "123");
            builder.add("password", "123");

            RequestBody body = builder.build();
            Request request = new Request.Builder()
                    .url("http://211.149.239.137:8080/user/loginPhone")
                    .post(body)
                    .build();
            Response response = null;
            try {
                response = client.newCall(request).execute();
                result = response.body().string();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return result;
        }

        @Override
        protected void onPostExecute(String s) {
            Log.e("result", "" + s);
            try {
                JSONObject jsonObject = new JSONObject(s);
                Log.e("key",""+jsonObject.get("key"));
            } catch (JSONException e) {
                e.printStackTrace();
            }
            super.onPostExecute(s);
        }
    }
}

你可能感兴趣的:(JAVA,Android)