-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBatch_HttpRequest(Double_loop).html
More file actions
427 lines (395 loc) · 23.5 KB
/
Copy pathBatch_HttpRequest(Double_loop).html
File metadata and controls
427 lines (395 loc) · 23.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
<!DOCTYPE html>
<html lang="zh-Hant">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>API批量請求器 (標準版)</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<style>
:root { --primary: #007bff; --success: #28a745; --danger: #dc3545; --light-bg: #f8f9fa; --shadow: 0 4px 12px rgba(0,0,0,0.1); }
body { background: var(--light-bg); font-family: 'Segoe UI', sans-serif; }
.container { max-width: 1000px; padding: 20px; }
.card { border: none; border-radius: 10px; box-shadow: var(--shadow); margin-bottom: 20px; }
.card-body { padding: 15px; }
.card-title { font-size: 1.2rem; font-weight: 600; color: var(--primary); }
.flow-arrow { font-size: 2rem; color: var(--primary); text-align: center; margin: 10px 0; }
.table-container, .request-status { max-height: 300px; overflow-y: auto; }
.table th { background: var(--primary); color: white; position: sticky; top: 0; z-index: 1; min-width: 120px; }
.btn-group { gap: 8px; flex-wrap: wrap; }
.status-item { padding: 8px; border-bottom: 1px solid #e9ecef; }
.status-success { background: #d4edda; } .status-error { background: #f8d7da; }
.result { font-size: 0.85rem; padding: 6px; background: #f1f3f5; border-radius: 6px; margin-top: 5px; cursor: pointer; }
.result.success { color: #155724; border-left: 4px solid var(--success); }
.result.error { color: #721c24; border-left: 4px solid var(--danger); }
.preview-box { background: #e9ecef; padding: 8px; border-radius: 5px; max-height: 300px; overflow-y: auto; font-size: 0.9rem; }
.step-icon { font-size: 1.5rem; color: var(--primary); margin-right: 8px; }
.help-text { font-size: 0.9rem; color: #6c757d; margin-top: 5px; }
.advanced-settings { display: none; }
.advanced-settings.show { display: block; }
</style>
</head>
<body>
<div class="container">
<h2 class="mb-4 text-center text-primary">批量自訂參數的HTTP請求器(雙循環_主項及TSV格式參數)</h2>
<!-- 操作說明 -->
<div class="card mb-3">
<div class="card-body">
<h5 class="card-title">操作說明</h5>
<p class="help-text">
1. 設置請求模板:選擇 GET 或 POST,輸入 URL 模板和(若為 POST)請求體模板,使用 {InputValue} 和 {ParameterX} 作為占位符。<br>
2. 輸入主值:每行一個主值,每個主值會觸發一輪請求。<br>
3. 設置參數組:每行一組參數,生成對應的請求。<br>
4. 進階設置:點擊「進階設置」調整請求間隔和授權選項。<br>
5. 發送並查看結果:點擊發送後查看請求預覽和結果。
</p>
</div>
</div>
<!-- 配置管理 -->
<div class="card mb-3">
<div class="card-body d-flex justify-content-center btn-group">
<button class="btn btn-warning" id="clear-storage" title="清空所有配置和數據">清空配置</button>
<button class="btn btn-info" id="export-config" title="將當前配置匯出為 JSON 文件">匯出配置</button>
<input type="file" id="import-config" accept=".json" hidden>
<button class="btn btn-primary" id="import-config-btn" title="從 JSON 文件匯入配置">匯入配置</button>
</div>
</div>
<!-- 步驟 1:設置請求模板 -->
<div class="card">
<div class="card-body">
<h5 class="card-title"><span class="step-icon">①</span>設置請求模板</h5>
<div class="mb-3">
<label for="request-method" class="form-label">請求方法</label>
<select class="form-select" id="request-method">
<option value="GET">GET</option>
<option value="POST">POST (JSON)</option>
</select>
<small class="form-text text-muted">選擇 HTTP 請求類型</small>
</div>
<div class="mb-3">
<label for="url-template" class="form-label">URL 模板</label>
<input type="text" class="form-control" id="url-template" placeholder="例如: https://api.example.com/?id={InputValue}&key={Parameter1}">
<small class="form-text text-muted">使用 {InputValue} 和 {ParameterX} 作為動態占位符</small>
</div>
<div id="post-config" hidden>
<div class="mb-3">
<label for="post-body-template" class="form-label">POST 請求體模板</label>
<textarea class="form-control" id="post-body-template" rows="2" placeholder='例如: {"id": "{InputValue}", "key": "{Parameter1}"}'></textarea>
<small class="form-text text-muted">輸入有效的 JSON 格式,使用 {InputValue} 和 {ParameterX} 替換</small>
</div>
</div>
<button class="btn btn-outline-secondary mt-2" id="toggle-advanced">進階設置</button>
<div class="advanced-settings" id="advanced-settings">
<div class="mt-3">
<label for="request-delay" class="form-label">每次請求間隔 (毫秒)</label>
<input type="number" class="form-control" id="request-delay" min="0" value="3000" step="100">
<small class="form-text text-muted">設置為 0 表示無間隔,建議 500ms 或以上以避免過載</small>
</div>
<div class="mt-3">
<label class="form-label">啟用 HTTP Authorization</label>
<div class="form-check">
<input class="form-check-input" type="checkbox" id="enable-auth">
<label class="form-check-label" for="enable-auth">啟用</label>
</div>
<small class="form-text text-muted">啟用後可設置認證頭</small>
</div>
<div id="auth-config" hidden>
<div class="mt-3">
<label for="auth-type" class="form-label">Authorization 類型</label>
<select class="form-select" id="auth-type">
<option value="Basic">Basic</option>
<option value="Bearer">Bearer</option>
</select>
<small class="form-text text-muted">Basic 使用用戶名和密碼,Bearer 使用 Token</small>
</div>
<div id="basic-auth-fields" hidden>
<div class="mt-3">
<label for="auth-username" class="form-label">用戶名</label>
<input type="text" class="form-control" id="auth-username" placeholder="輸入用戶名">
<small class="form-text text-muted">用於 Basic 認證</small>
</div>
<div class="mt-3">
<label for="auth-password" class="form-label">密碼</label>
<input type="password" class="form-control" id="auth-password" placeholder="輸入密碼">
<small class="form-text text-muted">用於 Basic 認證</small>
</div>
</div>
<div id="bearer-auth-field" hidden>
<div class="mt-3">
<label for="auth-token" class="form-label">Bearer Token</label>
<input type="text" class="form-control" id="auth-token" placeholder="輸入 API Token">
<small class="form-text text-muted">輸入完整的 Bearer Token</small>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- 步驟 2:輸入主值 -->
<div class="card">
<div class="card-body">
<h5 class="card-title"><span class="step-icon">②</span>輸入主值 (每個值發起一輪請求[每一輪有多組請求])</h5>
<div class="mb-3">
<label for="input-values" class="form-label">主值列表</label>
<textarea class="form-control" id="input-values" rows="3" placeholder="每行一個,例如:
ID1
ID2"></textarea>
<small class="form-text text-muted">每個主值將觸發一輪請求</small>
</div>
</div>
</div>
<div class="flow-arrow">↓</div>
<!-- 步驟 3:設置參數組 -->
<div class="card">
<div class="card-body">
<h5 class="card-title"><span class="step-icon">③</span> 設置參數組 (每組生成一個請求)</h5>
<div class="mb-3">
<label for="batch-input" class="form-label">批量參數輸入</label>
<textarea class="form-control" id="batch-input" rows="2" placeholder="每行一組,例如:
key1 value1
key2 value2"></textarea>
<small class="form-text text-muted">每行一組參數,用空格分隔多項</small>
</div>
<div class="btn-group mb-2">
<button class="btn btn-primary" id="batch-submit" title="將輸入的參數添加到表格">添加</button>
<button class="btn btn-secondary" id="add-row" title="添加一行空的參數行">加一行</button>
<button class="btn btn-secondary" id="add-column" title="為表格添加一列">加一項</button>
</div>
<div class="table-container">
<table class="table table-bordered table-striped">
<thead><tr id="table-header"></tr></thead>
<tbody id="data-table"></tbody>
</table>
</div>
</div>
</div>
<div class="flow-arrow">↓</div>
<!-- 步驟 4:生成並發送 -->
<div class="card">
<div class="card-body">
<h5 class="card-title"><span class="step-icon">④</span>生成並發送請求</h5>
<button class="btn btn-success mb-2" id="send-request" title="發送所有生成的請求">發送</button>
<div id="request-preview" class="preview-box">點擊「發送」後顯示預覽</div>
</div>
</div>
<!-- 步驟 5:查看結果 -->
<div class="card">
<div class="card-body request-status">
<h5 class="card-title"><span class="step-icon">⑤</span>查看結果</h5>
<div class="progress mb-2" id="total-progress">
<div class="progress-bar" role="progressbar" style="width: 0%;" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>
</div>
<div id="status-container"></div>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
const elements = {
tableBody: document.getElementById('data-table'),
tableHeader: document.getElementById('table-header'),
statusContainer: document.getElementById('status-container'),
requestPreview: document.getElementById('request-preview'),
totalProgress: document.getElementById('total-progress').querySelector('.progress-bar')
};
let paramCount = 0;
// 表格操作
function updateTableHeader(count) {
elements.tableHeader.innerHTML = Array.from({ length: count }, (_, i) => `<th>參數${i + 1}</th>`).join('');
paramCount = count;
Array.from(elements.tableBody.rows).forEach(row => {
while (row.cells.length < count) row.innerHTML += '<td><input type="text" class="form-control" value=""></td>';
});
saveConfig();
}
function addRow(data = []) {
const row = elements.tableBody.insertRow();
const count = Math.max(data.length, paramCount || 1);
updateTableHeader(count);
row.innerHTML = Array.from({ length: count }, (_, i) => `<td><input type="text" class="form-control" value="${data[i] || ''}" oninput="saveConfig()"></td>`).join('');
saveConfig();
}
// 配置管理
function saveConfig() {
const tableData = Array.from(elements.tableBody.rows).map(row => Array.from(row.querySelectorAll('input')).map(input => input.value));
const config = {
tableData, inputValues: $('#input-values').value, method: $('#request-method').value,
urlTemplate: $('#url-template').value, postBody: $('#post-body-template').value,
delay: $('#request-delay').value, enableAuth: $('#enable-auth').checked,
authType: $('#auth-type').value, authUsername: $('#auth-username').value,
authPassword: $('#auth-password').value, authToken: $('#auth-token').value
};
localStorage.setItem('requestConfig', JSON.stringify(config));
}
function loadConfig() {
const config = JSON.parse(localStorage.getItem('requestConfig') || '{}');
elements.tableBody.innerHTML = '';
(config.tableData || []).forEach(addRow);
$('#input-values').value = config.inputValues || '';
$('#request-method').value = config.method || 'GET';
$('#url-template').value = config.urlTemplate || '';
$('#post-body-template').value = config.postBody || '';
$('#request-delay').value = config.delay || '3000';
$('#enable-auth').checked = config.enableAuth || false;
$('#auth-type').value = config.authType || 'Basic';
$('#auth-username').value = config.authUsername || '';
$('#auth-password').value = config.authPassword || '';
$('#auth-token').value = config.authToken || '';
$('#post-config').hidden = config.method !== 'POST';
$('#auth-config').hidden = !config.enableAuth;
$('#basic-auth-fields').hidden = !(config.enableAuth && config.authType === 'Basic');
$('#bearer-auth-field').hidden = !(config.enableAuth && config.authType === 'Bearer');
}
function clearConfig() {
if (confirm('確定清空所有數據?')) {
localStorage.clear();
location.reload();
}
}
function exportConfig() {
const config = localStorage.getItem('requestConfig');
const blob = new Blob([config], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `request-config-${new Date().toISOString().split('T')[0]}.json`;
a.click();
URL.revokeObjectURL(url);
}
function importConfig(e) {
const file = e.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = e => {
localStorage.setItem('requestConfig', e.target.result);
loadConfig();
elements.statusContainer.innerHTML = '<div class="alert alert-success">已匯入</div>';
};
reader.readAsText(file);
$('#import-config').value = '';
}
// 請求處理
async function sendRequest(method, url, body) {
const options = { method };
if ($('#enable-auth').checked) {
const authType = $('#auth-type').value;
options.headers = options.headers || {};
if (authType === 'Basic') {
const username = $('#auth-username').value.trim();
const password = $('#auth-password').value.trim();
if (!username || !password) throw new Error('Basic Auth 需要用戶名和密碼');
options.headers['Authorization'] = `Basic ${btoa(`${username}:${password}`)}`;
} else if (authType === 'Bearer') {
const token = $('#auth-token').value.trim();
if (!token) throw new Error('Bearer Auth 需要 Token');
options.headers['Authorization'] = `Bearer ${token}`;
}
}
if (method === 'POST' && body) {
options.headers = options.headers || {};
options.headers['Content-Type'] = 'application/json';
options.body = JSON.stringify(body);
}
try {
const response = await fetch(url, options);
return { success: true, data: await response.text() };
} catch (error) {
return { success: false, error: error.message };
}
}
function formatResult(text, success) {
const max = 100;
return text.length > max ? { short: `${text.slice(0, max)} ... (點擊展開)`, full: text } : { short: text, full: text };
}
// 事件綁定
$('#batch-submit').addEventListener('click', () => {
const lines = $('#batch-input').value.trim().split('\n').map(line => line.trim().split(/\s+/));
lines.forEach(addRow);
$('#batch-input').value = '';
});
$('#add-row').addEventListener('click', () => addRow());
$('#add-column').addEventListener('click', () => updateTableHeader(paramCount + 1));
$('#request-method').addEventListener('change', e => { $('#post-config').hidden = e.target.value !== 'POST'; saveConfig(); });
$('#toggle-advanced').addEventListener('click', () => $('#advanced-settings').classList.toggle('show'));
$('#enable-auth').addEventListener('change', e => {
const authConfig = $('#auth-config');
authConfig.hidden = !e.target.checked;
const authType = $('#auth-type').value;
$('#basic-auth-fields').hidden = !(e.target.checked && authType === 'Basic');
$('#bearer-auth-field').hidden = !(e.target.checked && authType === 'Bearer');
saveConfig();
});
$('#auth-type').addEventListener('change', e => {
const enableAuth = $('#enable-auth').checked;
$('#basic-auth-fields').hidden = !(enableAuth && e.target.value === 'Basic');
$('#bearer-auth-field').hidden = !(enableAuth && e.target.value === 'Bearer');
saveConfig();
});
['input-values', 'url-template', 'post-body-template', 'request-delay', 'auth-username', 'auth-password', 'auth-token'].forEach(id => {
$('#' + id).addEventListener('input', saveConfig);
});
$('#send-request').addEventListener('click', async () => {
const inputValues = $('#input-values').value.trim().split('\n').filter(Boolean);
const rows = elements.tableBody.rows;
const method = $('#request-method').value;
const delay = parseInt($('#request-delay').value) || 0;
if (!inputValues.length || !rows.length) {
elements.statusContainer.innerHTML = '<div class="alert alert-warning">請輸入主值和參數組</div>';
return;
}
elements.statusContainer.innerHTML = '';
elements.requestPreview.innerHTML = '';
let count = 0;
const total = inputValues.length * rows.length;
for (let i = 0; i < inputValues.length; i++) {
const inputValue = inputValues[i];
const params = { InputValue: inputValue };
elements.requestPreview.innerHTML += `<strong>主值 ${i + 1}: ${inputValue}</strong><br>`;
for (let j = 0; j < rows.length; j++) {
Array.from(rows[j].querySelectorAll('input')).forEach((input, k) => params[`Parameter${k + 1}`] = input.value);
const statusItem = elements.statusContainer.appendChild(document.createElement('div'));
statusItem.className = 'status-item';
statusItem.innerHTML = `
<div>請求 ${count + 1}/${total} (主值 ${i + 1}, 組 ${j + 1})</div>
<div class="progress"><div class="progress-bar" style="width: 50%;"></div></div>
<div class="result-container mt-2"></div>
`;
const progress = statusItem.querySelector('.progress-bar');
const resultContainer = statusItem.querySelector('.result-container');
let url = $('#url-template').value;
let body;
for (const [key, val] of Object.entries(params)) url = url.replace(new RegExp(`{${key}}`, 'g'), encodeURIComponent(val));
if (method === 'POST') {
body = JSON.parse($('#post-body-template').value.replace(/{InputValue}|{Parameter\d+}/g, m => params[m.slice(1, -1)] || ''));
elements.requestPreview.innerHTML += `組 ${j + 1}: ${url} (資料: ${JSON.stringify(body)})<br>`;
} else {
elements.requestPreview.innerHTML += `組 ${j + 1}: ${url}<br>`;
}
const response = await sendRequest(method, url, body);
progress.style.width = '100%';
progress.classList.add(response.success ? 'bg-success' : 'bg-danger');
statusItem.classList.add(response.success ? 'status-success' : 'status-error');
const formatted = formatResult(response.success ? `成功:${response.data}` : `失敗:${response.error}`, response.success);
resultContainer.innerHTML = `<div class="result ${response.success ? 'success' : 'error'}">${formatted.short}</div>`;
resultContainer.dataset.full = formatted.full;
count++;
elements.totalProgress.style.width = `${(count / total) * 100}%`;
if (delay) await new Promise(resolve => setTimeout(resolve, delay));
}
elements.requestPreview.innerHTML += '<br>';
}
});
elements.statusContainer.addEventListener('click', e => {
if (e.target.classList.contains('result')) {
const container = e.target.parentElement;
e.target.textContent = e.target.textContent.includes('點擊展開') ? container.dataset.full : formatResult(container.dataset.full, e.target.classList.contains('success')).short;
}
});
$('#clear-storage').addEventListener('click', clearConfig);
$('#export-config').addEventListener('click', exportConfig);
$('#import-config-btn').addEventListener('click', () => $('#import-config').click());
$('#import-config').addEventListener('change', importConfig);
document.addEventListener('DOMContentLoaded', loadConfig);
function $(selector) { return document.getElementById(selector.replace('#', '')); }
</script>
</body>
</html>