zoukankan      html  css  js  c++  java
  • [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 }
  • 相关阅读:
    OTPUB知识课堂——VMware虚拟机应该如何优化
    春风十里,不如梭子鱼云安全解决方案全心为你!
    企业进行云存储,必须先搞清楚这5个问题
    OTPUB知识讲堂——如何在云计算中部署SQL
    Convertlab——营销的艺术,数字化的艺术
    腾讯云化解安全危机,开启网络安全智能时代
    11.2
    笔记
    this
    JS数据的基本类型
  • 原文地址:https://www.cnblogs.com/dehua/p/3510693.html
Copyright © 2011-2022 走看看