Форум программистов, компьютерный форум, киберфорум
PHP: сети
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
3 / 3 / 2
Регистрация: 27.06.2013
Сообщений: 96

CURL - 400 Bad Request

11.09.2015, 20:16. Показов 2363. Ответов 0
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Необходимо установить на МФУ Canon через web-интерфейс параметры копирования. С использованием CURL проходит вход в систему, первый вызов функции Submit работает, входит в систему и получает Cookie. Второй вызов функции при попытке изменить число копий отправляет Cookie (без отправки выводила сообщение, что время сессии истекло), но страница выводит сообщение Bad Request.

HTML5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
HTTP/1.1 400 Bad Request
Set-Cookie: sessid=UFgBfIzlRnOM3x8tkxnNrA##;path= /
pragma: no-cache
Cache-Control: no-store, no-cache, max-age=0
expires: Thu,01 Jan 1970 00:00:00 GMT
Accept-Ranges: bytes
Connection: close
 
<HTML>
<HEAD>
  <TITLE> 400 Bad Request </TITLE>
</HEAD>
<BODY>
  <H1> Bad Request </H1>
  <HR>
</BODY>
</HTML>
Используется следующий скрипт и запускается в командной строке php curl.php. Пытаюсь установить 40 копий.

PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?php
Submit('i0017=2&i0019=1&submitButton=Вход в систему', 'http://192.168.1.102', 'http://192.168.1.102/checkLogin.cgi', 1);
Submit('i0014=40&submitButton=OK', 'http://192.168.1.102/f_copy_edit.html', 'http://192.168.1.102/cgi/f_copy_edit.cgi', 2);
 
function Submit($PostFields, $Referer, $URL, $cookie)
{
if( $curl = curl_init() )
{
if ($cookie==1) curl_setopt($curl, CURLOPT_COOKIEJAR, '/srv/www/htdocs/php/test/sessid');
if ($cookie==2) curl_setopt($curl, CURLOPT_COOKIEFILE, '/srv/www/htdocs/php/test/sessid');
curl_setopt($curl, CURLOPT_POSTFIELDS, $PostFields);
curl_setopt($curl, CURLOPT_USERAGENT,'Mozilla 4.0 (compatible; MSIE 6.0; Win32');
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_URL, $URL);
curl_setopt($curl, CURLOPT_HEADER, true);
curl_setopt($curl, CURLOPT_REFERER, $Referer);
curl_setopt($curl, CURLOPT_RETURNTRANSFER,true);
curl_setopt($curl, CURLOPT_POST, true);
$out = curl_exec($curl);
echo $out;
curl_close($curl);
}
}
?>
Исходный код страницы, с которой работает вход в систему.

HTML5
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
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta http-equiv="content-script-type" content="text/javascript" />
<meta http-equiv="content-style-type" content="text/css" />
<meta http-equiv="pragma" content="no-cache" />
<meta http-equiv="cache-control" content="no-cache,no-store,max-age=0" />
<meta http-equiv="expires" content="Thu, 01 Jan 1970 00:00:00 GMT" />
<link rel="shortcut icon" type="image/x-icon" href="/media/favicon.ico" />
<link rel="icon" type="image/x-icon" href="/media/favicon.ico" />
<link rel="stylesheet" type="text/css" media="all" href="/css/common.css" />
<link rel="stylesheet" type="text/css" media="all" href="/css/login.css" />
<link rel="stylesheet" type="text/css" media="all" href="/css/ot.css" />
 
<script type="text/javascript" src="/js/rui.js"></script>
<script language="javascript">
<!--
function unloadFunc(e){}
registEvent(window,"unload",unloadFunc);
// -->
</script>
<script language="javascript">
<!--
function validate(e){
buttonDisabled();
document.forms[0].submit();
return true;
}
function changeMode(obj){
if(obj.name=="i0012" || obj.name=="i0016" || obj.name=="i0014"){
document.forms[0].i0012A.checked=true;
document.forms[0].i0017A.checked=false;
}
else{
document.forms[0].i0012A.checked=false;
document.forms[0].i0017A.checked=true;
}
}
function initControls(e){
var errCd = getQueryValue("err", "");
if(errCd == "1"){
alert("Неправильные сведения для аутентификации.\nВведите заново.");
document.location="/";
}
registEvent($I("submitButton"),"click",validate);
}
registEvent(window,"load",initControls);
// -->
</script>
<title>Удаленный ИП: Вход в системуimageRUNNER1133&nbsp;series:imageRUNNER1133&nbsp;series</title>
</head>
<body>
<div id="container">
<div id="loginWindow">
<div id="loginHeader">
<div id="corporateBranding">
<img src="/media/canonlogo.gif" alt="" title="" />
</div>
<div id="windowTitle">
<h1>Вход в систему</h1>
<p id="deviceType">
<span id="deviceName">imageRUNNER1133&nbsp;series / imageRUNNER1133&nbsp;series / </span>
</p>
</div>
<hr />
</div>
<form name="loginFrm" action="/checkLogin.cgi" autocomplete="off" method="post" onsubmit="return false;">
 
<input type="hidden" name="iToken" id="iToken" value="" />
 
<div id="login_contentsArea">
<div id="loginContentsWrapper">
<div id="loginContents">
<div class="LoginModule">
<table class="PropertyListComponent">
<tbody>
 
<tr>
<th colspan="2"><input type="radio" name="i0012" id="i0012A" value="1" onclick="changeMode(this)" /><label for="i0012A">Режим управления</label><br />
</th>
</tr>
<tr class="Sub">
<th>ИД администратора системы:</th>
<td><input type="text" name="i0014" id="i0014" class="Size_shortest" value="" maxlength="7" onfocus="changeMode(this)" autocomplete="off" />
</td>
</tr>
<tr class="Sub">
<th>PIN администратора системы:</th>
<td><input type="password" name="i0016" id="i0016" class="Size_shortest" value="" maxlength="7" onfocus="changeMode(this)" autocomplete="off" />
</td>
</tr>
<tr>
<th colspan="2"><input type="radio" name="i0017" id="i0017A" value="2" checked='checked' onclick="changeMode(this)" /><label for="i0017A">Режим пользователя</label><br />
</th>
</tr>
<tr class="Sub">
<th>Имя пользователя:</th>
<td><input type="text" name="i0019" id="i0019" class="Size_shortest" value="" maxlength="32" onfocus="changeMode(this)" autocomplete="off" />
</td>
</tr>
 
<!--
<tr>
<th></th>
<td></td>
</tr>
<tr>
<th></th>
<td></td>
</tr>
-->
</tbody>
</table>
</div>
<div class="LoginOperation">
<fieldset>
<input type="submit" id="submitButton" class="ButtonEnable" value="Вход в систему" />
</fieldset>
</div>
</div>
</div>
</div>
</form>
<hr />
<div id="applicationInfo">
<address class="SiteInforLegal">Copyright CANON INC. 2011 All Rights Reserved</address>
</div>
</div>
</div>
</body>
</html>
Она запускает файл checkLogin.cgi, который перенаправляет на страницу portal_top.html

Добавлено через 5 минут
Исходный код в браузере страницы f_copy_edit.html , с которой не работает переход через CURL на страницу f_copy.html с помощью файла f_copy_edit.cgi слишком длинный и не принимается форумом. Но и обратный переход с f_copy.html на f_copy_edit.html тоже не работает. Привожу как пример f_copy.html

