測試攻城師的一點小開心

    String strUrl="http://192.168.16.xxx:8088/funadx-web/xxx/xxx/xxx/xxx";
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(strUrl);java

運行後,出現異常:java.net.URISyntaxException
 
網上找資料,原來是地址中涉及了特殊字符「-」,因此只能先把String轉成URL,再能過URL生成URI的方法來解決問題 
修改代碼以下:
    URL url = new URL(strUrl);
    URI uri = new URI(url.getProtocol(), url.getHost(), url.getPath(), url.getQuery(), null);
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(uri);
 
調試發現,post的時候端口不見了。。。
真真有點鬱悶呀,還好我當時想這個確定是能夠設置端口的,可是怎麼樣設置端口呢?百度了一下,沒找到解決方案(多是我搜索時問題描述的不對)
還好此時想起程序猿男票說他看開源代碼的好處。。。額。要不我看下源碼。
哈哈,好開心,原來URI還有個構造函數,能夠設置端口。bingo,問題解決。
最終代碼以下:
    URL postUrl = new URL(strUrl);
    URI uri = new URI(url.getProtocol(), null, url.getHost(),url.getPort(),url.getPath(), url.getQuery(), null );
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(uri);
 
此次雖然解決的不是一個很難的問題,但對於我來講也算一個小突破了,仍是小開心的,mark一下。
相關文章
相關標籤/搜索