发送HTTP数据流以及HTTPS数据流

来源:互联网 发布:推荐钢琴弹奏软件 编辑:程序博客网 时间:2024/05/21 17:20

HTTP数据流:

public String getRequest(String surl, String encoding) throws IOException {
  String sresult = "";
  HttpURLConnection conn = null;
  try {
   URL url = new URL(surl);
   conn = (HttpURLConnection) url.openConnection();
   conn.setRequestMethod("GET");
   conn.setDoOutput(false);
    System.setProperty("sun.net.client.defaultConnectTimeout",
    "1500");
    System.setProperty("sun.net.client.defaultReadTimeout", "1500");
   InputStream in = conn.getInputStream();
   InputStreamReader isr = new InputStreamReader(in, encoding);
   char[] b = new char[255];
   StringBuffer sb = new StringBuffer();
   int len = 0;
   while ((len = isr.read(b)) > 0) {
    sb.append(b, 0, len);
   }
   sresult = sb.toString();
   isr.close();
   in.close();
   conn.disconnect();
  } catch (IOException e) {
   throw e;
  } finally {
   if (conn != null) {
    conn.disconnect();
   }
  }
  return sresult;
 }

 

HTTPS数据流

 

  public void content(String url){
 try{

  URL reqURL = new URL(url);
  HttpsURLConnection httpsConn = (HttpsURLConnection)reqURL.openConnection();
  //   HttpURLConnection urlCon = (HttpURLConnection)reqURL.openConnection();
          // urlCon.setConnectTimeout(3000);//设置连接超时时间
          // urlCon.setReadTimeout(3000);//设置响应超时时间
  //取得该连接的输入流,以读取响应内容  
  InputStreamReader insr = new InputStreamReader(httpsConn.getInputStream());  
   
  //读取服务器的响应内容并显示  
  int respInt = insr.read();  
  while( respInt != -1){  
  System.out.print((char)respInt);  
  respInt = insr.read();  
  } 

 }catch(Exception e){
  e.printStackTrace();
 }
 
  }