java httpurlconnection因连接重置而失败
我开始用java编写代码,并尝试将一个现有的.NET应用程序转换为一个连续的数据流。我尝试了下面的代码,但是如果连接仍然为false,并且似乎连接了,则不会检索到任何数据,然后连接重置失败java httpurlconnection因连接重置而失败,java,httpurlconnection,Java,Httpurlconnection,我开始用java编写代码,并尝试将一个现有的.NET应用程序转换为一个连续的数据流。我尝试了下面的代码,但是如果连接仍然为false,并且似乎连接了,则不会检索到任何数据,然后连接重置失败 private static HttpURLConnection getConnection(String urlString, String username, String password) throws IOException { URL url = new URL(urlString);
private static HttpURLConnection getConnection(String urlString, String username, String password) throws IOException {
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setReadTimeout(300000);
connection.setConnectTimeout(30000);
connection.setRequestProperty("Authorization", createAuthHeader(username, password));
connection.setRequestProperty("Accept-Encoding", "gzip");
connection.setRequestProperty("Content-Type","application/json");
connection.setRequestProperty("Connection","Keep-Alive");
connection.setRequestProperty("useragent", "Mozilla/5.0 (Windows; U; Windows
NT 6.0; en-US; rv:1.9.0.10) Gecko/2009042316 Firefox/3.0.10 (.NET CLR 3.5.30729)");
return connection;
}
...
public Producer(Properties cprops, String kafkaBroker, String kafkaTopic) {
....
try {
String charset = "UTF-8";
String username = "me.com";
String password = "password";
String url = "https:/something.com.json";
HttpURLConnection connection = null;
InputStream inputStream = null;
try {
connection = getConnection(url, username, password);
connection.connect();
inputStream = connection.getInputStream();
int responseCode = connection.getResponseCode();
int numbytesRead = 0;
if (responseCode >= 200 && responseCode <= 299) {
BufferedReader reader =
new BufferedReader(new InputStreamReader
(new StreamingGZIPInputStream(inputStream), charset));
String line = reader.readLine();
while(true){
//read message per line and send to kafka
numbytesRead = line.length();
if (numbytesRead != 0) {
producer.send(new
KeyedMessage<String, String>(kafkaTopic,null,line));
System.out.println(line);
}else {
line = reader.readLine();
continue;
}
编辑:添加了附加代码
感谢您的任何帮助您无需设置方法或连接请求属性。在调用connection.getInputStream或getStatusCode或类似方法对连接进行实际操作之前,连接本身不会真正发生。您的代码看起来不错。您请求的url是什么?它接受get吗?您应该显示更多代码。调用getConnection后,代码中会发生什么?顺便说一句,您必须删除header方法,有一种方法可用于此目的。标题ContentType应为ContentType。如果你不再想与野兽HTTPURLConnect战斗,你应该考虑使用其中列出的一个库。我插入了第二次尝试连接-Connect。Connect。HttpURLConnection有问题吗?我将对属性和标题进行更正。哦,等等;它确实起作用了。不确定这是否只是标题属性中的微小更改,但我可以看到数据。也许我连接到的流当时没有推送数据。谢谢大家。