httpclient demo 3.1 4.2不同版本的API实现 解析JSON

4.2版本:

/*
 * code by Chenzhipeng
 * Date:2-13-0907
 *
要获取网络上的网页内容有POST,和GET两种方式,
Get比较简单,直接把参数放在URL结尾就OK,比如http://127.0.0.1/list.php?id=1这个URL,
问号后面的就是传送的参数,id为1。但是get有个受到浏览器支持的URL最大长度的限制,而且如果传用密码
之类的东西,直接写在网址里也不安全。
Post相对于Get没有长度限制,也不会把数据明文放在URL结尾。
 *
 */



import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;
import net.sf.json.util.JSONTokener;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.*;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.DefaultRedirectStrategy;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;

public class HttpDemo {

	
	
    @SuppressWarnings("deprecation")
	public static void main(String[] args) throws Exception {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        
  
        
         HttpGet httpGet = new HttpGet("http://10.11.0.19:8774/v2/2ac9993729ff486786a821bd2f508e1c/os-resourcemanagers");
       // 2 HttpGet httpGet = new HttpGet("http://10.11.0.19:8774/v2/2ac9993729ff486786a821bd2f508e1c/os-resourcemanagers/2");
       // 3 HttpDelete httpGet=new HttpDelete("http://10.11.0.19:8774/v2/2ac9993729ff486786a821bd2f508e1c/os-resourcemanagers/2");
        /*
         * nodemanager
         */
        //12 HttpGet httpGet = new HttpGet("http://10.11.0.19:8774/v2/2ac9993729ff486786a821bd2f508e1c/os-nodemanagers/2");
        
        
         //HttpDelete httpGet=new HttpDelete("http://10.11.0.19:8774/v2/2ac9993729ff486786a821bd2f508e1c/os-nodemanagers/3");
        HttpResponse response1 = httpclient.execute(httpGet);

        // The underlying HTTP connection is still held by the response object 
        // to allow the response content to be streamed directly from the network socket. 
        // In order to ensure correct deallocation of system resources 
        // the user MUST either fully consume the response content  or abort request 
        // execution by calling HttpGet#releaseConnection().

        try {
            System.out.println(response1.getStatusLine());
            HttpEntity entity1 = response1.getEntity();
            // do something useful with the response body
            // and ensure it is fully consumed
           //InputStream sin = entity1.getContent();
            System.out.println("----------------------------------------");
            System.out.println(response1.getStatusLine());
            //  response1.getParams()
            Header[] headers = response1.getAllHeaders();
            for (int i = 0; i<headers.length; i++) {
                System.out.println(headers[i]);
            }
            System.out.println("----------------------------------------");

            if (entity1 != null) {
              //  System.out.println(EntityUtils.toString(entity1));
               String result=EntityUtils.toString(entity1);
    			//得到返回的字符串
    		   System.out.println(result);
                //byte[] bytes = EntityUtils.toByteArray(entity1);
                //System.out.println( " - " + bytes.length + " bytes read");
            }

            
            
            
            
            EntityUtils.consume(entity1);
        } finally {
            httpGet.releaseConnection();
        }
       
       
        
        System.out.println("*************"+"以下为post:"+"*********************");
        HttpPost httpPost = new HttpPost("http://10.11.0.19:8774/v2/2ac9993729ff486786a821bd2f508e1c/os-resourcemanagers");
        
       
        
        /*
        List <NameValuePair> nvps = new ArrayList <NameValuePair>();
        nvps.add(new BasicNameValuePair("hdfs", "123456"));
        //nvps.add(new BasicNameValuePair("password", "tomandjerry"));
        httpPost.setEntity(new UrlEncodedFormEntity(nvps,"UTF-8"));
        httpPost.setEntity(new UrlEncodedFormEntity(nvps));
        */
        
      //向服务器写json
        JSONObject json = new JSONObject();

        //Object hdfs = null;

        json.put("hdfs", "10.3.3.3");

        StringEntity se = new StringEntity(json.toString());

        se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
  
        httpPost.setEntity(se);
        
        /*
        // 以下为新增内容  
        httpclient.setRedirectStrategy(new DefaultRedirectStrategy() {                  
                public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context)  {  
                    boolean isRedirect=false;  
                    try {  
                        isRedirect = super.isRedirected(request, response, context);  
                    } catch (Exception e) {  
                        e.printStackTrace();  
                    }  
                    if (!isRedirect) {  
                        int responseCode = response.getStatusLine().getStatusCode();  
                        if (responseCode == 301 || responseCode == 302) {  
                            return true;  
                        }  
                    }  
                    return isRedirect;  
                }  
        });  
        
        */
        HttpResponse response2 = httpclient.execute(httpPost);
        HttpEntity entity2 = response2.getEntity();
        try {
        	System.out.println(response2.getStatusLine());
    		if(response2.getStatusLine().getStatusCode()==200){//如果状态码为200,就是正常返回
    			
    			String result=EntityUtils.toString(entity2);
    			//得到返回的字符串
    			System.out.println(result);
    			//打印输出
               //如果是下载文件,可以用response.getEntity().getContent()返回InputStream
    		}
    		
            
            // do something useful with the response body
            // and ensure it is fully consumed
            EntityUtils.consume(entity2);
        } finally {
            httpPost.releaseConnection();
        }
    }

}


