解析http协议的url

Posted 和xin

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了解析http协议的url相关的知识,希望对你有一定的参考价值。

package util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class ServerUtil{
  public static StringBuilder getServerResponse(HttpURLConnection connection){
    String strLine = "";
    StringBuilder strResponse = new StringBuilder();
    try{
      Map<String,List<String>> rspHeaders = connection.getHeaderFields();
      Set<String> rspHeadNames = rspHeaders.keySet();
      for (String key : rspHeadNames) {
        if(null!=key){
          strResponse.append(key+":");
        }
        strResponse.append(new String(rspHeaders.get(key).get(0).getBytes("iso-8859-1"),"UTF-8")+"\n");
      }
      //获取状态码
      int code = connection.getResponseCode();
      InputStream in;
      if(code==200){
        in = connection.getInputStream();
      }else{
        in = connection.getErrorStream();
      }
      if(null!=in){
        //读取一串字符
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        while((strLine=reader.readLine())!=null){
          strResponse.append("\n"+strLine);
        }
      }
    }catch(Exception e){
      e.printStackTrace();
    }
    return strResponse;
  }
}

以上是关于解析http协议的url的主要内容,如果未能解决你的问题,请参考以下文章

HTTP -- HTTP相关协议(TCP/IPDNSURI/URLHTTPS)HTTP请求响应过程HTTP报文分析(请求方法URL)HTTP标头

路由器外网访问内网

HTTP协议详解

小白必学的爬虫基础

HTTP协议基本原理

url解析