HTML5
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
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta http-equiv="content-script-type" content="text/javascript" />
<meta http-equiv="content-style-type" content="text/css" />
<meta http-equiv="pragma" content="no-cache" />
<meta http-equiv="cache-control" content="no-cache,no-store,max-age=0" />
<meta http-equiv="expires" content="Thu, 01 Jan 1970 00:00:00 GMT" />
<link rel="shortcut icon" type="image/x-icon" href="/media/favicon.ico" />
<link rel="icon" type="image/x-icon" href="/media/favicon.ico" />
<link rel="stylesheet" type="text/css" media="all" href="/css/common.css" />
<link rel="stylesheet" type="text/css" media="all" href="/css/system_default.css" />
<link rel="stylesheet" type="text/css" media="all" href="/css/ot.css" />
<script type="text/javascript" src="/js/layoutFix_ie6.js"></script>
<script type="text/javascript" src="/js/rui.js"></script>
<script language="javascript">
<!--
function unloadFunc(e){}
registEvent(window,"unload",unloadFunc);
// -->
</script>
<title>Удаленный ИПНастройки копирования:imageRUNNER1133&nbsp;series:imageRUNNER1133&nbsp;series</title>
</head>
<body>
<div id="container">
<div id="ruiCommons">
<div class="Wrapper">
<div id="commonBranding">
<h1 id="deviceLogo">
<a href="/portal_top.html"><span>imageRUNNER</span></a>
</h1>
<p id="deviceType">
<span id="deviceName">imageRUNNER1133&nbsp;series / imageRUNNER1133&nbsp;series / </span>
</p>
</div>
<div id="commonTools">
<fieldset id="moveTools">
<p>
<a href="/portal_top.html"><span class="Name">К порталу</span></a>
</p>
</fieldset>
<fieldset id="authTools">
<p id="loginUserData">
<span class="Supplement"></span>
<span id="userName"></span>
</p>
<p>
<a href="/logout.cgi"><span class="Name">Выход из системы</span></a>
</p>
</fieldset>
</div>
</div>
<hr />
</div>
<div id="applications">
<div id="applicationBranding">
<div class="Wrapper">
<h1 id="applicationLogo">
<img src="/media/app_icon_default.png" alt="Параметры/Регистрация" title="Параметры/Регистрация" />
<span class="BrandingName">Параметры/Регистрация</span></h1>
<div id="appTools">
<table>
<tr>
<td><a href="mailto:"><span class="Name">Отправить эл. почтой администратору системы</span></a> </td>
<td><a href="/s_help.html" target="_blank"><span class="Name">Справка</span></a></td>
</tr>
</table>
</div>
</div>
</div>
<hr />
<div id="applicationContents">
<div class="Wrapper">
<div id="contentsWrapper">
<div id="contents">
<div id="navTopicPath">
Параметры/Регистрация: Настройки функций: Настройки копирования
</div>
<div id="contentHeading">
<h2 class="PageName">Настройки копирования</h2>
</div>
<div class="ContentOperation">
<fieldset class="TransitionOperation">
<input class="ButtonEnable" type="button" value="Исправить..." onclick="document.location='/f_copy_edit.html'" />
</fieldset>
</div>
<hr />
<div id="" class="ContentModule">
<div class="ModuleHeading">
<h4>Настройки копирования</h4>
</div>
<div id="" class="ModuleElement">
<table class="PropertyListComponent">
<tbody>
<tr>
<th>Кол-во копий:</th>
<td>35 Копий</td>
</tr>
<tr>
<th>Плотность:</th>
<td>0</td>
</tr>
<tr>
<th>Фон:</th>
<!--
<td></td>
-->
 
<td>Настройка</td>
 
 
<tr>
<th>Настройка:</th>
<td>0</td>
</tr>
 
 
<!--
<tr>
<th></th>
<td></td>
</tr>
<tr>
<th></th>
<td></td>
</tr>
<tr>
<th></th>
<td></td>
</tr>
-->
 
<!--
<tr>
<th></th>
<td></td>
</tr>
<tr>
<th></th>
<td></td>
</tr>
<tr>
<th></th>
<td></td>
</tr>
<tr>
<th></th>
<td></td>
</tr>
<tr>
<th></th>
<td></td>
</tr>
-->
<tr>
<th>Тип оригинала:</th>
<!--
<td></td>
-->
 
<td>Текст/Фото</td>
 
</tr>
<!--
<tr>
<th></th>
<td></td>
</tr>
-->
 
<tr>
<th>2-сторонняя:</th>
<td>Выкл.</td>
</tr>
<!--
<tr>
<th></th>
<td></td>
</tr>
-->
 