/*
HTTP/1.1 200 OK
----------------------------------------
HTTP/1.1 200 OK
Date: Sat, 07 Sep 2013 15:26:52 GMT
Server: BWS/1.0
Content-Length: 11054
Content-Type: text/html;charset=utf-8
Cache-Control: private
BDPAGETYPE: 1
BDUSERID: 0
BDQID: 0x8860d3fc07b48f84
Set-Cookie: BDSVRTM=2; path=/
Set-Cookie: H_PS_PSSID=2776_1451_2976_3135_3108_3225; path=/; domain=.baidu.com
Set-Cookie: BAIDUID=1D9FC5975DB897ED60C256A60C5006D6:FG=1; expires=Sat, 07-Sep-43 15:26:52 GMT; path=/; domain=.baidu.com
Expires: Sat, 07 Sep 2013 15:26:52 GMT
P3P: CP=" OTI DSP COR IVA OUR IND COM "
Connection: Keep-Alive
----------------------------------------
<!DOCTYPE html><!--STATUS OK--><html><head><meta http-equiv="content-type" content="text/html;charset=utf-8"><title>百度一下,你就知道</title><style >html,body{height:100%}html{overflow-y:auto}#wrapper{position:relative;_position:;min-height:100%}#content{padding-bottom:100px;text-align:center}#ftCon{height:100px;position:absolute;bottom:44px;text-align:center;width:100%;margin:0 auto;z-index:0;overflow:hidden}#ftConw{width:720px;margin:0 auto}body{font:12px arial;text-align:;background:#fff}body,p,form,ul,li{margin:0;padding:0;list-style:none}body,form,#fm{position:relative}td{text-align:left}img{border:0}a{color:#00c}a:active{color:#f60}.bg{background-image:url(http://s1.bdstatic.com/r/www/cache/static/global/img/icons_d3d3a658.png);background-repeat:no-repeat;_background-image:url(http://s1.bdstatic.com/r/www/cache/static/global/img/icons_b13038b3.gif)}.c-icon{display:inline-block;width:14px;height:14px;vertical-align:text-bottom;font-style normal;overflow:hidden;background:url(http://s1.bdstatic.com/r/www/cache/static/global/img/icons_d3d3a658.png) no-repeat 0 0;_background-image:url(http://s1.bdstatic.com/r/www/cache/static/global/img/icons_b13038b3.gif)}.c-icon-triangle-down-blue{background-position:-480px -24px}.c-icon-chevron-unfold2{background-position:-504px -24px}#u{color:#999;padding:4px 10px 5px 0;text-align:right}#u a{margin:0 5px}#u .reg{margin:0}#m{width:720px;margin:0 auto}#nv a,#nv b,.btn,#lk{font-size:14px}#fm{padding-left:110px;text-align:left;z-index:1}input{border:0;padding:0}#nv{height:19px;font-size:16px;margin:0 0 4px;text-align:left;text-indent:137px}.s_ipt_wr{width:418px;height:30px;display:inline-block;margin-right:5px;background-position:0 -288px;border:1px solid #b6b6b6;border-color:#9a9a9a #cdcdcd #cdcdcd #9a9a9a;vertical-align:top}.s_ipt{width:405px;height:22px;font:16px/22px arial;margin:5px 0 0 7px;background:#fff;outline:0;-webkit-appearance:none}.s_btn{width:95px;height:32px;padding-top:2px\9;font-size:14px;background-color:#ddd;background-position:0 -240px;cursor:pointer}.s_btn_h{background-position:-240px -240px}.s_btn_wr{width:97px;height:34px;display:inline-block;background-position:-120px -240px;*position:relative;z-index:0;vertical-align:top}#lg img{vertical-align:top;margin-bottom:3px}#lk{margin:33px 0}#lk span{font:14px "宋体"}#lm{height:60px}#lh{margin:16px 0 5px;word-spacing:3px}.tools{position:absolute;top:-4px;*top:10px;right:7px}#mHolder{width:62px;position:relative;z-index:296;display:none}#mCon{height:18px;line-height:18px;position:absolute;cursor:pointer}#mCon span{color:#00c;cursor:default;display:block}#mCon .hw{text-decoration:underline;cursor:pointer;display:inline-block}#mCon .pinyin{display:inline-block}#mCon .c-icon-chevron-unfold2{margin-left:5px}#mMenu a{width:100%;height:100%;display:block;line-height:22px;text-indent:6px;text-decoration:none;filter:none\9}#mMenu,#user ul{box-shadow:1px 1px 2px #ccc;-moz-box-shadow:1px 1px 2px #ccc;-webkit-box-shadow:1px 1px 2px #ccc;filter:progid:DXImageTransform.Microsoft.Shadow(Strength=2,Direction=135,Color="#cccccc")\9}#mMenu{width:56px;border:1px solid #9b9b9b;list-style:none;position:absolute;right:27px;top:28px;display:none;background:#fff}#mMenu a:hover{background:#ebebeb}#mMenu .ln{height:1px;background:#ebebeb;overflow:hidden;font-size:1px;line-height:1px;margin-top:-1px}#cp,#cp a{color:#666}#seth{display:none;behavior:url(#default#homepage)}#setf{display:none}#sekj{margin-left:14px}#shouji{margin-right:14px}</style><script >function h(obj){obj.style.behavior='url(#default#homepage)';var a = obj.setHomePage('http://www.baidu.com/');}</script></head><body><div id="wrapper"><div id="content"><div id="u"><a href="http://www.baidu.com/gaoji/preferences.html" name="tj_setting">搜索设置</a>|<a href="https://passport.baidu.com/v2/?login&tpl=mn&u=http%3A%2F%2Fwww.baidu.com%2F" name="tj_login" id="lb" οnclick="return false;">登录</a><a href="https://passport.baidu.com/v2/?reg®Type=1&tpl=mn&u=http%3A%2F%2Fwww.baidu.com%2F" target="_blank" name="tj_reg" class="reg">注册</a></div><div id="m"><p id="lg"><img src="http://www.baidu.com/img/bdlogo.gif" width="270" height="129"></p><p id="nv"><a href="http://news.baidu.com">新 闻</a> <b>网 页</b> <a href="http://tieba.baidu.com">贴 吧</a> <a href="http://zhidao.baidu.com">知 道</a> <a href="http://music.baidu.com">音 乐</a> <a href="http://image.baidu.com">图 片</a> <a href="http://v.baidu.com">视 频</a> <a href="http://map.baidu.com">地 图</a></p><div id="fm"><form name="f" action="/s"><span class="bg s_ipt_wr"><input type="text" name="wd" id="kw" maxlength="100" class="s_ipt"></span><input type="hidden" name="rsv_bp" value="0"><input type=hidden name=ch value=""><input type=hidden name=tn value="baidu"><input type=hidden name=bar value=""><input type="hidden" name="rsv_spt" value="3"><input type="hidden" name="ie" value="utf-8"><span class="bg s_btn_wr"><input type="submit" value="百度一下" id="su" class="bg s_btn" οnmοusedοwn="this.className='bg s_btn s_btn_h'" οnmοuseοut="this.className='bg s_btn'"></span></form><span class="tools"><span id="mHolder"><div id="mCon"><span>输入法</span></div></span></span><ul id="mMenu"><li><a href="#" name="ime_hw">手写</a></li><li><a href="#" name="ime_py">拼音</a></li><li class="ln"></li><li><a href="#" name="ime_cl">关闭</a></li></ul></div><p id="lk"><a href="http://baike.baidu.com">百科</a> <a href="http://wenku.baidu.com">文库</a> <a href="http://www.hao123.com">hao123</a><span> | <a href="http://www.baidu.com/more/">更多>></a></span></p><p id="lm"></p></div></div><div id="ftCon"><div id="ftConw"><p ><a id="seth" onClick="h(this)" href="/" οnmοusedοwn="return ns_c({'fm':'behs','tab':'homepage','pos':0})">把百度设为主页</a><a id="setf" href="http://www.baidu.com/cache/sethelp/index.html" οnmοusedοwn="return ns_c({'fm':'behs','tab':'favorites','pos':0})" target="_blank">把百度设为主页</a><span id="sekj"><a href="http://liulanqi.baidu.com/ps.php" target="_blank" οnmοusedοwn="return ns_c({'fm':'behs','tab':'bdbrwlk','pos':1})">安装百度浏览器</a></span></p><p id="lh"><a href="http://e.baidu.com/?refer=888" οnmοusedοwn="return ns_c({'fm':'behs','tab':'btlink','pos':2})">加入百度推广</a> | <a οnmοusedοwn="return ns_c({'fm':'behs','tab':'tj_bang'})" href="http://top.baidu.com">搜索风云榜</a> | <a οnmοusedοwn="return ns_c({'fm':'behs','tab':'tj_about'})" href="http://home.baidu.com">关于百度</a> | <a οnmοusedοwn="return ns_c({'fm':'behs','tab':'tj_about_en'})" href="http://ir.baidu.com">About Baidu</a></p><p id="cp">©2013 Baidu <a href="/duty/" name="tj_duty">使用百度前必读</a> 京ICP证030173号 <img src="http://www.baidu.com/cache/global/img/gs.gif"></p></div></div></div></body><script>var bds={se:{},comm : {ishome : 1,sid : "2776_1425_2976_2980_3092_3225",user : "",username : "",sugHost : "http://suggestion.baidu.com/su",personalData : "",loginAction : []}}</script><script type="text/javascript" src="http://s1.bdstatic.com/r/www/cache/static/global/js/home_299f7566.js" charset="utf-8"></script><script>var bdUser = null;var w=window,d=document,n=navigator,k=d.f.wd,a=d.getElementById("nv").getElementsByTagName("a"),isIE=n.userAgent.indexOf("MSIE")!=-1&&!window.opera;(function(){if(/q=([^&]+)/.test(location.search)){k.value=decodeURIComponent(RegExp["\x241"])}})();if(n.cookieEnabled){bds.se.sug();};function addEV(o, e, f){if(w.attachEvent){o.attachEvent("on" + e, f);}else if(w.addEventListener){ o.addEventListener(e, f, false);}}function G(id){return d.getElementById(id);}function ns_c(q){var p = encodeURIComponent(window.document.location.href), sQ = '', sV = '', mu='', img = window["BD_PS_C" + (new Date()).getTime()] = new Image();for (v in q) {sV = q[v];sQ += v + "=" + sV + "&";} mu= "&mu=" + p ;img.src = "http://nsclick.baidu.com/v.gif?pid=201&pj=www&rsv_sid=2776_1425_2976_2980_3092_3225&" + sQ + "path="+p+"&t="+new Date().getTime();return true;}if(/\bbdime=[12]/.test(d.cookie)){document.write('<script src="' + "http://s1.bdstatic.com/r/www/cache/static/ime/js/openime_ceac1c4e.js" + '" charset="utf-8"><\/script>');}(function(){var u = G("u").getElementsByTagName("a"), nv = G("nv").getElementsByTagName("a"), lk = G("lk").getElementsByTagName("a"), un = "";var tj_nv = ["news","tieba","zhidao","mp3","img","video","map"];var tj_lk = ["baike","wenku","hao123","more"];un = bds.comm.user == "" ? "" : bds.comm.user;function _addTJ(obj){addEV(obj, "mousedown", function(e){var e = e || window.event;var target = e.target || e.srcElement;ns_c({'fm':'behs','tab':target.name||'tj_user','un':encodeURIComponent(un)});});}for(var i = 0; i < u.length; i++){_addTJ(u[i]);}for(var i = 0; i < nv.length; i++){nv[i].name = 'tj_' + tj_nv[i];}for(var i = 0; i < lk.length; i++){lk[i].name = 'tj_' + tj_lk[i];}})();(function() {var links = {'tj_news': ['word', 'http://news.baidu.com/ns?tn=news&cl=2&rn=20&ct=1&ie=utf-8'],'tj_tieba': ['kw', 'http://tieba.baidu.com/f?ie=utf-8'],'tj_zhidao': ['word', 'http://zhidao.baidu.com/search?pn=0&rn=10&lm=0'],'tj_mp3': ['key', 'http://music.baidu.com/search?fr=ps&ie=utf-8'],'tj_img': ['word', 'http://image.baidu.com/i?ct=201326592&cl=2&nc=1&lm=-1&st=-1&tn=baiduimage&istype=2&fm=&pv=&z=0&ie=utf-8'],'tj_video': ['word', 'http://video.baidu.com/v?ct=301989888&s=25&ie=utf-8'],'tj_map': ['wd', 'http://map.baidu.com/?newmap=1&ie=utf-8&s=s'],'tj_baike': ['word', 'http://baike.baidu.com/search/word?pic=1&sug=1&enc=utf8'],'tj_wenku': ['word', 'http://wenku.baidu.com/search?ie=utf-8']};var domArr = [G('nv'), G('lk'),G('cp')],kw = G('kw');for (var i = 0, l = domArr.length; i < l; i++) {domArr[i].onmousedown = function(e) {e = e || window.event;var target = e.target || e.srcElement,name = target.getAttribute('name'),items = links[name],reg = new RegExp('^\\s+|\\s+\x24'),key = kw.value.replace(reg, '');if (items) {if (key.length > 0) {var wd = items[0], url = items[1],url = url + ( name === 'tj_map' ? encodeURIComponent('&' + wd + '=' + key) : ( ( url.indexOf('?') > 0 ? '&' : '?' ) + wd + '=' + encodeURIComponent(key) ) );target.href = url;} else {target.href = target.href.match(new RegExp('^http:\/\/.+\.baidu\.com'))[0];}}name && ns_c({'fm': 'behs','tab': name,'query': encodeURIComponent(key),'un': encodeURIComponent(bds.comm.user || '') });};}})();addEV(w,"load",function(){k.focus()});w.οnunlοad=function(){};</script><script type="text/javascript" src="http://s1.bdstatic.com/r/www/cache/static/global/js/tangram-1.3.4c1.0_07038476.js"></script><script type="text/javascript" src="http://s1.bdstatic.com/r/www/cache/static/user/js/u_ec0ebfe1.js" charset="utf-8"></script><script>try{document.cookie="WWW_ST=;expires=Sat, 01 Jan 2000 00:00:00 GMT";baidu.on(document.forms[0],"submit",function(){var _t=new Date().getTime();document.cookie = "WWW_ST=" + _t +";expires=" + new Date(_t + 10000).toGMTString()})}catch(e){}</script></html><!--23ae5b39adaa4955-->
*************以下为post:*********************
HTTP/1.1 200 OK
<!DOCTYPE html>
<!-- saved from url=(0038)http://www.baidu.com/search/error.html -->
<html><head><meta http-equiv="Content-Type" content="text/html; charset=GBK">
<meta charset="gbk">
<title>°Ù¶È--ÄúµÄ·ÃÎʳö´íÁË</title>
<style type="text/css">
	body{margin:0;padding:0;font-size:14px;font-family:"ËÎÌå",Arial, Helvetica, sans-serif;}
	img,ul,li,form,h2,ol{border:0;padding:0;margin:0;list-style:none;}
	.cl{clear:both;height:0px;line-height:0px;font-size:0px;overflow:hidden;}
	input{vertical-align:middle;}
	a:link{color:#0033cc}
	a:visited{color:#800080;}
	a:hover{color:#800080;}
	a:actived{color:#800080;}
	#content{width:95%;align:center;margin:0 auto  0;}
	.logo{float:left;width:141px;margin:10px 0 0 0;}
	.title{float:right;width:;line-height:24px;background:#e5ecf9;margin:20px 0 0 0;padding-left:8px;}
	.title a{margin-left:320px;}
	.tip{font-size:18px;margin:25px 0 25px 5px;*margin:25px 0 25px 5px;}
	.reason{margin:25px 0 33px 5px;*margin:25px 0 30px 5px;}
	.reason li{line-height:24px;height:24px;}
	.searchbox{margin:0 0 40px 8px;*margin:0 0 40px 8px;}
	.help{margin:0 0 100px 5px;}
	.footer{margin:50px 0 20px 0;*margin:50px 0 20px 0;text-align:center;color:#666666;}
	.footer a{color:#666666;}
</style>
</head>
<body>
<table border="0" width="95%" align="center">
	<tbody><tr height="60">
		<td height="65" valign="top" width="141"><a href="http://www.baidu.com/"><img border="0" src="http://www.baidu.com/search/img/logo.gif" alt="µ½°Ù¶ÈÊ×Ò³"></a></td>
		<td valign="bottom">
			<table border="0" cellspacing="0" cellpadding="0" width="100%">
				<tbody><tr bgcolor="#e5ecf9">
					<td height="24"> <b class="p1">ÄúµÄ·ÃÎʳö´íÁË</b></td>
					<td class="p2" height="24"><div align="right"><a href="http://www.baidu.com/">°Ù¶ÈÊ×Ò³</a>  |  <a href="http://www.baidu.com/search/jiqiao.html">°ïÖúÖÐÐÄ</a>  </div></td>
				</tr>
				<tr><td class="p2" height="20" colspan="2"></td></tr>
			</tbody></table>
		</td>
	</tr>
</tbody></table>
<div id="content">
	<h2 class="tip" style="padding-left:144px"><p>ºÜ±§Ç¸£¬ÄúÒª·ÃÎʵÄÒ³Ãæ²»´æÔÚ!<br><br></p><hr color="#dddddd" size="1"></h2>
</div>
<div id="content">
<ol class="reason" style="padding-left:144px">
    	<li> 1. Çë¼ì²éÄú·ÃÎʵÄÍøÖ·ÊÇ·ñÕýÈ·¡£</li><br>
        <li> 2. Èç¹ûÄú²»ÄÜÈ·ÈÏ·ÃÎʵÄÍøÖ·£¬Çëä¯ÀÀ<a href="http://www.baidu.com/more/index.html">°Ù¶È¸ü¶à</a>Ò³Ãæ²é¿´¸ü¶àÍøÖ·¡£</li><br>
        <li> 3. Ö±½ÓËÑË÷Òª²éÕÒµÄÄÚÈÝ£º</li>
    <li class="searchbox"><br>
    	<form action="http://www.baidu.com/s" name="f">
        	<input type="text" name="wd" size="35" maxlength="100"><input type="hidden" name="cl" value="3"><input type="hidden" name="tn" value="baiduerr"><input type="submit" value="°Ù¶ÈÒ»ÏÂ">
	  </form></li>
    <li class="help">
      4.ÈçÓÐÈκÎÒâ¼û»ò½¨Ò飬Ç뼰ʱ<a href="http://qingting.baidu.com/">·´À¡¸øÎÒÃÇ</a>¡£
        <br><br><br>
        <b>ÍƼöÄú·ÃÎÊ£º</b><a href="http://news.baidu.com/">ÐÂÎÅ</a>¡¡<a href="http://tieba.baidu.com/">Ìù°É</a>¡¡<a href="http://zhidao.baidu.com/">ÖªµÀ</a>¡¡<a href="http://music.baidu.com/">ÒôÀÖ</a>¡¡<a href="http://image.baidu.com/">ͼƬ</a>¡¡<a href="http://v.baidu.com/">ÊÓƵ</a>¡¡<a href="http://map.baidu.com/">µØͼ</a>¡¡<a href="http://baike.baidu.com/">°Ù¿Æ</a>¡¡<a href="http://wenku.baidu.com/">ÎÄ¿â</a>¡¡<a href="http://www.hao123.com/">hao123</a>
    </li>¡¡</ol>

    <div class="footer">© 2013 Baidu <a href="http://www.baidu.com/duty/index.html">ÃâÔðÉùÃ÷</a></div>
</div>

</body></html>

*/

