android 用于网络交互的方式

工具类:

package com.liu.http;


import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;

import static com.liu.http.MyHttpUtil11.doPost;

public class MyHttpUtil {


    private static final int TIMEOUT_IN_MILLIONS = 5000;

    public interface CallBack
    {
        void onRequestComplete(String result);
    }

   public static  void doGetAsyn(final String urlStr, final CallBack callBack){

                String result = doGet(urlStr);
                if (callBack != null)
                {
                    callBack.onRequestComplete(result);
                }
   }

    /**
     *  /GET 方式请求
     * @param urlStr
     * @return
     */
    public static String doGet(String urlStr){

        URL url = null;
        HttpURLConnection conn = null;
        InputStream is = null;
        ByteArrayOutputStream baos = null;

        try {
            url = new URL(urlStr);
            conn= (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(TIMEOUT_IN_MILLIONS);// 设置读取超时
            conn.setConnectTimeout(TIMEOUT_IN_MILLIONS);// 设置连接超时
            conn.setRequestMethod("GET");// 设置请求方式
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");

            if(conn.getResponseCode() ==  200){
                is = conn.getInputStream();
                baos = new ByteArrayOutputStream();
                int len = -1;
                byte[] buf = new byte[128];
                while ((len = is.read(buf)) != -1)
                {
                    baos.write(buf, 0, len);
                }
                baos.flush();
                return baos.toString();
            }else {
                throw new RuntimeException(" responseCode is not 200 ... ");
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally
        {
            try
            {
                if (is != null)
                    is.close();
            } catch (IOException e)
            {
            }
            try
            {
                if (baos != null)
                    baos.close();
            } catch (IOException e)
            {
            }
            conn.disconnect();
        }

        return null;
    }

    /**
     * 异步的Post请求
     * @param urlStr
     * @param params
     * @param callBack
     * @throws Exception
     */
    public static void doPostAsyn(final String urlStr, final String params,
                                  final CallBack callBack) throws Exception
    {
                try
                {
                    String result = doPost(urlStr, params);
                    if (callBack != null)
                    {
                        System.out.println("============tijiao===========");
                        callBack.onRequestComplete(result);
                    }
                } catch (Exception e)
                {
                    e.printStackTrace();
                }

}


    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url
     *   发送请求的 URL
     * @param jsonParam
     *   请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     * @throws Exception
     */
    public static String doPost(String url, String jsonParam)
    {
        DataOutputStream out=null;
        BufferedReader reader = null;
        StringBuffer result = new StringBuffer();

        try
        {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            HttpURLConnection conn = (HttpURLConnection) realUrl
                    .openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type",
//                    "application/x-www-form-urlencoded");
                    "application/json");
            conn.setRequestProperty("charset", "utf-8");
            conn.setUseCaches(false);
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setReadTimeout(TIMEOUT_IN_MILLIONS);
            conn.setConnectTimeout(TIMEOUT_IN_MILLIONS);


            //往服务器写数据
             out =new DataOutputStream(conn.getOutputStream());
             out.writeBytes(jsonParam);
             out.flush();
             out.close();

             reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String lines;
            while ((lines = reader.readLine()) != null) {
                lines = new String(lines.getBytes(), "utf-8");
                result.append(lines);
            }
            System.out.println(result);
            reader.close();
            // 断开连接
            conn.disconnect();

        } catch (Exception e)
        {
            e.printStackTrace();
        }
        // 使用finally块来关闭输出流、输入流
        finally
        {
            try
            {
                if (out != null)
                {
                    out.close();
                }
                if (reader != null)
                {
                    reader.close();
                }
            } catch (IOException ex)
            {
                ex.printStackTrace();
            }
        }
        return result.toString();
    }


}

后台程序:

package com.liu.android.controller;


import com.liu.android.model.User;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
public class LoginController {

    @RequestMapping("/login")
    public Map login(@RequestBody User user){
        Map<String ,Object > result = new HashMap<>();

        System.out.println(user.toString());

        result.put("code",200);
        result.put("msg","登录成功");

        return  result;

    }




}

测试类:

@Test
public void  postTest() throws Exception {
    MyHttpUtil.doPostAsyn("http://192.168.10.48:8080/login","{\n" +
            "\"userName\":\"zhangsan\",\n" +
            "\"password\":123\n" +
            "}",new MyHttpUtil.CallBack(){

        @Override
        public void onRequestComplete(String result) {
            System.out.println("================");
            System.out.println(result);
        }
    });
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-anKzg7kx-1584681826349)(C:\Users\Administrator\Desktop\error\json\1584681320823.png)]
在这里插入图片描述

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