HttpURLConnection ----GET请求 和 POST请求:

你想要了解HttpUrlConnection吗?
------------了解一个httpUrlConnection请求的顺序:

[TOC]

-带着问题你看我的文章,理解起来会简单许多!

1. 怎么获取HttpURLConnection呢?为什么要拿它?
2. HttpURLConnection要配置那些信息?
3. 基本参数怎么上传,文件怎么上传?
4. 发送请求之后怎么接受请求返回的信息?
5. 请求可能碰到的问题,可能的编码问题!


### 一 . 获取HttpURLConnection ------getHttpURLConnection ``` //url_path是访问的地址 URL url = new URL(url_path); //这里用URL获取URLConnection,因为没有构造方法 URLConnection urlConnection = url.openConnection(); //转成HttpURLConnection因为该类的方法多 HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection; ```
### 二 . 配置 ------HttpURLConnectionConfig
   httpURLConnection.setDoOutput(doOutPut); //设置是否向httpUrlConnection输出,post请求,参数要放在http正文内,因此需要设为true, 默认情况下是false;
   httpURLConnection.setDoInput(doInPut);   // 设置是否从httpUrlConnection读入,默认情况下是true;
   httpURLConnection.setUseCaches(useCache);  // Post 请求不能使用缓存
   httpURLConnection.setRequestMethod(method);    //请求的方法:默认是GET请求
   httpURLConnection.setRequestProperty("Charsert", "UTF-8"); //设置编码为UTF-8
   // 设置内容类型
   httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" +BOUNDARY);
   httpURLConnection.setConnectTimeout(6000);    //连接 1 min  超时
   httpURLConnection.setReadTimeout(6000);     //读取 1 min  超时
   httpURLConnection.connect(); //向URL发送连接,getOutputStream()方法中

### 三 . 基本参数的上传-------- get_Param / post_Param

(1)get请求参数上传(因为get上传参数是可见的,传送的信息大小也有限制,所以我这里就写基本的GET请求)

	setUrl(url+"?"+get_Param(param));   //直接读取上传的Map,拼接到URL后面,get_param 方法在后面文件中有!
	

(2) post请求参数上传 (正版的表单上传,有基本数据,有文件上传(包含图片哟))

httpURLConnection.getOutputStream()   //拿到这个stream才能将参数传出去

os=new DataOutputStream(httpURLConnection.getOutputStream());  //这只是一种例子,不一定是DataOutputStream

//普通参数的格式规范
			StringBuilder sb= new StringBuilder();
            sb.append("--" + BOUNDARY + "\r\n");
            sb.append("Content-Disposition: form-data; name=\""+name+"\"\r\n");
            sb.append("\r\n");
            sb.append(value);
            sb.append("\r\n");
            System.out.print(sb.toString());     //展示请求报文
            os.write(sb.toString().getBytes("UTF-8"));

//文件参数的格式规范
			StringBuilder sb=new StringBuilder();
            sb.append("--" + BOUNDARY + "\r\n");
	        sb.append("Content-Disposition: form-data; name=\"" + name + "\"; filename=\"" +      value.getName()+"\"");
            sb.append("\r\n");
            sb.append("Content-Type: " + getContentType(value) + "\r\n");
            sb.append("\r\n");
            os.write(sb.toString().getBytes("UTF-8"));
            get_Bytes(value);
            os.writeBytes("\r\n");
            System.out.print(sb.toString());     //展示请求报文

//参数的结尾一定要加上
	        os.writeBytes("--" + BOUNDARY + "--" + "\r\n");
	        os.writeBytes("\r\n");



### 四 . 判断请求是否成功,成功之后怎么接受返回的信息---respResult
 private static String respResult()throws IOException{
        int responseCode=httpURLConnection.getResponseCode();
        if (responseCode != 200) {
            return "responseCode:"+responseCode;
        }
        // 定义BufferedReader输入流来读取URL的ResponseData
        InputStreamReader reader= new InputStreamReader(httpURLConnection.getInputStream(),"UTF-8");
        BufferedReader bufferedReader = new BufferedReader(reader);
        String line;
        StringBuffer responseResult=new StringBuffer();
        while ((line = bufferedReader.readLine()) != null) {
            responseResult.append(line);
        }
        return responseResult.toString();
    }

### 五 . 注意点,以及出错可能的情况

注意点:

  1. 因为HttpURLConnection是一个抽象类,所以不能被直接实例化,通过URL.openConnection()方法得到HttpURLConnection的父类,然后再强转成HttpURLConnection对象实例。
  2. 无论是post请求还是get请求,connect()函数实际上只是建立了一个与服务器的tcp连接,并没有实际发送http请求。但是也可以不通过connect()方法来建立连接,因为getOutputStream()方法会隐式的进行connect。
  3. 方法的调用顺序非常重要,对connection对象的一切配置(就是各种set方法)必须在connect()方法之前调用,getOutputStream()方法必须在getInputStream()之前调用。
  4. 前面说到了各种方法的调用顺序,那么为什么要这样呢。首先HttpURLConnection对象被创建,然后被指定各种选项(例如连接超时时间,是否使用缓存,是否读取输出流等),然后与服务端建立连接。如果已经连接成功再设置这些选项将会报错。
  5. post请求参数是放在正文里面的,正文通过outputStream流写入的,实际上outputStream是个字符串流,往里面写入的东西不会立即发送到网络,而是存在于内存缓冲区中,待outputStream流关闭时,根据输入的内容生成http正文。在getInputStream()函数调用的时候,就会把准备好的http请求正式发送到服务器了,然后返回一个输入流,用于读取服务器对于此次http请求的返回信息。即使outputStream流没有关闭,在调用getInputStream()之后再写入参数也无效了。
  6. 参数的内容一定要规范,不能瞎JB修改,不然会出现 500的错误。

我自己写了一个HttpUrlConnection访问工具,可以下载参考一下哈!
有问题发我邮箱:[email protected] ------------------------------------------------------------作者:想做方丈的小沙弥

2018-12-27--------------------------------------------
1.增加 PATCH请求的支持
2.GET请求参数带特殊字符的支持

点击下载

你可能感兴趣的:(http请求)