programing

Java에서의 RESTful 콜

prostudy 2022. 8. 7. 16:14
반응형

Java에서의 RESTful 콜

RESTFUL하다하지만 어떻게 전화를 해야 할지 모르겠어요.URLConnection른른?

업데이트: 아래에 답을 쓴 지 5년이 다 되어가는데, 오늘은 다른 시각을 갖게 되었습니다.

99%의 사람들이 REST라는 용어를 사용하는 것은 HTTP를 의미하며, 이들은 "리소스", "표현", "상태 전송", "유니폼 인터페이스", "하이퍼미디어" 또는 Fielding에 의해 식별된 REST 아키텍처 스타일의 기타 제약사항이나 측면에 대해 덜 관심을 가질 수 있습니다.따라서 다양한 REST 프레임워크에 의해 제공되는 추상화는 혼란스럽고 도움이 되지 않는다.

2015년에는 Java를 사용하여 HTTP 요청을 전송하고자 합니다.명확하고 표현력 있고 직관적이며 관용적이고 단순한 API를 원합니다.뭘 쓸까?저는 이제 자바를 사용하지 않지만, 지난 몇 년 동안 가장 유망하고 흥미로워 보였던 자바 HTTP 클라이언트 라이브러리는 OkHttp입니다.이것을 확인해 보세요.


RESTful을 하면 웹 할 수 .URLConnection또는 HTTP Client를 사용하여 HTTP 요청을 코드화합니다.

그러나 일반적으로는 이 목적을 위해 특별히 설계된 보다 단순하고 의미 있는 API를 제공하는 라이브러리 또는 프레임워크를 사용하는 것이 더 바람직합니다.이것에 의해, 코드의 기입, 판독, 및 디버깅이 용이하게 되어, 작업의 중복이 경감됩니다.이러한 프레임워크는 일반적으로 콘텐츠 네고시에이션, 캐싱 및 인증과 같은 하위 수준의 라이브러리에는 존재하지 않거나 사용하기 쉬운 몇 가지 뛰어난 기능을 구현합니다.

Jersey, RESTEASY, RESTETEASH가장 성숙한 옵션입니다.

대해 잘 어떻게 만들 수 POST모두 합니다.

저지 예시

Form form = new Form();
form.add("x", "foo");
form.add("y", "bar");

Client client = ClientBuilder.newClient();

WebTarget resource = client.target("http://localhost:8080/someresource");

Builder request = resource.request();
request.accept(MediaType.APPLICATION_JSON);

Response response = request.get();

if (response.getStatusInfo().getFamily() == Family.SUCCESSFUL) {
    System.out.println("Success! " + response.getStatus());
    System.out.println(response.getEntity());
} else {
    System.out.println("ERROR! " + response.getStatus());    
    System.out.println(response.getEntity());
}

레스트렛의 예시

Form form = new Form();
form.add("x", "foo");
form.add("y", "bar");

ClientResource resource = new ClientResource("http://localhost:8080/someresource");

Response response = resource.post(form.getWebRepresentation());

if (response.getStatus().isSuccess()) {
    System.out.println("Success! " + response.getStatus());
    System.out.println(response.getEntity().getText());
} else {
    System.out.println("ERROR! " + response.getStatus());
    System.out.println(response.getEntity().getText());
}

나 "GET" 할 수 있습니다.Accept그러나 이러한 예는 유용하게 사용할 수 있지만 너무 복잡하지는 않습니다.

보시는 것처럼 Restlet과 Jersey는 비슷한 클라이언트 API를 가지고 있습니다.비슷한 시기에 발전했기 때문에 서로 영향을 미쳤다고 생각합니다.

Restlet API는 좀 더 의미 있고 따라서 좀 더 명확하지만 YMMV입니다.

