欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

使用UrlConnection实现后台模拟http请求的简单实例

程序员文章站 2023-12-13 08:01:15
使用urlconnection实现后台模拟http请求的简单实例 这两天在整理看httpclient,然后想自己用urlconnection后台模拟实现http请求,于是...

使用urlconnection实现后台模拟http请求的简单实例

这两天在整理看httpclient,然后想自己用urlconnection后台模拟实现http请求,于是一个简单的小例子就新鲜出炉了(支持代理哦):

public class simplehttptest { 
 
  public static string send(string urlstr, map<string,string> map,string encoding){ 
    string body=""; 
    stringbuffer sbuf = new stringbuffer(); 
    if(map!=null){ 
      for (entry<string,string> entry : map.entryset()) { 
        sbuf.append(entry.getkey()).append("=").append(entry.getvalue()).append("&"); 
      } 
      if(sbuf.length()>0){ 
        sbuf.deletecharat(sbuf.length()-1); 
      } 
    } 
     // 1、重新对请求报文进行 gbk 编码 
    byte[] postdata = null; 
    try { 
      postdata = sbuf.tostring().getbytes(encoding); 
    } catch (unsupportedencodingexception e) { 
      e.printstacktrace(); 
    } 
 
    // 2、发送 http(s) 请求 
    outputstream reqstream = null; 
    inputstream resstream = null; 
    urlconnection request = null; 
    try { 
      system.out.println("交易请求地址:" + urlstr); 
      system.out.println("参数:" + sbuf.tostring()); 
       
      //a、与服务器建立 http(s) 连接 
      url url = null; 
      try { 
        proxy proxy = new proxy(java.net.proxy.type.http,new inetsocketaddress("127.0.0.1", 8087)); 
        url = new url(urlstr); 
        request = url.openconnection(proxy); 
        request.setdoinput(true); 
        request.setdooutput(true); 
      } catch (malformedurlexception e) { 
        e.printstacktrace(); 
      } catch (ioexception e) { 
        e.printstacktrace(); 
      } 
       
      //b、指定报文头【content-type】、【content-length】 与 【keep-alive】 
      request.setrequestproperty("content-type", "application/x-www-form-urlencoded"); 
      request.setrequestproperty("content-length", string.valueof(postdata.length)); 
      request.setrequestproperty("keep-alive", "false"); 
      request.setrequestproperty("user-agent", "mozilla/4.0 (compatible; msie 5.0; windows nt; digext)"); 
       
      //c、发送报文至服务器 
      reqstream = request.getoutputstream(); 
      reqstream.write(postdata); 
      reqstream.close(); 
       
      //d、接收服务器返回结果 
      bytearrayoutputstream ms = null; 
      resstream = request.getinputstream(); 
      ms = new bytearrayoutputstream(); 
      byte[] buf = new byte[4096]; 
      int count; 
      while ((count = resstream.read(buf, 0, buf.length)) > 0) { 
        ms.write(buf, 0, count); 
      } 
      resstream.close(); 
      body = new string(ms.tobytearray(), encoding); 
    } catch (unknownhostexception e) { 
      system.err.println( "服务器不可达【" + e.getmessage() + "】"); 
    } catch (ioexception e) { 
      e.printstacktrace(); 
    } finally { 
      try { 
        if (reqstream != null) 
          reqstream.close(); 
        if (resstream != null) 
          resstream.close(); 
      } catch (exception ex) { 
      } 
    } 
 
    system.out.println("交易响应结果:"); 
    system.out.println(body); 
    return body; 
  } 
   
  public static void main(string[] args) { 
    string url="http://php.weather.sina.com.cn/iframe/index/w_cl.php"; 
    map<string, string> map = new hashmap<string, string>(); 
    map.put("code", "js"); 
    map.put("day", "0"); 
    map.put("city", "上海"); 
    map.put("dfc", "1"); 
    map.put("charset", "utf-8"); 
    send(url, map,"utf-8"); 
  } 
} 

结果如下:

交易请求地址:http://php.weather.sina.com.cn/iframe/index/w_cl.php 
参数:dfc=1&charset=utf-8&day=0&code=js&city=上海 
交易响应结果: 
(function(){var w=[];w['上海']=[{s1:'阴',s2:'阴',f1:'yin',f2:'yin',t1:'17',t2:'14',p1:'≤3',p2:'≤3',
d1:'东北风',d2:'东北风'}];var add={now:'2015-11-11 19:04:33',time:'1447239873',update:'
北京时间11月11日17:10更新',error:'0',total:'1'};window.swther={w:w,add:add};})();//0 

代码中的步骤写的很明白了,如果你有心,还可以对该方法进行各种封装,方便使用。下篇我会分享一下httpclient是如何模拟后台来发送http请求的,还有配置ssl、代理、自定义header等等,敬请期待吧。

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

上一篇:

下一篇: