我正在使用Java并尝试使用连接字符串形成URL。然后将其作为要POST的URI传递给HttpPost。
此代码失败:
String str1 = "http://www.example.com";
String str2 = "/directory";
HttpPost httppost = new HttpPost(str1 + str2);
这也失败了:
HttpPost httppost = new HttpPost(str1.concat(str2));
就像这样:
String strCombined = str1 + str2;
HttpPost httppost = new HttpPost(strCombined);
然而,这有效:
HttpPost httppost = new HttpPost("http://www.example.com/directory");
我错过了什么?
编辑:Stacktrace:05-31 01:43:29.973: W/System.err(451): java.net.UnknownHostException: http
05-31 01:43:29.983: W/System.err(451): at java.net.InetAddress.lookupHostByName(InetAddress.java:513)
05-31 01:43:29.993: W/System.err(451): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:278)
05-31 01:43:29.993: W/System.err(451): at java.net.InetAddress.getAllByName(InetAddress.java:242)
05-31 01:43:30.003: W/System.err(451): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:136)
05-31 01:43:30.013: W/System.err(451): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
05-31 01:43:30.013: W/System.err(451): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
05-31 01:43:30.024: W/System.err(451): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:348)
05-31 01:43:30.033: W/System.err(451): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
05-31 01:43:30.043: W/System.err(451): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
05-31 01:43:30.043: W/System.err(451): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
答案 0 :(得分:0)
理论上这不是我们可以期待的,对吧?那么在这里困扰你的原因可能是什么.. 您与我们分享的代码可能是简化版(为了更好的可读性),而不是您的实际代码,对吧?这让我觉得你的实际代码中可能有拼写错误或任何其他简单的错误,这可能会更复杂(并且很难找到简单的错误/拼写错误/错误)。
这可能是方法或构造函数,如
public HttpPost getConnection(String str1){
String strCombined = this.domain+ str1;
HttpPost httppost = new HttpPost(strCombined);
}
我会在这样的情况下做的事情是,在将它提供给HttpPost构造函数之前打印strCombined并查看它是否是我真正期望的。
public HttpPost getConnection(String str1){
String strCombined = this.domain+ str1;
System.out.print("strCombined : "+strCombined);
HttpPost httppost = new HttpPost(strCombined);
}
这可能是多线程应用程序的一个简单部分,那么你必须确保这个方法是线程安全的!