Android uses the Volley framework for data transmission

Table of contents

Pre-configuration

1. Import the package in the "build.gradle" file:

//导入Volley相关
    implementation 'com.mcxiaoke.volley:library:1.0.19'
    implementation 'androidx.localbroadcastmanager:localbroadcastmanager:1.0.0'

2. Add access network permission in "AndroidManifest":

<uses-permission android:name="android.permission.INTERNET" />

main code

/**
     * 函数功能:上传一条数据到服务器
     */
    public void UploadImage(Context mContext, final String Image) {
    
    
        Log.d("Record", "Uploading image...");
        //请求地址
        String url = "http://0.0.0.0:8080/ImageUpload/ImageServlet";
        String tag = "UploadImage";
        //取得请求队列
        RequestQueue requestQueue = Volley.newRequestQueue(mContext);
        //防止重复请求,所以先取消tag标识的请求队列
        requestQueue.cancelAll(tag);
        //创建StringRequest,定义字符串请求的请求方式为POST(省略第一个参数会默认为GET方式)
        final StringRequest request = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>() {
    
    
                    @Override
                    public void onResponse(String response) {
    
    
                        try {
    
    
                            JSONObject jsonObject = (JSONObject) new JSONObject(response).get("params");
                            String insertresult = jsonObject.getString("InsertResult");
                            if (insertresult.equals("success")) {
    
    
                                Log.d("Record", "Upload Success");
                                mTvChange.setText("上传成功");
                                //插入成功
                            } else {
    
    
                                Log.d("Record", "UpLoad Failed");
                                //插入失败
                            }
                        } catch (JSONException e) {
    
    
                            //请求异常
                            Log.d("Record", "UpLoad error:" + e);
                        }
                    }
                }, new Response.ErrorListener() {
    
    
            @Override
            public void onErrorResponse(VolleyError error) {
    
    
                //响应错误
                Log.e("Record", "插入错误:"+error.getMessage(), error);
            }
        }) {
    
    
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
    
    
                Map<String, String> params = new HashMap<>();
                params.put("Image", Image);
                return params;
            }
        };
        //设置Tag标签
        request.setTag(tag);
        //将请求添加到队列中
        requestQueue.add(request);
    }

Note:
1. "0.0.0.0:8080" is the domain name of the server, you can change it to your own domain name;
2. "/ImageUpload/ImageServlet" is the name of your server-side Web application, you can modify it according to your personal name ;
3. Note that Volley is executed asynchronously, so it is best not to use the method of setting the return value to proceed to the next step, which is prone to null pointer errors and other methods.
4. In higher Android versions, there may be a phenomenon of transmission error, because Http does not support plaintext transmission. The specific solution is in this article: Android uses the Volley
framework to display "Cleartext HTTP traffic to XXX not permitted" solution
———————————————————————————————
Finally, post my personal public account: WeChat search "Chaqian" or scan the picture below. Usually, some programming-related articles will be updated, and everyone is welcome to pay attention~
tea move

Guess you like

Origin blog.csdn.net/weixin_46269688/article/details/111308030