最近碰到一個 bug 卡關,那就是當我 new HttpGet("http://aaa_bbb.ccc.dddd") 出來,交由 HttpClient 執行時,卻會看到以下訊息:
java.lang.IllegalArgumentException: Host name may not be null
org.apache.http.HttpHost.<init>(HttpHost.java:83)
org.apache.http.impl.client.AbstractHttpClient.determineTarget(AbstractHttpClient.java:497)
org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
當下讓我連問隔壁的同事幾次...難道 hostname 不能有底線?改成 new HttpGet("aaa_bbb.ccc.dddd") 則是:
java.lang.IllegalStateException: Target host must not be null, or set in parameters.
org.apache.http.impl.client.DefaultRequestDirector.determineRoute(DefaultRequestDirector.java:561)
org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:292)
org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
原始程式碼:
String target = "http://aaa_bbb.ccc.dddd";
HttpClient mClient = new DefaultHttpClient();
HttpContext mHttpContext = new BasicHttpContext();
HttpUriRequest mHttpUriRequest = new HttpGet(target);
response = mClient.execute(mHttpUriRequest, mHttpContext);
解法:
String hostname = "aaa_bbb.ccc.dddd";
String target = "http://"+hostname;
HttpClient mClient = new DefaultHttpClient();
HttpContext mHttpContext = new BasicHttpContext();
HttpUriRequest mHttpUriRequest = new HttpGet(target);
response = mClient.execute(new HttpHost(hostname), mHttpUriRequest, mHttpContext);
不曉得這是不是一個 framework 的 bug?還是單純我操作錯誤呢...暫時先這樣解掉吧。
沒有留言:
張貼留言