<!--
 
<tr>
<th></th>
<td></td>
</tr>
 
-->
 
<!--
<tr>
<th></th>
<td></td>
</tr>
-->
 
<tr>
<th>Коэффициент масшт.:</th>
 
<!--
<td></td>
-->
<!--
<td></td>
-->
 
<td>100% 1:1</td>
 
<!--
<td></td>
-->
 
<!--
<td></td>
-->
</tr>
<tr>
<th>Источник бумаги:</th>
<td>Кассета 1</td>
</tr>
<tr>
<th>N на 1:</th>
<td>Выкл.</td>
</tr>
<!--
<tr>
<th></th>
<td></td>
</tr>
</tbody>
<tr>
<th></th>
<td><img src="" alt="" title="" /> </td>
</tr>
-->
<tr>
<th>Сортировка:</th>
<td>Выкл.</td>
</tr>
<tr>
<th>Стирание рамки:</th>
<td>Выкл.</td>
</tr>
<!--
<tr>
<th></th>
 
<td></td>
 
 
<td></td>
 
</tr>
<tr>
<th></th>
<td></td>
</tr>
-->
<tr>
<th>Резкость:</th>
<td>0</td>
</tr>
</tbody>
</table>
</div>
</div>
<div id="tmpFooter">
<hr />
<div class="GotoTop">
<a href="javascript:scrollTo(0,0);"><img src="/media/ba_ptp.gif" alt="В начало страницы" title="В начало страницы" /></a>
</div>
</div>
</div>
</div>
<hr />
<div id="navigationWrapper">
<div id="navigation">
<ul class="Main">
<li class="MainItem">
<span class="GroupTitle">Настройки</span>
<ul class="Sub">
<li class="Standby"><a href="/p_paper.html">Установки бумаги</a></li>
<li class="Standby"><a href="/p_preference.html">Рег. громкости звука / Настройки отображения</a></li>
<li class="Standby"><a href="/p_timer.html">Настройки таймера</a></li>
</ul>
</li>
</ul>
<ul class="Main">
<li class="MainItem">
<span class="GroupTitle">Настройки функций</span>
<ul class="Sub">
<li class="Standby"><a href="/f_common.html">Общие настройки</a></li>
<li class="Selected"><a href="/f_copy.html">Настройки копирования</a></li>
<!--
<li class=""><a href=""></a></li>
-->
 
<li class="Standby"><a href="/f_scan.html">Настройки сканирования</a></li>
 
 
<li class="Standby"><a href="/f_external_interface.html">Настройки прямой печати из устр-ва USB</a></li>
 
 
<li class="Standby"><a href="/f_printer.html">Настройки принтера</a></li>
 
<!--
<li class=""><a href=""></a></li>
-->
</ul>
</li>
</ul>
<ul class="Main">
<li class="MainItem">
<span class="GroupTitle">Настройки системы</span>
<ul class="Sub">
<li class="Standby"><a href="/m_system.html">Настройки системы</a></li>
<!--
 
<li class=""><a href=""></a></li>
 
<li class=""><a href=""></a></li>
<li class=""><a href=""></a></li>
 
<li class=""><a href=""></a></li>
 
<li class=""><a href=""></a></li>
<li class=""><a href=""></a></li>
-->
</ul>
</li>
</ul>
</div>
</div>
</div>
</div>
<hr />
<div id="applicationInfo">
<address class="SiteInforLegal">Copyright CANON INC. 2011 All Rights Reserved</address>
</div>
</div>
</div>
</body>
</html>
В чем здесь может быть дело, почему в первом случае работает, а во втором случае не работает?

Добавлено через 18 часов 43 минуты
Проблема была в том, что надо отправлять все данные формы, а также случайное число iToken, которое определяю при чтении страницы. Теперь работает.
0
IT_Exp
Эксперт
34794 / 4073 / 2104
Регистрация: 17.06.2006
Сообщений: 32,602
Блог
11.09.2015, 20:16
Ответы с готовыми решениями:

