Java에서 URLConnection 객체를 사용하여 REST를 통해 원격 데이터베이스에 데이터를 게시하고 있습니다. 작은 데이터 패키지를 많이 게시해야하므로 보낼 데이터 패키지가 더 이상 없을 때까지 연결 상태를 유지하고 싶습니다. 그러나 보내야 할 데이터 패키지가 없을 때 오랜 시간이 걸릴 수도 있습니다.연결이 끊어진 경우 URLConnection 객체는 무엇을 반환합니까?
예를 들어 시간 초과로 인해 연결이 끊어졌을 때 URLConnection 객체가 null로 재설정되는지 궁금합니다. 이 경우 객체가 null인지 다시 확인할 수 있습니다. 그러나 그렇지 않은 경우이 문제를 어떻게 해결할 것인가에 대한 제안 (각 데이터 패키지의 연결을 열고 닫아야 할 필요가 있습니까?)을 제안합니다.
이 (완전히 완료되지 :)!) 내 현재 코드 :
public class PersistenceServiceImpl implements PersistenceService, Runnable{
public void activate(){
new Thread(this).start();
}
@Override
public void run() {
LinkedBlockingQueue<JSONObject> queue = JSONQueue.getUniqueInstance();
JSONObject json;
try {
final URL url = new URL("");
URLConnection urlConn = null;
DataOutputStream printout;
while(true){
makeConnection(url, urlConn);
try {
json = queue.take();
printout = new DataOutputStream (urlConn.getOutputStream());
String content = json.toString();
printout.writeBytes(content);
printout.flush();
printout.close();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}catch(Exception e){
}
}
public void makeConnection(URL url, URLConnection urlConn) {
if(urlConn == null){
try {
urlConn = url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
}else{
try {
urlConn.connect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
urlConn.setDoInput(false);
urlConn.setDoOutput(true);
urlConn.setUseCaches(false);
urlConn.setRequestProperty("Content-Type", "application/json");
}
}
편집 :
나의 새로운 개선 (또는 그래서 희망) 코드 : p :
public class PersistenceServiceImpl implements PersistenceService, Runnable{
public void activate(){
new Thread(this).start();
}
LinkedBlockingQueue<JSONObject> queue = JSONQueue.getUniqueInstance();
JSONObject json;
final String urlString = new String("http://localhost/");
@Override
public void run() {
while(true){
try {
URL url = new URL("http://localhost:8080/RESTful");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
json = queue.take();
DataOutputStream output = new DataOutputStream(conn.getOutputStream());
output.write(json.toString().getBytes("utf-8"));
output.flush();
output.close();
} catch (MalformedURLException e) {
System.out.println("MALFORMEDURLEXCEPTION: fout url!!");
e.printStackTrace();
} catch (ProtocolException e){
System.out.println("PROTCOL EXCEPTION: post fout");
} catch (IOException e) {
System.out.println("IOEXCEPTION: connection failure");
e.printStackTrace();
} catch (InterruptedException e) {
System.out.println("INTERRUPTEDEXCEPTION: queue.take() deed iets fout");
e.printStackTrace();
}
그래서 시간 제한에 대해 걱정할 필요없이 연결을 열어 둘 수 있습니까? – Don
질문에 의미가 없습니다. 내 대답에 표시된 것 이외의 다른 연결을 제어 할 수 없기 때문에 * 연결을 계속 열 수 없습니다. 타임 아웃에 대해서는 항상 염려해야하지만 완전히 별개의 문제입니다. – EJP