JavaRush /Java блог /Архив info.javarush /JSOUP + multipart/form-data response
wildsinner
41 уровень
Самара

JSOUP + multipart/form-data response

Статья из группы Архив info.javarush
Добрый день, В общем необходимо отправить на сайт данные в виде ответа в форме multipart/form-data. Перехватить запрос генерируемый браузером труда не составляет, но выполнить такой же с помощью JSOUP вызывает сложности. В качестве примера можно взять простейшую форму, которая сгенирирует нужный запрос.
Request Headers Provisional headers are shown Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryjtkXVNw9YVG1H2P9 Origin:null Upgrade-Insecure-Requests:1 User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36 X-DevTools-Emulate-Network-Conditions-Client-Id:8DCCE949-56FA-4AB0-81B7-DA2BC7960E5C ->Request Payload ------WebKitFormBoundaryjtkXVNw9YVG1H2P9 Content-Disposition: form-data; name="text" text default ------WebKitFormBoundaryjtkXVNw9YVG1H2P9 Content-Disposition: form-data; name="file1"; filename="" Content-Type: application/octet-stream ------WebKitFormBoundaryjtkXVNw9YVG1H2P9 Content-Disposition: form-data; name="file2"; filename="" Content-Type: application/octet-stream ------WebKitFormBoundaryjtkXVNw9YVG1H2P9-- Я пытался различными способами сгенирировать аналогичный запрос различными вариантами, и остановился на таком, но пока "танцы с бубнами" не дают результатов. Map responseMap= new HashMap(); String key1 = "------WebKitFormBoundary9A3GpeDAwfa0TBDK\r\n" + "Content-Disposition: form-data; name=\"text\"\r\n\r\n"; String value1 = "text default"; headersMap.put(key1, value1); String key2 = "\r\n------WebKitFormBoundary9A3GpeDAwfa0TBDK\r\n" + "Content-Disposition: form-data; name=\"doc_sma_ref_file\"; filename=\"\"" + "\r\nContent-Type: application/octet-stream\r\n\r\n"; String value2 = ""; headersMap.put(key2, value2); String key3 = "\r\n------WebKitFormBoundary9A3GpeDAwfa0TBDK\r\n" + "Content-Disposition: form-data; name=\"doc_val_ref_file\"; filename=\"\"" + "\r\nContent-Type: application/octet-stream\r\n\r\n"; String value3 = ""; headersMap.put(key3, value3); String key4 = "\r\n------WebKitFormBoundary9A3GpeDAwfa0TBDK--"; String value4 = ""; headersMap.put(key4, value4); Connection.Response resBGT = Jsoup.connect(URL) .header("Content-Type", "multipart/form-data; boundary=----WebKitFormBoundary9A3GpeDAwfa0TBDK") .userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36") .followRedirects(true) .data(responseMap) .cookies(cookies) .ignoreHttpErrors(true) .timeout(15000) .method(Connection.Method.POST) .execute(); Возможно у кого-то есть опыт в данном вопросе. Если вас не затруднит направьте на путь истинный. Также возможно, есть способ перехватить запрос сгенирированный JSOUP, что впринципе также позволило бы продвинутся дальше. Спасибо
Комментарии (8)
ЧТОБЫ ПОСМОТРЕТЬ ВСЕ КОММЕНТАРИИ ИЛИ ОСТАВИТЬ КОММЕНТАРИЙ,
ПЕРЕЙДИТЕ В ПОЛНУЮ ВЕРСИЮ
wildsinner Уровень 41
12 января 2016
Если кому интересно, решение нашлось и достаточно простое.
File file1 = new File("C:/dir/file1.txt");
File file2 = new File("C:/dir/file2.txt");
FileInputStream fs1 = new FileInputStream(file1);
FileInputStream fs2 = new FileInputStream(file2);
Connection.Response response = Jsoup.connect("http://www.example.com")
        .data("text", "value")
        .data("file1", "filename", fs1)
        .data("file2", "filename", fs2)
        .userAgent("Mozilla")
        .method(Method.POST)
        .execute();
Alexey90 Уровень 32
28 декабря 2015
привет, в свое время пытался дернуть расписание своего инста, делал так:

HttpURLConnection urlConnection = null;
        BufferedReader reader = null;
        String resut = "";// получаем данные с внешнего ресурса
        try

        {
            URL url = new URL("http://gu-unpk.ru/schedule");
            urlConnection = (HttpURLConnection) url.openConnection(); //открываем соединение
            urlConnection.setRequestMethod("GET");
            urlConnection.setRequestProperty("Host", "gu-unpk.ru");
            urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:41.0) Gecko/20100101 Firefox/41.0");
            urlConnection.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
            urlConnection.setRequestProperty("Accept-Language", "ru-RU,ru;q=0.8,en-US;q=0.5,en;q=0.3");
//            urlConnection.setRequestProperty("Accept-Encoding", "gzip, deflate");
            urlConnection.setRequestProperty("Referer", "http://gu-unpk.ru/");
            urlConnection.setRequestProperty("Cookie", "длинная строка с куками");
            urlConnection.setRequestProperty("Connection", "keep-alive");
            urlConnection.setRequestProperty("Cache-Control", "max-age=0");

            urlConnection.connect(); //подключаемся
            InputStream inputStream = urlConnection.getInputStream();//поток ввода
            StringBuffer buffer = new StringBuffer(); //в эту переменную будем читать
            reader = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            while ((line = reader.readLine()) != null)
            {  //читаем строку из потока
                buffer.append