URLConnection: URL からの読み込み[URLConnection:URL からのよみがみこ]

java.net.URLConnection は、アプリケーションを URL にリンクするクラスです。HTTPレスポンスを取得するには、まず2段階のURLで接続を作成する必要があります:
  • openConnection: このメソッドはオブジェクトconnection は、接続パラメータと受信パラメータを設定します。
  • URLConnection.connect: Java プログラムと url.
の間の通信を開始することにより、リソースとの対話を作成します次のコードは、http:// サイトへの接続を作成しますwww.codeurjava.com.

URL url=null;
try {
url = new URL("http://www.codeurjava.com");
} catch (MalformedURLException e) {
// TODO 自動生成された catch ブロック
e.printStackTrace();
}
try {
URLConnection con = url.openConnection();
in.close();
} catch (IOException e1) {
// TODO 自動生成された catch block
e.printStackTrace();
}
openConnection() で接続が確立されるたびに URLConnection オブジェクトが作成されます。接続が正常に確立されたので、URLConnection を使用して InputStream と outputStream.

Read from URLConnection

このプログラムは inputStream オブジェクトを取得し、接続は getInputStream() メソッドで開かれます。 次に、そのInputStreamにBufferedReaderを作成し、その内容を読み取ります。一行ずつreadline() メソッドを String 型の変数にロードする必要がある

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

public class URLConnectionExample:{

public static void main(String[] args) {
String host = "http://www.codeurjava.com/";
URL aURL = null;
文字列 codeHTML = "";
{
aURL = new URL(host);
//接続を開く
URLConnection con = aURL.openConnection();
//接続に割り当てられる最大時間
con.setConnectTimeout(60000);
//読み取りに割り当てられる最大時間
con.setReadTimeout(60000);
//UTF-8 文字エンコードでストリームを読み込みます
BufferedReader in = new BufferedReader(
new InputStreamReader(
con.getInputStream(),"UTF-8"));
文字列入力行。
while((inputline = in.readLine())!=null){
//連結+改行と\n
HTML コード += inputline+"\n";
}
//再生ストリームは閉じなければならない
in.close();
} catch (IOException e1) {
// TODO 自動生成された catch ブロック
e.printStackTrace();
}
System.out.println(codeHTML);
}
}
Result