3.1版本

get/delete

import java.io.*;

import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;
import org.apache.commons.httpclient.params.HttpMethodParams;
public class HttpPostTutorial {

	//private static String url ="http://www.apache.org/";
	private static String url ="http://10.11.0.19:8774/v2/2ac9993729ff486786a821bd2f508e1c/os-resourcemanagers";
			//"http://www.apache.org/";
	
	public static void main(String[] args) throws Exception {
		 HttpClient client = new HttpClient();
		PostMethod post = new PostMethod(url);
        NameValuePair[] data = {
          new NameValuePair("hdfs", "123456")
          
        };
        post.setRequestBody(data);
        // execute method and handle any error responses.
        // 执行postMethod
        int statusCode = client.executeMethod(post);
        // Display status code
        System.out.println("Response status code: " + statusCode);
         	// Display response
         	System.out.println("Response body: ");
         	System.out.println(post.getResponseBodyAsString());
        //InputStream in = post.getResponseBodyAsStream();
        // handle response.

	}

}

3.1post

import java.io.IOException;

import net.sf.json.JSONObject;

import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;
import org.apache.commons.httpclient.params.HttpMethodParams;

public class Postdemo1 {

	private static String url ="http://10.11.0.19:8774/v2/2ac9993729ff486786a821bd2f508e1c/os-resourcemanagers";
	public static void main(String[] args) throws HttpException, Exception {
		// TODO Auto-generated method stub
		 HttpClient httpClient = new HttpClient();
		PostMethod postMethod = new PostMethod(url);
		
		 JSONObject json = new JSONObject();
	        json.put("hdfs", "10.3.3.3");
	        
		StringRequestEntity requestEntity = new StringRequestEntity(json.toString(),"application/json","UTF-8");
		postMethod.setRequestEntity(requestEntity);
//		//postMethod.addRequestHeader("Content-Type", "application/json");
//		postMethod.addParameters(new NameValuePair[]{
//		        new NameValuePair("name", "value")
//		});
		int statusCode=httpClient.executeMethod(postMethod);
		postMethod.getResponseBodyAsStream();
		 System.out.println("Response status code: " + statusCode);
      	// Display response
      	System.out.println("Response body: ");
      	System.out.println(postMethod.getResponseBodyAsString());
      	
        String jsonString= postMethod.getResponseBodyAsString();
      	System.out.println(jsonString);
      	/*
      	JSONObject jsonObject = JSONObject.fromObject(jsonString);        
        Iterator keyIter = jsonObject.keys();        
        String key;        
        Object value;        
        Map valueMap = new HashMap();        
       
        while (keyIter.hasNext()) {        
            key = (String) keyIter.next();        
            value = jsonObject.get(key);        
            valueMap.put(key, value);        
        }        
        
        
      	String hostIP=(String)valueMap.get("NMhostIP");
      	System.out.println("hostIP is: "+hostIP);
      	
      	String hostName=(String)valueMap.get("NMhostName");
      	System.out.println("NMhostName is: "+hostName);
      	*/
      	int i=jsonString.indexOf(',');
      	String IP=jsonString.substring(14, i-1);
      	System.out.println("hostIP is: "+IP);
      	
      	String hostName=jsonString.substring(i+17, jsonString.length()-2);
      	System.out.println("NMhostName is: "+hostName);

postMethod.releaseConnection();}}




参考: http://hc.apache.org/httpclient-3.x/methods/multipartpost.html

          http://projects.apache.org/projects/commons_httpclient.html

        http://hc.apache.org/downloads.cgi




  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值