1.1.43. fejezet, RestEasy kliens
Beküldte pzoli - 2021, március 15 - 4:41du
package hu.infokristaly.rest; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.StringReader; import java.net.HttpURLConnection; import java.net.URL; import javax.json.Json; import javax.json.JsonObject; import javax.json.JsonReader; public class RestApiClient { private static JsonObject sendPostRequest(String urlString, String body, String userName, String password) throws Exception { URL url = new URL(urlString); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("Content-Type", "application/json; utf-8"); con.setRequestProperty("Username", userName); con.setRequestProperty("Password", password); con.setRequestProperty("cache-control", "no-cache"); con.setDoOutput(true); try(OutputStream os = con.getOutputStream()) { byte[] input = body.getBytes("utf-8"); os.write(input, 0, input.length); } InputStream stream = con.getInputStream(); InputStreamReader reader = new InputStreamReader(stream,"UTF-8"); BufferedReader br = new BufferedReader(reader); StringBuilder jsonString = new StringBuilder(); String line; while ((line = br.readLine()) != null) { jsonString.append(line); } br.close(); JsonReader jsonReader = Json.createReader(new StringReader(jsonString.toString())); JsonObject jsonObject = jsonReader.readObject(); return jsonObject; } public static void main(String[] args) { String body = "{\"cim\":\"RestEasy teszt\",\"leiras\":\"<p>Árvíztűrő tükörfúró gép.</p>\",\"kategoria\":{\"id\":1},\"telepules\":{\"id\":1},\"tavmunka\":true,\"reszmunkaido\":false,\"validFrom\":1614553200000,\"validTo\":1617141600000,\"url\":\"https://infokristaly.hu\"}"; try { JsonObject jsonObject = sendPostRequest("http://localhost:8080/hirdetesek/rest/hirdetesek/",body,"a@b.hu","q"); System.out.println(jsonObject.toString()); } catch (Exception e) { e.printStackTrace(); } } }
- A hozzászóláshoz be kell jelentkezni