<ヘッド>
JAVA開発のチュートリアルと例<br />.<br />.<br />.<br /></head><br /></div ><br /></div ><br /></pre></div>このコードは<b>Java.</bのHTMLコードを取得します> プログラムにエラーメッセージが表示された場合は、プログラムがサーバーを見つけられなかったか、URLに到達できません。このプログラムでは、接続と再生に許可される最大時間を6秒にプログラムしました。この時間が経過すると、プログラムは停止します。<br /><br />References<br /><a href="http://docs.oracle.com/javase/7/docs/api/java/net/URL.html#openConnection()" target="_blank">Oracle: クラスURL: openConnection</a><br /><a href="http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.net.URLConnection.html" target="_blank">upenn: クラス java.net.URLConnection</a><br /><ahref="http://stackoverflow.com/questions/2793150/using-java-net-urlconnection-to-fire-and-handle-http-requests" target="_blank">StackOverFlow: java.net.URLConnection を使用して HTTP 要求を発生および処理する?</a></div> </article> <!-- Système de commentaires - Option 1 : Authentification requise --> <!-- Section des commentaires --> <section class="comments-section"> <div class="comments-header"> <h3 class="comments-count">Commentaires (<span id="commentCount">0</span>)</h3> </div> <!-- Messages d'alerte --> <div id="alertMessage" class="alert"></div> <!-- Formulaire pour les utilisateurs connectés --> <div id="commentForm" class="comment-form hidden"> <h4>Laisser un commentaire</h4> <textarea id="commentContent" class="comment-textarea" placeholder="Écrivez votre commentaire ici..." maxlength="1000" ></textarea> <div style="display: flex; justify-content: space-between; align-items: center;"> <span style="font-size: 0.85rem; color: #64748b;"> <span id="charCount">0</span>/1000 caractères </span> <button class="btn btn-primary" onclick="submitComment()"> Publier le commentaire </button> </div> </div> <!-- Message pour les utilisateurs non connectés --> <div id="authRequired" class="comment-auth-required"> <h4>Connectez-vous pour commenter</h4> <p>Rejoignez la discussion et partagez vos connaissances avec la communauté</p> <div class="auth-buttons"> <a href="/login" class="btn btn-secondary">Se connecter</a> <a href="/register" class="btn btn-primary">Créer un compte</a> </div> </div> <!-- Liste des commentaires --> <div id="commentsList" class="comments-list"> <div class="loading"> <div class="spinner"></div> <p>Chargement des commentaires...</p> </div> </div> <!-- Pagination --> <div id="pagination" class="pagination"></div> </section> </main> <!-- Right Sidebar --> <aside class="aside"> <!-- Author Box --> <div class="aside-section"> <h3>À propos de l'auteur</h3> <div class="author-box"> <div class="author-avatar">CJ</div> <div class="author-info"> <h4>CodeurJava</h4> <p>Passionné de Java et de développement</p> </div> </div> </div> <!-- Related Articles --> <div class="aside-section"> <h3>Articles similaires</h3> <a href="https://www.codeurjava.com/ja/php/html、css、php、mysqlを使用したログインフォーム.html" class="related-article">HTML/CSS、PHP、MySQLによるログインフォーム</a> <a href="https://www.codeurjava.com/ja//asciiテーブルとヘキサからasciiへのコンバーター.html" class="related-article">テキスト/ASCIIコンバータ</a> <a href="https://www.codeurjava.com/ja/python/for-in-を使用して-python-でリストを参照する.html" class="related-article">Pythonでリストを閲覧する方法</a> <a href="https://www.codeurjava.com/ja/java/javaでハッシュマップを閲覧する方法.html" class="related-article">JavaでHashMapを閲覧する方法</a> </div> <!-- Tags --> <div class="aside-section"> <h3>Tags</h3> <div style="display: flex; flex-wrap: wrap; gap: 0.5rem; margin-top: 1rem;"> </div> </div> <!-- Newsletter --> <div class="aside-section" style="background: var(--gradient); color: white;"> <h3>Newsletter</h3> <p style="margin-bottom: 1rem; font-size: 0.9rem;">Recevez nos derniers articles directement dans votre boîte mail</p> <input type="email" placeholder="Votre email" style="width: 100%; padding: 0.8rem; border-radius: 10px; border: none; margin-bottom: 1rem;"> <button style="width: 100%; background: white; color: var(--primary-color); border: none; padding: 0.8rem; border-radius: 10px; font-weight: 600; cursor: pointer;">S'inscrire</button> </div> </aside> </div> <!-- Footer --> <footer class="article-footer"> <p>© 2025 CodeurJava. Tous droits réservés.</p> </footer> <script> // Configuration const API_BASE = '/api'; const ARTICLE_ID = 1; // À remplacer par l'ID réel de l'article let currentPage = 1; let totalPages = 1; let isAuthenticated = false; let currentUser = null; let csrfToken = ''; // Generate Table of Contents dynamically function generateTOC() { const tocList = document.getElementById('toc-list'); const headings = document.querySelectorAll('.article-content h2'); headings.forEach((heading, index) => { // Ensure heading has an ID if (!heading.id) { heading.id = 'section-' + index; } // Create TOC item const li = document.createElement('li'); const a = document.createElement('a'); a.href = '#' + heading.id; a.textContent = heading.textContent; if (index === 0) a.classList.add('active'); li.appendChild(a); tocList.appendChild(li); }); } // Call on page load document.addEventListener('DOMContentLoaded', generateTOC); // Progress Bar window.addEventListener('scroll', () => { const winScroll = document.body.scrollTop || document.documentElement.scrollTop; const height = document.documentElement.scrollHeight - document.documentElement.clientHeight; const scrolled = (winScroll / height) * 100; document.getElementById('progressBar').style.width = scrolled + '%'; }); // Table of Contents Active State window.addEventListener('scroll', () => { const sections = document.querySelectorAll('.article-content h2[id]'); const tocLinks = document.querySelectorAll('.toc-list a'); let current = ''; sections.forEach(section => { const sectionTop = section.offsetTop; if (scrollY >= (sectionTop - 200)) { current = section.getAttribute('id'); } }); tocLinks.forEach(link => { link.classList.remove('active'); if (link.getAttribute('href').slice(1) === current) { link.classList.add('active'); } }); }); // Smooth scrolling for TOC links document.addEventListener('click', (e) => { if (e.target.matches('.toc-list a')) { e.preventDefault(); const targetId = e.target.getAttribute('href').slice(1); const targetElement = document.getElementById(targetId); if (targetElement) { targetElement.scrollIntoView({ behavior: 'smooth', block: 'start' }); // Update URL without jumping history.pushState(null, null, '#' + targetId); } } }); // Header Scroll Effect window.addEventListener('scroll', () => { const header = document.querySelector('header'); if (window.scrollY > 100) { header.style.background = 'rgba(255, 255, 255, 0.98)'; header.style.boxShadow = '0 4px 30px rgba(0, 0, 0, 0.08)'; } else { header.style.background = 'rgba(255, 255, 255, 0.95)'; header.style.boxShadow = '0 2px 20px rgba(0, 0, 0, 0.05)'; } }); // Fonction pour initialiser prettyprint function initializePrettyPrint() { // Wrapper automatique des balises pre.prettyprint document.querySelectorAll('pre.prettyprint').forEach(pre => { if (!pre.parentElement.classList.contains('code-wrapper')) { const wrapper = document.createElement('div'); wrapper.className = 'code-wrapper'; const header = document.createElement('div'); header.className = 'code-header'; // Détecter le langage const langClass = Array.from(pre.classList).find(c => c.startsWith('lang-')); const lang = langClass ? langClass.replace('lang-', '').toUpperCase() : 'CODE'; header.innerHTML = ` <span class="code-language" data-lang="${lang.toLowerCase()}">${lang}</span> <button class="copy-button" onclick="copyCode(this)">Copier</button> `; pre.parentNode.insertBefore(wrapper, pre); wrapper.appendChild(header); wrapper.appendChild(pre); } }); // Si vous utilisez Google Prettify, décommentez cette ligne // PR.prettyPrint(); } // Fonction de copie du code function copyCode(button) { const codeBlock = button.closest('.code-wrapper').querySelector('pre'); const textArea = document.createElement('textarea'); textArea.value = codeBlock.textContent; document.body.appendChild(textArea); textArea.select(); document.execCommand('copy'); document.body.removeChild(textArea); button.textContent = 'Copié !'; button.classList.add('copied'); setTimeout(() => { button.textContent = 'Copier'; button.classList.remove('copied'); }, 2000); } // Coloration syntaxique simple (sans Google Prettify) function applySyntaxHighlighting() { document.querySelectorAll('pre.prettyprint').forEach(pre => { let code = pre.innerHTML; // Java keywords const javaKeywords = [ 'public', 'private', 'protected', 'class', 'interface', 'extends', 'implements', 'static', 'final', 'void', 'return', 'if', 'else', 'for', 'while', 'do', 'switch', 'case', 'break', 'continue', 'new', 'this', 'super', 'import', 'package', 'try', 'catch', 'finally', 'throw', 'throws', 'abstract', 'synchronized', 'volatile' ]; // Types const types = [ 'String', 'int', 'boolean', 'double', 'float', 'long', 'char', 'byte', 'short', 'Integer', 'Boolean', 'Double', 'Float', 'Long', 'Character', 'Byte', 'Short', 'List', 'ArrayList', 'Map', 'HashMap', 'Set', 'HashSet' ]; // Literals const literals = ['true', 'false', 'null']; // Apply highlighting // Comments code = code.replace(/(\/\/.*$)/gm, '<span class="com">$1</span>'); code = code.replace(/(\/\*[\s\S]*?\*\/)/g, '<span class="com">$1</span>'); // Strings code = code.replace(/(".*?")/g, '<span class="str">$1</span>'); code = code.replace(/('.')/g, '<span class="str">$1</span>'); // Numbers code = code.replace(/\b(\d+)\b/g, '<span class="lit">$1</span>'); // Keywords javaKeywords.forEach(keyword => { const regex = new RegExp('\\b(' + keyword + ')\\b', 'g'); code = code.replace(regex, '<span class="kwd">$1</span>'); }); // Types types.forEach(type => { const regex = new RegExp('\\b(' + type + ')\\b', 'g'); code = code.replace(regex, '<span class="typ">$1</span>'); }); // Literals literals.forEach(literal => { const regex = new RegExp('\\b(' + literal + ')\\b', 'g'); code = code.replace(regex, '<span class="lit">$1</span>'); }); pre.innerHTML = code; }); } // ======================================== // SYSTÈME DE COMMENTAIRES // ======================================== // Initialisation document.addEventListener('DOMContentLoaded', function() { checkAuthentication(); loadComments(); // Compteur de caractères document.getElementById('commentContent').addEventListener('input', function() { document.getElementById('charCount').textContent = this.value.length; }); }); // Vérifier l'authentification async function checkAuthentication() { try { const response = await fetch(`${API_BASE}/auth.php?action=check`); const data = await response.json(); isAuthenticated = data.loggedIn; currentUser = data.user; csrfToken = data.csrf_token || ''; // Afficher/masquer les éléments selon l'état d'authentification document.getElementById('commentForm').classList.toggle('hidden', !isAuthenticated); document.getElementById('authRequired').classList.toggle('hidden', isAuthenticated); } catch (error) { console.error('Erreur lors de la vérification d\'authentification:', error); } } // Charger les commentaires async function loadComments(page = 1) { try { const response = await fetch( `${API_BASE}/comments.php?action=get&article_id=${ARTICLE_ID}&page=${page}` ); const data = await response.json(); if (data.success) { renderComments(data.comments); updatePagination(data.pagination); document.getElementById('commentCount').textContent = data.pagination.total; } else { showAlert('Erreur lors du chargement des commentaires', 'error'); } } catch (error) { console.error('Erreur:', error); showAlert('Erreur de connexion au serveur', 'error'); } } // Afficher les commentaires function renderComments(comments) { const container = document.getElementById('commentsList'); if (comments.length === 0) { container.innerHTML = ` <div style="text-align: center; padding: 3rem; color: #64748b;"> Aucun commentaire pour le moment. Soyez le premier à commenter ! </div> `; return; } container.innerHTML = comments.map(comment => renderComment(comment)).join(''); } // Rendre un commentaire function renderComment(comment, isReply = false) { const initials = comment.username.substring(0, 2).toUpperCase(); const statusBadge = comment.status === 'pending' ? '<span class="comment-status status-pending">En attente</span>' : ''; return ` <div class="comment${isReply ? '-reply' : ''}" data-id="${comment.id}"> <div class="comment-header"> <div class="comment-author"> <div class="comment-avatar">${initials}</div> <div class="comment-author-info"> <span class="comment-author-name"> ${escapeHtml(comment.username)} ${comment.role === 'admin' || comment.role === 'moderator' ? `<span style="color: #10b981; font-size: 0.8rem;">✓ ${comment.role}</span>` : ''} </span> <span class="comment-date">${comment.formatted_date}</span> </div> </div> ${statusBadge} </div> <div class="comment-content"> ${escapeHtml(comment.content)} ${comment.is_edited ? '<span style="font-size: 0.8rem; color: #64748b;"> (modifié)</span>' : ''} </div> ${!isReply ? ` <div class="comment-actions"> <button class="comment-action ${comment.user_liked ? 'liked' : ''}" onclick="likeComment(${comment.id})"> <span>${comment.user_liked ? '❤️' : '🤍'}</span> <span>${comment.likes}</span> </button> <button class="comment-action" onclick="toggleReplyForm(${comment.id})"> 💬 Répondre </button> <button class="comment-action" onclick="reportComment(${comment.id})"> 🚩 Signaler </button> ${comment.can_edit ? ` <button class="comment-action" onclick="editComment(${comment.id})"> ✏️ Modifier </button> ` : ''} ${comment.can_delete ? ` <button class="comment-action" onclick="deleteComment(${comment.id})"> 🗑️ Supprimer </button> ` : ''} </div> <div id="replyForm${comment.id}" class="reply-form"> <textarea id="replyContent${comment.id}" class="comment-textarea" placeholder="Votre réponse..." style="min-height: 80px;" ></textarea> <div style="display: flex; gap: 1rem; justify-content: flex-end;"> <button class="btn btn-secondary" onclick="toggleReplyForm(${comment.id})"> Annuler </button> <button class="btn btn-primary" onclick="submitReply(${comment.id})"> Répondre </button> </div> </div> ` : ''} ${comment.replies && comment.replies.length > 0 ? ` <div class="comment-replies"> ${comment.replies.map(reply => renderComment(reply, true)).join('')} </div> ` : ''} ${comment.has_more_replies ? ` <button class="comment-action" style="margin-left: 3rem; margin-top: 0.5rem;" onclick="loadMoreReplies(${comment.id})"> Voir plus de réponses (${comment.reply_count - 3}) </button> ` : ''} </div> `; } // Soumettre un commentaire async function submitComment() { const content = document.getElementById('commentContent').value.trim(); if (content.length < 3) { showAlert('Le commentaire doit contenir au moins 3 caractères', 'error'); return; } try { const formData = new FormData(); formData.append('action', 'add'); formData.append('article_id', ARTICLE_ID); formData.append('content', content); formData.append('csrf_token', csrfToken); const response = await fetch(`${API_BASE}/comments.php`, { method: 'POST', body: formData }); const data = await response.json(); if (data.success) { document.getElementById('commentContent').value = ''; document.getElementById('charCount').textContent = '0'; showAlert(data.message || 'Commentaire publié', 'success'); loadComments(1); // Recharger la première page } else { showAlert(data.error || 'Erreur lors de la publication', 'error'); } } catch (error) { console.error('Erreur:', error); showAlert('Erreur de connexion au serveur', 'error'); } } // Soumettre une réponse async function submitReply(parentId) { const content = document.getElementById(`replyContent${parentId}`).value.trim(); if (content.length < 3) { showAlert('La réponse doit contenir au moins 3 caractères', 'error'); return; } try { const formData = new FormData(); formData.append('action', 'add'); formData.append('article_id', ARTICLE_ID); formData.append('content', content); formData.append('parent_id', parentId); formData.append('csrf_token', csrfToken); const response = await fetch(`${API_BASE}/comments.php`, { method: 'POST', body: formData }); const data = await response.json(); if (data.success) { toggleReplyForm(parentId); showAlert(data.message || 'Réponse publiée', 'success'); loadComments(currentPage); } else { showAlert(data.error || 'Erreur lors de la publication', 'error'); } } catch (error) { console.error('Erreur:', error); showAlert('Erreur de connexion au serveur', 'error'); } } // Liker un commentaire async function likeComment(commentId) { if (!isAuthenticated) { showAlert('Vous devez être connecté pour liker', 'info'); return; } try { const formData = new FormData(); formData.append('action', 'like'); formData.append('comment_id', commentId); formData.append('csrf_token', csrfToken); const response = await fetch(`${API_BASE}/comments.php`, { method: 'POST', body: formData }); const data = await response.json(); if (data.success) { loadComments(currentPage); } else { showAlert(data.error || 'Erreur', 'error'); } } catch (error) { console.error('Erreur:', error); showAlert('Erreur de connexion au serveur', 'error'); } } // Signaler un commentaire async function reportComment(commentId) { if (!isAuthenticated) { showAlert('Vous devez être connecté pour signaler', 'info'); return; } const reason = prompt('Raison du signalement:\n1. spam\n2. inappropriate\n3. harassment\n4. other'); if (!reason) return; const details = prompt('Détails supplémentaires (optionnel):'); try { const formData = new FormData(); formData.append('action', 'report'); formData.append('comment_id', commentId); formData.append('reason', reason); formData.append('details', details || ''); formData.append('csrf_token', csrfToken); const response = await fetch(`${API_BASE}/comments.php`, { method: 'POST', body: formData }); const data = await response.json(); if (data.success) { showAlert(data.message || 'Commentaire signalé', 'success'); } else { showAlert(data.error || 'Erreur', 'error'); } } catch (error) { console.error('Erreur:', error); showAlert('Erreur de connexion au serveur', 'error'); } } // Supprimer un commentaire async function deleteComment(commentId) { if (!confirm('Êtes-vous sûr de vouloir supprimer ce commentaire ?')) { return; } try { const formData = new FormData(); formData.append('action', 'delete'); formData.append('comment_id', commentId); formData.append('csrf_token', csrfToken); const response = await fetch(`${API_BASE}/comments.php`, { method: 'POST', body: formData }); const data = await response.json(); if (data.success) { showAlert('Commentaire supprimé', 'success'); loadComments(currentPage); } else { showAlert(data.error || 'Erreur', 'error'); } } catch (error) { console.error('Erreur:', error); showAlert('Erreur de connexion au serveur', 'error'); } } // Afficher/masquer le formulaire de réponse function toggleReplyForm(commentId) { const form = document.getElementById(`replyForm${commentId}`); form.classList.toggle('active'); if (form.classList.contains('active')) { document.getElementById(`replyContent${commentId}`).focus(); } } // Charger plus de réponses async function loadMoreReplies(commentId) { try { const response = await fetch( `${API_BASE}/comments.php?action=replies&comment_id=${commentId}` ); const data = await response.json(); if (data.success) { // Recharger les commentaires pour afficher toutes les réponses loadComments(currentPage); } } catch (error) { console.error('Erreur:', error); showAlert('Erreur lors du chargement des réponses', 'error'); } } // Pagination function updatePagination(pagination) { currentPage = pagination.current_page; totalPages = pagination.total_pages; const container = document.getElementById('pagination'); if (totalPages <= 1) { container.innerHTML = ''; return; } let html = ''; // Bouton précédent html += ` <button class="pagination-btn" onclick="loadComments(${currentPage - 1})" ${currentPage === 1 ? 'disabled' : ''}> ← Précédent </button> `; // Numéros de page for (let i = 1; i <= Math.min(totalPages, 5); i++) { html += ` <button class="pagination-btn ${i === currentPage ? 'active' : ''}" onclick="loadComments(${i})"> ${i} </button> `; } if (totalPages > 5) { html += `<span>...</span>`; html += ` <button class="pagination-btn ${totalPages === currentPage ? 'active' : ''}" onclick="loadComments(${totalPages})"> ${totalPages} </button> `; } // Bouton suivant html += ` <button class="pagination-btn" onclick="loadComments(${currentPage + 1})" ${currentPage === totalPages ? 'disabled' : ''}> Suivant → </button> `; container.innerHTML = html; } // Afficher une alerte function showAlert(message, type = 'info') { const alert = document.getElementById('alertMessage'); alert.className = `alert alert-${type} show`; alert.textContent = message; setTimeout(() => { alert.classList.remove('show'); }, 5000); } // Échapper le HTML function escapeHtml(text) { const div = document.createElement('div'); div.textContent = text; return div.innerHTML; } </script>