while (true) {
char c = (char) in.read();
recv.append(c);
if (recv.length() > 1024) {
throw new HttpException(ProxyInfo.ProxyType.HTTP, "Received header longer then 1024 chars");
}
if (c == -1) {
throw new HttpException(ProxyInfo.ProxyType.HTTP, "Invalid response");
}
if ((nlchars == 0 || nlchars == 2) && c == '\r') {
nlchars++;
} else if ((nlchars == 1 || nlchars == 3) && c == '\n') {
nlchars++;
} else {
nlchars = 0;
}
if (nlchars == 4) {
break;
}
}
String recvStr = recv.toString();
BufferedReader br = new BufferedReader(new StringReader(recvStr));
String response = br.readLine();
if (response == null) {
throw new HttpException(ProxyInfo.ProxyType.HTTP, "Empty proxy response");
}
Matcher m = RESPONSE_PATTERN.matcher(response);
if (!m.matches()) {
throw new HttpException(ProxyInfo.ProxyType.HTTP, "Unexpected proxy response");
}
int code = Integer.parseInt(m.group(1));
if (code != HttpURLConnection.HTTP_OK) {
throw new HttpException(ProxyInfo.ProxyType.HTTP, "Invalid code");
}
return socket;
} catch (RuntimeException rtex) {
closeSocket(socket);
throw rtex;
} catch (Exception ex) {
closeSocket(socket);
throw new HttpException(ProxyInfo.ProxyType.HTTP, ex.toString(), ex);
}
}