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 }
  • 相关阅读:
    JAVA Shallow heap & Retained heap
    JAVA-堆区,栈区,方法区。
    Android经典的设计模式
    Android 绘制view的小知识点
    Android View的滑动 动画
    Android开发aidl使用中linkToDeath和unlinkToDeath的使用
    Android任务栈的运行规律
    Android 通过httppost上传文本文件到服务器。
    Android中的Libraries以及Order and Export的使用。
    drawable微技巧以及layout的小知识
  • 原文地址:https://www.cnblogs.com/dehua/p/3510693.html
Copyright © 2011-2022 走看看