post 方式上传json数据到服务器(基于okhttp3),并解析返回的json数据

直接上代码:
布局很简单,就是个Demo而已
activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
    <Button
        android:id="@+id/bt1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="查询用户配置"/>
    <Button
        android:id="@+id/bt2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="修改或插入用户单项配置"/>
    <Button
        android:id="@+id/bt3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="查询用户特别关心"/>
    <Button
        android:id="@+id/bt4"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="添加某人到特别关心"/>
    <Button
        android:id="@+id/bt5"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="把某人从特别关心中删除"/>

    <ScrollView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:textSize="18sp"
        />
    </ScrollView>

</LinearLayout>

MainActivity.java

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    private static final String TAG = "MainActivity";
    TextView responseText;
    Button checkAll;
    Button changeAndInsert;
    Button checkSpecial;
    Button insertSpecial;
    Button deleteSpecial;
    private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        responseText=(TextView)findViewById(R.id.text);
        checkAll=(Button)findViewById(R.id.bt1);
        changeAndInsert=(Button)findViewById(R.id.bt2);
        checkSpecial=(Button)findViewById(R.id.bt3);
        insertSpecial=(Button)findViewById(R.id.bt4);
        deleteSpecial=(Button)findViewById(R.id.bt5);
        checkAll.setOnClickListener(this);
        changeAndInsert.setOnClickListener(this);
        checkSpecial.setOnClickListener(this);
        insertSpecial.setOnClickListener(this);
        deleteSpecial.setOnClickListener(this);
    }

    public static class RequestType{  //请求类型后缀
        public static String CHECKALL="config/get";//查询用户配置
        public static String CHANGEANDINSERT="config/insert";//修改或者插入用户单项配置
        public static String CHECKSPECIAL="special/get";//查询用户特别关心
        public static String INSERTSPECIAL="special/insert";//添加特别关心
        public static String DELETESPECIAL="special/detele";//删除特别关心
    }
    @Override
    public void onClick(View v) {
        if (v.getId()==R.id.bt1){//按下按钮
            checkallRequest("http://www.xxxxxx.cn:8084/appdemo/"+RequestType.CHECKALL, new okhttp3.Callback() {
                @Override
                public void onFailure(okhttp3.Call call, IOException e) {
                    showResponse("请求失败");
                }

                @Override
                public void onResponse(okhttp3.Call call, Response response) throws IOException {
                    String responseData=response.body().string();
                    showResponse(responseData);
                    Gson gson=new Gson();
                   HttpBack data=gson.fromJson(responseData,HttpBack.class);
                    Log.e(TAG, "data0=="+data.getData().getList().get(0).getConfigValue() );//messageBell
                    Log.e(TAG, "data1=="+data.getData().getList().get(1).getConfigValue() );//messageReminding
                    Log.e(TAG, "data2=="+data.getData().getList().get(2).getConfigValue() );//music
                    Log.e(TAG, "data3=="+data.getData().getList().get(3).getConfigValue() );//navigation
                    Log.e(TAG, "data4=="+data.getData().getList().get(4).getConfigValue() );//receiverMode
                    Log.e(TAG, "data5=="+data.getData().getList().get(5).getConfigValue() );//voiceCode
                }
            });
        }
        if (v.getId()==R.id.bt2){//按下按钮
            changeAndInsertRequest("http://www.xxxxx.cn:8084/appdemo/"+RequestType.CHANGEANDINSERT, new okhttp3.Callback() {
                @Override
                public void onFailure(okhttp3.Call call, IOException e) {
                    showResponse("请求失败");
                }

                @Override
                public void onResponse(okhttp3.Call call, Response response) throws IOException {
                    String responseData = response.body().string();//返回的原始Json数据
                    showResponse(responseData);
                    JsonParser parser=new JsonParser();//Json解析
                    JsonObject jsonObject= (JsonObject)parser.parse(responseData);
                    Log.e(TAG, "返回信息=== "+jsonObject.get("msg"));
                }
            });
        }
        if (v.getId()==R.id.bt3){//按下按钮
            checkSpecialRequest("http://www.xxxxxx.cn:8084/appdemo/"+RequestType.CHECKSPECIAL, new okhttp3.Callback() {
                @Override
                public void onFailure(okhttp3.Call call, IOException e) {
                    showResponse("请求失败");
                }

                @Override
                public void onResponse(okhttp3.Call call, Response response) throws IOException {
                    String responseData = response.body().string();//返回的原始Json数据
                    showResponse(responseData);
                    Gson gson=new Gson();
                    CheckSpecial data=gson.fromJson(responseData,CheckSpecial.class);
                    if (data.getData().getList().size()>0 && data.getData().getList()!=null) {
                        for (int i = 0; i < data.getData().getList().size(); i++) {
                            Log.e(TAG, "返回信息=== " + data.getData().getList().get(i).getSpecialPrimarykey().getOtherPhone());//如果列表不为空
                        }
                    }else {
                        Log.e(TAG, " 没有特别关心的人");
                        Log.e(TAG, "List==="+data.getData().getList().size() );
                    }
                }
            });
        }
        if (v.getId()==R.id.bt4){//按下按钮
            insertSpecialRequest("http://www.xxxxxx.cn:8084/appdemo/"+RequestType.INSERTSPECIAL, new okhttp3.Callback() {
                @Override
                public void onFailure(okhttp3.Call call, IOException e) {
                    showResponse("请求失败");
                }

                @Override
                public void onResponse(okhttp3.Call call, Response response) throws IOException {
                    String responseData = response.body().string();//返回的原始Json数据
                    showResponse(responseData);
                    JsonParser parser=new JsonParser();//Json解析
                    JsonObject jsonObject= (JsonObject)parser.parse(responseData);
                    Log.e(TAG, "返回信息=== "+jsonObject.get("msg"));
                }
            });
        }
        if (v.getId()==R.id.bt5){//按下按钮
            deleteSpecialRequest("http://www.xxxxxx.cn:8084/appdemo/"+RequestType.DELETESPECIAL, new okhttp3.Callback() {
                @Override
                public void onFailure(okhttp3.Call call, IOException e) {
                    showResponse("请求失败");
                }

                @Override
                public void onResponse(okhttp3.Call call, Response response) throws IOException {
                    String responseData = response.body().string();//返回的原始Json数据
                    showResponse(responseData);
                    JsonParser parser=new JsonParser();//Json解析
                    JsonObject jsonObject= (JsonObject)parser.parse(responseData);
                    Log.e(TAG, "返回信息=== "+jsonObject.get("msg"));
                }
            });
        }


    }

    private void checkallRequest(String address,okhttp3.Callback callback){
        OkHttpClient client=new OkHttpClient();
        JsonObject obj=new JsonObject();
        JsonObject object=new JsonObject();
        obj.addProperty("phone","13411982971");//查询所有配置
        object.add("userConfigPrimarykey",obj);
        String jsonStr=object.toString();
        Log.e(TAG, "jsonStr== "+jsonStr);
        RequestBody requestBody=RequestBody.create(JSON,jsonStr);
        Request request=new Request.Builder()
                .url(address)
                .post(requestBody)
                .build();
        client.newCall(request).enqueue(callback);

    }
    private void changeAndInsertRequest(String address,okhttp3.Callback callback){
        OkHttpClient client=new OkHttpClient();
        JsonObject obj=new JsonObject();
        JsonObject object=new JsonObject();
        obj.addProperty("phone","13411982971");
        obj.addProperty("configName","messageReminding");
        object.add("userConfigPrimarykey",obj);
        object.addProperty("configValue","open");
        String jsonStr=object.toString();
        Log.e(TAG, "jsonStr== "+jsonStr);
        RequestBody requestBody=RequestBody.create(JSON,jsonStr);
        Request request=new Request.Builder()
                .url(address)
                .post(requestBody)
                .build();
        client.newCall(request).enqueue(callback);
    }
        private void checkSpecialRequest(String address,okhttp3.Callback callback){
            OkHttpClient client=new OkHttpClient();
            JsonObject obj=new JsonObject();
            JsonObject object=new JsonObject();
            obj.addProperty("phone","13411982971");//查询特别关心
            object.add("specialPrimarykey",obj);
            String jsonStr=object.toString();
            Log.e(TAG, "jsonStr== "+jsonStr);
            RequestBody requestBody=RequestBody.create(JSON,jsonStr);
            Request request=new Request.Builder()
                    .url(address)
                    .post(requestBody)
                    .build();
            client.newCall(request).enqueue(callback);
        }
        private void insertSpecialRequest(String address,okhttp3.Callback callback){
            OkHttpClient client=new OkHttpClient();
            JsonObject obj=new JsonObject();
            JsonObject object=new JsonObject();
            obj.addProperty("phone","13411982971");//增添特别关心
            obj.addProperty("otherPhone","14716006328");
            object.add("specialPrimarykey",obj);
            String jsonStr=object.toString();
            Log.e(TAG, "jsonStr== "+jsonStr);
            RequestBody requestBody=RequestBody.create(JSON,jsonStr);
            Request request=new Request.Builder()
                    .url(address)
                    .post(requestBody)
                    .build();
            client.newCall(request).enqueue(callback);
        }
    private void deleteSpecialRequest(String address,okhttp3.Callback callback){
        OkHttpClient client=new OkHttpClient();
        JsonObject obj=new JsonObject();
        JsonObject object=new JsonObject();
        obj.addProperty("phone","13411982971");//删除特别关心...跟添加特别关心一样的json数据
        obj.addProperty("otherPhone","14716006328");
        object.add("specialPrimarykey",obj);
        String jsonStr=object.toString();
        Log.e(TAG, "jsonStr== "+jsonStr);
        RequestBody requestBody=RequestBody.create(JSON,jsonStr);
        Request request=new Request.Builder()
                .url(address)
                .post(requestBody)
                .build();
        client.newCall(request).enqueue(callback);
    }
    /*
    **UI显示结果部分
     */
    private void showResponse(final String response){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                responseText.setText(response);
            }
        });
    }

}

其中上面的用gson来进行json解析的部分其实不用那么麻烦,我们可以不用知道哪个数据在list中具体编号i是多少,闭着眼睛都可以解析出我们要的值:
设编号为i;

for(int i=0;i<data.getData().getList().size();i++){
                        if (data.getData().getList().get(i).getUserConfigPrimarykey().getConfigName().equals("messageReminding")){
                            myInfoBean.setMessage_reminding(data.getData().getList().get(i).getConfigValue());
                        }
                        if (data.getData().getList().get(i).getUserConfigPrimarykey().getConfigName().equals("messageBell")){
                            myInfoBean.setMessage_bell(data.getData().getList().get(i).getConfigValue());
                        }
                        if (data.getData().getList().get(i).getUserConfigPrimarykey().getConfigName().equals("navigation")){
                            myInfoBean.setNavigation(data.getData().getList().get(i).getConfigValue());
                        }
                        if (data.getData().getList().get(i).getUserConfigPrimarykey().getConfigName().equals("music")){
                            myInfoBean.setMusic(data.getData().getList().get(i).getConfigValue());
                        }

                    }

看到if条件框了吗,就是判断list中哪个含有我们要的数据对应的键(参数名,ConfigName),如果找到了就把对应的参数值(ConfigValue)取出来

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值