말씀드렸듯이, 저는 Restlet을 가장 잘 알고 있습니다.여러 앱에서 오랫동안 사용해 왔습니다만, 매우 만족하고 있습니다.매우 성숙하고 견고하며 단순하고 효과적이며 능동적이며 잘 지원되는 프레임워크입니다.저는 저지나 RESTEASHY에게 말할 수 없지만, 제 인상은 둘 다 확실한 선택이라는 것입니다.

서비스 프로바이더(Facebook, Twitter 등)에서 RESTful 서비스를 호출하는 경우 원하는 플레이버로 호출할 수 있습니다.

경우 할 수 .java.net.HttpURLConnection ★★★★★★★★★★★★★★★★★」javax.net.ssl.HttpsURLConnection) 단, 은 (SSL의 경우)의 유형 입니다.java.net.URLConnection , 「 「 」가 합니다.connection.getInputStream() ★★★★★★★★★★★★★★★★★★.InputStream그런 다음 입력 스트림을 문자열로 변환하고 문자열을 대표 객체(XML, JSON 등)로 해석해야 합니다.

또는 Apache HttpClient(버전 4가 최신 버전)를 사용할 수도 있습니다.자바 디폴트보다 안정적이고 견고합니다.URLConnection또한 대부분의 HTTP 프로토콜(전부는 아니더라도)을 지원합니다(또한 Strict 모드로 설정할 수도 있습니다).당신의 답변은 계속됩니다.InputStream위와 같이 사용하셔도 됩니다.


HttpClient 관련 자료: http://hc.apache.org/httpcomponents-client-ga/tutorial/html/index.html

자바에서는 매우 복잡하기 때문에 Spring의 추상화를 사용하는 것이 좋습니다.

String result = 
restTemplate.getForObject(
    "http://example.com/hotels/{hotel}/bookings/{booking}",
    String.class,"42", "21"
);

레퍼런스:

Java에서 REST 서비스로 간단한 호출만 하면 다음과 같은 방법을 사용할 수 있습니다.

/*
 * Stolen from http://xml.nig.ac.jp/tutorial/rest/index.html
 * and http://www.dr-chuck.com/csev-blog/2007/09/calling-rest-web-services-from-java/
*/
import java.io.*;
import java.net.*;

public class Rest {

    public static void main(String[] args) throws IOException {
        URL url = new URL(INSERT_HERE_YOUR_URL);
        String query = INSERT_HERE_YOUR_URL_PARAMETERS;

        //make connection
        URLConnection urlc = url.openConnection();

        //use post mode
        urlc.setDoOutput(true);
        urlc.setAllowUserInteraction(false);

        //send query
        PrintStream ps = new PrintStream(urlc.getOutputStream());
        ps.print(query);
        ps.close();

        //get result
        BufferedReader br = new BufferedReader(new InputStreamReader(urlc
            .getInputStream()));
        String l = null;
        while ((l=br.readLine())!=null) {
            System.out.println(l);
        }
        br.close();
    }
}

주변에는 몇 가지 RESTful API가 있습니다.저지를 추천합니다.

https://jersey.java.net/

클라이언트 API 매뉴얼은 다음과 같습니다.

https://jersey.java.net/documentation/latest/index.html


다음 코멘트의 OAuth 문서 위치는 데드링크이며 https://jersey.java.net/nonav/documentation/latest/security.html#d0e12334으로 이동했습니다.

Post JSON 콜을 사용한 REST WS에 전화를 걸어 개인적인 경험을 공유하고 싶습니다.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.URL;
import java.net.URLConnection;

public class HWS {

    public static void main(String[] args) throws IOException {
        URL url = new URL("INSERT YOUR SERVER REQUEST");
        //Insert your JSON query request
        String query = "{'PARAM1': 'VALUE','PARAM2': 'VALUE','PARAM3': 'VALUE','PARAM4': 'VALUE'}";
        //It change the apostrophe char to double quote char, to form a correct JSON string
        query=query.replace("'", "\"");

        try{
            //make connection
            URLConnection urlc = url.openConnection();
            //It Content Type is so important to support JSON call
            urlc.setRequestProperty("Content-Type", "application/xml");
            Msj("Conectando: " + url.toString());
            //use post mode
            urlc.setDoOutput(true);
            urlc.setAllowUserInteraction(false);
    
            //send query
            PrintStream ps = new PrintStream(urlc.getOutputStream());
            ps.print(query);
            Msj("Consulta: " + query);
            ps.close();
    
            //get result
            BufferedReader br = new BufferedReader(new InputStreamReader(urlc.getInputStream()));
            String l = null;
            while ((l=br.readLine())!=null) {
                Msj(l);
            }
            br.close();
        } catch (Exception e){
            Msj("Error ocurrido");
            Msj(e.toString());
        }
    }
    
    private static void Msj(String texto){
        System.out.println(texto);
    }
}

CXF를 확인할 수 있습니다.JAX-RS 기사는 이쪽에서 보실 수 있습니다.

통화는 다음과 같이 간단합니다(견적).

BookStore store = JAXRSClientFactory.create("http://bookstore.com", BookStore.class);
// (1) remote GET call to http://bookstore.com/bookstore
Books books = store.getAllBooks();
// (2) no remote call
BookResource subresource = store.getBookSubresource(1);
// {3} remote GET call to http://bookstore.com/bookstore/1
Book b = subresource.getDescription();

대부분의 Easy Solution은 Apache http 클라이언트 라이브러리를 사용합니다.다음 샘플 코드를 참조하십시오.이 코드는 인증에 기본 보안을 사용합니다.

다음 종속성을 추가합니다.

<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.4</version>
</dependency>
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
Credentials credentials = new UsernamePasswordCredentials("username", "password");
credentialsProvider.setCredentials(AuthScope.ANY, credentials);
HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider).build();
HttpPost request = new HttpPost("https://api.plivo.com/v1/Account/MAYNJ3OT/Message/");HttpResponse response = client.execute(request);
    // Get the response
    BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    String line = "";
    while ((line = rd.readLine()) != null) {    
    textView = textView + line;
    }
    System.out.println(textView);

실제로 이는 "Java에서는 매우 복잡하다"고 할 수 있습니다.

송신원: https://jersey.java.net/documentation/latest/client.html

Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://foo").path("bar");
Invocation.Builder invocationBuilder = target.request(MediaType.TEXT_PLAIN_TYPE);
Response response = invocationBuilder.get();

많은 답변이 있습니다. 다음은 2020년 WebClient에서 사용하는 것입니다. BTW RestTemplate는 더 이상 사용되지 않을 것입니다.(확인 가능) RestTemplate는 폐지됩니다.

다음으로 응답 본문을 HttpRequest를 사용한 문자열로 출력하는 GET 요청의 예를 나타냅니다.

   HttpClient client = HttpClient.newHttpClient();
   HttpRequest request = HttpRequest.newBuilder()
         .uri(URI.create("http://example.org/"))
         .build();
   client.sendAsync(request, BodyHandlers.ofString())
         .thenApply(HttpResponse::body)
         .thenAccept(System.out::println)
         .join(); 

헤더를 설정할 필요가 있는 경우는, 다음의 방법을 사용해 주세요.HttpRequest.Builder:

.setHeader("api-key", "value")

다음과 같이 Async Http Client(라이브러리는 WebSocket Protocol도 지원합니다)를 사용할 수 있습니다.

    String clientChannel = UriBuilder.fromPath("http://localhost:8080/api/{id}").build(id).toString();

    try (AsyncHttpClient asyncHttpClient = new AsyncHttpClient())
    {
        BoundRequestBuilder postRequest = asyncHttpClient.preparePost(clientChannel);
        postRequest.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
        postRequest.setBody(message.toString()); // returns JSON
        postRequest.execute().get();
    }

언급URL : https://stackoverflow.com/questions/3913502/restful-call-in-java

반응형