Java httpclient 4.1如何使用可配置端口发送post请求

时间:2011-05-23 12:07:06

标签: java https httpclient

哇,我只是找不到任何有效的httpclient 4.1示例,用Not default端口发送post请求 但可配置端口,我有这个代码,但它不能正常工作

// lHashMapParams is with params getting form function .. 

List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
        for (String key : lHashMapParams.keySet()) {
            String val = lHashMapParams.get(key);
            params.add(new BasicNameValuePair(key,val));

}
String url = "https://foo.com";
int port = 8883;
String = "https";
UrlEncodedFormEntity query = new UrlEncodedFormEntity(params);
        HttpHost httpHost = new HttpHost(url,port,httpType); 

        HttpPost post = new HttpPost("/");
        post.setEntity(query);


        HttpResponse response_ = httpclient.execute(httpHost,post);

获得此例外:

log4j:WARN Please initialize the log4j system properly.
java.net.UnknownHostException: https://foo.com
    at java.net.Inet4AddressImpl.lookupAllHostAddr(Native Method)
    at java.net.InetAddress$1.lookupAllHostAddr(InetAddress.java:849)
    at java.net.InetAddress.getAddressFromNameService(InetAddress.java:1183)
    at java.net.InetAddress.getAllByName0(InetAddress.java:1136)
    at java.net.InetAddress.getAllByName0(InetAddress.java:1109)
    at java.net.InetAddress.getAllByName(InetAddress.java:1072)
    at org.apache.http.impl.conn.DefaultClientConnectionOperator.resolveHostname(DefaultClientConnectionOperator.java:242)
    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:130)
    at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:149)
    at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:121)
    at org.apache.http.impl.client.DefaultRequestDirector.tryConnect(DefaultRequestDirector.java:561)
    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:415)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:820)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:776)
    at com.ut.HttpClientImpl.postHttpReqest(HttpClientImpl.java:75)  

简单的话是如何定义端口的?

1 个答案:

答案 0 :(得分:4)

您正在尝试执行主机名https://foo.com 的查找,这就是问题所在;查找应该是foo.com。我不确定你是如何得到有问题的代码的,但是值得一些时间来看看HttpClient tutorial

如果我没错,下面的代码就足够了:

HttpPost httpost = new HttpPost(url); //construct the complete URL i.e. action to post to
httpost.setEntity(entity);
response = httpclient.execute(httpost);

其中url将使用http / https架构,主机名,端口和资源URI的其余部分构建。