|
| 1 | + |
| 2 | +//And I heard a loud voice saying in heaven, Now is come salvation, and strength, and the kingdom of our God, |
| 3 | +//and the power of his Christ: for the accuser of our brethren is cast down, which accused them before our God day and night. (Revelation 12:10) |
| 4 | + |
| 5 | +package com.javarush.task.task40.task4001; |
| 6 | + |
| 7 | +import java.io.BufferedReader; |
| 8 | +import java.io.DataOutputStream; |
| 9 | +import java.io.InputStreamReader; |
| 10 | +import java.io.OutputStream; |
| 11 | +import java.net.HttpURLConnection; |
| 12 | +import java.net.URL; |
| 13 | + |
| 14 | +/* |
| 15 | +POST, а не GET |
| 16 | +*/ |
| 17 | + |
| 18 | +public class Solution { |
| 19 | + public static void main(String[] args) throws Exception { |
| 20 | + Solution solution = new Solution(); |
| 21 | + solution.sendPost(new URL("http://requestb.in/1cse9qt1"), "name=zapp&mood=good&locale=&id=777"); |
| 22 | + } |
| 23 | + |
| 24 | + public void sendPost(URL url, String urlParameters) throws Exception { |
| 25 | + HttpURLConnection connection = (HttpURLConnection) url.openConnection(); |
| 26 | + |
| 27 | + connection.setRequestMethod("POST"); |
| 28 | + connection.setRequestProperty("User-Agent", "Mozilla/5.0"); |
| 29 | + connection.setDoOutput(true); |
| 30 | + OutputStream outputStream = connection.getOutputStream(); |
| 31 | + outputStream.write(urlParameters.getBytes()); |
| 32 | + outputStream.flush(); |
| 33 | + outputStream.close(); |
| 34 | + |
| 35 | + int responseCode = connection.getResponseCode(); |
| 36 | + System.out.println("Response Code: " + responseCode); |
| 37 | + |
| 38 | + BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream())); |
| 39 | + String responseLine; |
| 40 | + StringBuilder response = new StringBuilder(); |
| 41 | + |
| 42 | + while ((responseLine = bufferedReader.readLine()) != null) { |
| 43 | + response.append(responseLine); |
| 44 | + } |
| 45 | + bufferedReader.close(); |
| 46 | + |
| 47 | + System.out.println("Response: " + response.toString()); |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | +/* |
| 52 | +POST, а не GET |
| 53 | +
|
| 54 | +Исправь ошибки в методе sendPost, чтобы он отправлял POST-запрос с переданными параметрами. |
| 55 | +
|
| 56 | +Примечание: метод main в тестировании не участвует, но чтобы программа корректно работала локально, можешь зайти на сайт http://requestb.in/, создать свой RequestBin и использовать его в main. |
| 57 | +
|
| 58 | +
|
| 59 | +
|
| 60 | +
|
| 61 | +
|
| 62 | +Требования: |
| 63 | +
|
| 64 | +1. Метод sendPost должен вызвать метод setRequestMethod с параметром "POST". |
| 65 | +
|
| 66 | +2. Метод sendPost должен устанавливать флаг doOutput у соединения в true. |
| 67 | +
|
| 68 | +3. В OutputStream соединения должны быть записаны переданные в метод sendPost параметры. |
| 69 | +
|
| 70 | +4. Метод sendPost должен выводить результат своей работы на экран. |
| 71 | +*/ |
0 commit comments