Ошибка 400 Bad Request
Формирую вот такой запрос POST: POST index.php HTTP/1.1 Host: risris.cwahi.net Referer: http://risris.cwahi.net/index.php ...

ошибка: Bad Request (Invalid Hostname)
Переустановил денвер. Перехожу на http://localhost/index.php и вижу сее великолепие Bad Request (Invalid Hostname) апач выдает ошибки...

Авторизация curl (различие между curl и ajax запросами)
Есть ли различие в передаче данных в json формате через curl и ajax? Я хочу написать запрос, который будет авторизировать пользователя на...

0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
BasicMan
Эксперт
29316 / 5623 / 2384
Регистрация: 17.02.2009
Сообщений: 30,364
Блог
11.09.2015, 20:16
Помогаю со студенческими работами здесь

Curl команду превратить в php curl
команда: curl -s -F widget=$WIDGET -F secret=$SECRET -F amouser=$AMOUSER -F amohash=$AMOHASH -F domain=amocrm.ru -F widget=@$file...

Request.Response ошибка 400 bad request
Добрый день! Прошу помочь с обработкой запросов в Python 2.7.11 Принимать реквест и сохранить на сервере файл из него уже...

400 Bad request
Когда пытаюсь получить инфу с сайта, получаю 400 Bad Request, что делать?? Срочно, прошу!! #pragma optimize(&quot;t&quot;,on) ...

400 Bad Request
Ребят, помогите советом, пожалуйста. я уже устала... Проблема: При попытке воспользоваться Yandex-поиском вылезает: Bad Request ...

Ошибки Synapse (HTTP/1.1 400 Bad Request / HTTP/1.1 413 Request Entity Too Large)
Добрый день. При работе с Synapse начали возникать вот такие вот две ошибки (HTTP/1.1 400 Bad Request / HTTP/1.1 413 Request Entity Too...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
1
Ответ Создать тему
Новые блоги и статьи
http://iceja.net/ математические сервисы
iceja 20.01.2026
Обновила свой сайт http:/ / iceja. net/ , приделала Fast Fourier Transform экстраполяцию сигналов. Однако предсказывает далеко не каждый сигнал (см ограничения http:/ / iceja. net/ fourier/ docs ). Также. . .
http://iceja.net/ сервер решения полиномов
iceja 18.01.2026
Выкатила http:/ / iceja. net/ сервер решения полиномов (находит действительные корни полиномов методом Штурма). На сайте документация по API, но скажу прямо VPS слабенький и 200 000 полиномов. . .
Расчёт переходных процессов в цепи постоянного тока
igorrr37 16.01.2026
/ * Дана цепь постоянного тока с R, L, C, k(ключ), U, E, J. Программа составляет систему уравнений по 1 и 2 законам Кирхгофа, решает её и находит переходные токи и напряжения на элементах схемы. . . .
Восстановить юзерскрипты Greasemonkey из бэкапа браузера
damix 15.01.2026
Если восстановить из бэкапа профиль Firefox после переустановки винды, то список юзерскриптов в Greasemonkey будет пустым. Но восстановить их можно так. Для этого понадобится консольная утилита. . .
Сукцессия микоризы: основная теория в виде двух уравнений.
anaschu 11.01.2026
https:/ / rutube. ru/ video/ 7a537f578d808e67a3c6fd818a44a5c4/
WordPad для Windows 11
Jel 10.01.2026
WordPad для Windows 11 — это приложение, которое восстанавливает классический текстовый редактор WordPad в операционной системе Windows 11. После того как Microsoft исключила WordPad из. . .
Classic Notepad for Windows 11
Jel 10.01.2026
Old Classic Notepad for Windows 11 Приложение для Windows 11, позволяющее пользователям вернуть классическую версию текстового редактора «Блокнот» из Windows 10. Программа предоставляет более. . .
Почему дизайн решает?
Neotwalker 09.01.2026
В современном мире, где конкуренция за внимание потребителя достигла пика, дизайн становится мощным инструментом для успеха бренда. Это не просто красивый внешний вид продукта или сайта — это. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru