我知道有關於這個主題的幾個問題但我沒有找到任何一個答案。爪哇HttpUrlConnection拋出拒絕連接
我想打開一個連接到我的本地服務器,但我一直在拒絕連接。
我有服務器正在運行,我測試了與瀏覽器和名爲Postman的谷歌應用程序的連接,它可以工作。
打開連接時發生故障,好像沒有連接。或者可能是阻塞了連接?我測試了防火牆和防病毒軟件,沒有運氣。在郵差
測試網址如果我取代「http://www.google.com」它工作正常的URL會返回一個用戶,因爲它應該...
。
這裏是我的代碼:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
*
* @author Gabriel
*/
public class HttpConnection {
public HttpConnection() {
}
public void makeRequest() throws MalformedURLException, IOException {
String url = "http://localhost:8000/users/1";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
//add request header
con.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36");
con.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
con.setRequestProperty("Accept-Encoding", "gzip,deflate,sdch");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.8,es;q=0.6");
con.setRequestProperty("Connection", "keep-alive");
con.setRequestProperty("Host", "localhost:8000");
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
}
}
和瀏覽器是你正在運行的Java在同一臺計算機上? – 2014-09-20 01:47:42
是的...我的猜測是,有些東西阻止Java打開本地連接:P – 2014-09-20 02:03:15
好吧,我試過只是連接到http:// localhost,它的工作原理是,問題是http:// localhost:8000 :p我不知道爲什麼 – 2014-09-20 02:19:36