• [android] Http Post 请求


    设置常量

    1 /**
    2 * 建立连接的超时值
    3 */
    4 public static final int HTTP_CONNECTION_TIMEOUT = 6 * 1000;
    5 /**
    6  * 读超时的超时值
    7 */
    8 public static final int HTTP_READ_TIMEOUT = 25 * 1000;
    9 public static final String UTF_8 = "UTF-8";
    httpPostRequest 函数

    1
    /** 2 * Http Post 请求 3 * 4 * @param requestUrl 5 * 请求地址 6 * @param postJson 7 * 上传数据 8 * @return 如果请求失败返回null 9 * @throws IOException 10 */ 11 public static String httpPostRequest(String requestUrl, String postJson) throws IOException { 12 URL url = new URL(requestUrl); 13 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 14 connection.setRequestMethod("POST"); 15 connection.setDoInput(true); 16 connection.setDoOutput(true); 17 connection.setUseCaches(false); 18 //设置连接超时时间 19 connection.setConnectTimeout(HTTP_CONNECTION_TIMEOUT); 20 //设置读超时的时间 21 connection.setReadTimeout(HTTP_READ_TIMEOUT); 22 connection.setRequestProperty("Charset", UTF_8); 23 connection.setRequestProperty("Connection", "keep-alive"); 24 connection.setRequestProperty("Content-Type", "application/json"); 25 26 connection.getOutputStream().write(postJson.getBytes()); 27 connection.getOutputStream().flush(); 28 connection.getOutputStream().close(); 29 30 String data = null; 31 if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { 32 InputStream inputStream = connection.getInputStream(); 33 data = new String(FileUtil.readStream(inputStream)); 34 } else { 35 Log.d(TAG, "Post Response Code : " + connection.getResponseCode()); 36 } 37 connection.disconnect(); 38 return data; 39 }
  • 相关阅读:
    Vue中关于路由传参query和params的区别
    网页从输入网址到渲染完成经历了哪些过程?
    http常见的状态码
    项目中遇到哪些难点,如何解决的
    vue双向绑定、Proxy、defineproperty
    Proxy相比于defineProperty的优势
    axios
    虚拟DOM
    vue、react、angular三大框架对比 && 与jQuery的对比
    DOS、DOS攻击、DDOS攻击、DRDOS攻击
  • 原文地址:https://www.cnblogs.com/dehua/p/3510693.html
Copyright © 2020-2023  润新知