IT이야기

HTTP 응답 본문을 문자열로 가져오는 방법

cyworld 2022. 5. 10. 22:25
반응형

HTTP 응답 본문을 문자열로 가져오는 방법

여기 문서화된 Apache Commons와 함께 이것을 얻을 수 있는 방법이 있었다는 것을 알고 있다.

http://hc.apache.org/httpclient-legacy/apidocs/org/apache/commons/httpclient/HttpMethod.html

...그리고 여기에 예를 하나 들어보자.

http://www.kodejava.org/examples/416.html

...하지만 나는 이것이 더 이상 사용되지 않는다고 믿는다.

Java에서 http get 요청을 하고 stream이 아닌 string으로 응답 본체를 얻을 수 있는 다른 방법이 없을까?

여기 내 작업 프로젝트에서 나온 두 가지 예가 있다.

  1. 사용 및

    HttpResponse response = httpClient.execute(new HttpGet(URL));
    HttpEntity entity = response.getEntity();
    String responseString = EntityUtils.toString(entity, "UTF-8");
    System.out.println(responseString);
    
  2. 사용

    HttpResponse response = httpClient.execute(new HttpGet(URL));
    String responseString = new BasicResponseHandler().handleResponse(response);
    System.out.println(responseString);
    

내가 생각할 수 있는 모든 도서관은 개울을 반환한다.Apache Commons IO를 사용하여InputStream.String일률적으로예:

URL url = new URL("http://www.example.com/");
URLConnection con = url.openConnection();
InputStream in = con.getInputStream();
String encoding = con.getContentEncoding();
encoding = encoding == null ? "UTF-8" : encoding;
String body = IOUtils.toString(in, encoding);
System.out.println(body);

업데이트: 가능한 경우 응답의 내용 인코딩을 사용하도록 위의 예를 변경했다.그렇지 않으면 로컬 시스템 기본값을 사용하는 대신 UTF-8로 기본 설정된다.

다음은 Apache에서 httpclient 라이브러리를 사용하여 작업하던 다른 간단한 프로젝트의 예:

String response = new String();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("j", request));
HttpEntity requestEntity = new UrlEncodedFormEntity(nameValuePairs);

HttpPost httpPost = new HttpPost(mURI);
httpPost.setEntity(requestEntity);
HttpResponse httpResponse = mHttpClient.execute(httpPost);
HttpEntity responseEntity = httpResponse.getEntity();
if(responseEntity!=null) {
    response = EntityUtils.toString(responseEntity);
}

EntityUtils를 사용하여 응답 본체를 문자열로 잡으십시오.아주 간단한

이것은 구체적인 경우에는 비교적 간단하지만 일반적인 경우에는 상당히 까다롭다.

HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://stackoverflow.com/");
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
System.out.println(EntityUtils.getContentMimeType(entity));
System.out.println(EntityUtils.getContentCharSet(entity));

답은 에 달려 있다.Content-Type HTTP 응답 헤더.

이 헤더에는 페이로드에 대한 정보가 포함되어 있으며 텍스트 데이터의 인코딩을 정의할 수 있다.텍스트 유형을 가정하더라도 올바른 문자 인코딩을 결정하기 위해 내용 자체를 검사해야 할 수 있다.예: 특정 형식에 대한 자세한 내용은 HTML 4 규격을 참조하십시오.

일단 인코딩이 알려지면, InputStreamReader를 사용하여 데이터를 디코딩할 수 있다.

응답 헤더가 문서와 일치하지 않거나 문서 선언이 사용된 인코딩과 일치하지 않는 경우를 처리하려면 서버가 올바른 작업을 수행하느냐에 따라 이 답변이 달라진다.

아래는 Apache HTTP Client 라이브러리를 사용하여 String으로 응답에 액세스하는 간단한 방법이다.

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;

//... 

HttpGet get;
HttpClient httpClient;

// initialize variables above

ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpClient.execute(get, responseHandler);

McDowell의 답은 정확하다.그러나 위의 게시물 중 몇 가지에서 다른 제안을 시도한다면.

HttpEntity responseEntity = httpResponse.getEntity();
if(responseEntity!=null) {
   response = EntityUtils.toString(responseEntity);
   S.O.P (response);
}

그러면 콘텐츠가 이미 소비되었음을 나타내는 불법 StateException이 제공될 것이다.

이것만 하는 게 어때?

org.apache.commons.io.IOUtils.toString(new URL("http://www.someurl.com/"));

우리는 또한 아래 코드를 사용하여 자바에서 HTML 응답을 얻을 수 있다.

import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.HttpResponse;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.apache.log4j.Logger;

public static void main(String[] args) throws Exception {
    HttpClient client = new DefaultHttpClient();
    //  args[0] :-  http://hostname:8080/abc/xyz/CheckResponse
    HttpGet request1 = new HttpGet(args[0]);
    HttpResponse response1 = client.execute(request1);
    int code = response1.getStatusLine().getStatusCode();

    try (BufferedReader br = new BufferedReader(new InputStreamReader((response1.getEntity().getContent())));) {
        // Read in all of the post results into a String.
        String output = "";
        Boolean keepGoing = true;
        while (keepGoing) {
            String currentLine = br.readLine();

            if (currentLine == null) {
                keepGoing = false;
            } else {
                output += currentLine;
            }
        }

        System.out.println("Response-->" + output);
    } catch (Exception e) {
        System.out.println("Exception" + e);

    }
}

경량화 방법은 다음과 같다.

String responseString = "";
for (int i = 0; i < response.getEntity().getContentLength(); i++) { 
    responseString +=
    Character.toString((char)response.getEntity().getContent().read()); 
}

물론responseString다음 유형의 웹 사이트의 응답 및 응답 포함HttpResponse,에 의해 반환됨HttpClient.execute(request)

다음은 HTTP POST 요청에 대한 유효한 응답인지 오류 응답인지 문자열로 응답 본체를 처리하는 더 나은 방법을 보여주는 코드 조각이다.

BufferedReader reader = null;
OutputStream os = null;
String payload = "";
try {
    URL url1 = new URL("YOUR_URL");
    HttpURLConnection postConnection = (HttpURLConnection) url1.openConnection();
    postConnection.setRequestMethod("POST");
    postConnection.setRequestProperty("Content-Type", "application/json");
    postConnection.setDoOutput(true);
    os = postConnection.getOutputStream();
    os.write(eventContext.getMessage().getPayloadAsString().getBytes());
    os.flush();

    String line;
    try{
        reader = new BufferedReader(new InputStreamReader(postConnection.getInputStream()));
    }
    catch(IOException e){
        if(reader == null)
            reader = new BufferedReader(new InputStreamReader(postConnection.getErrorStream()));
    }
    while ((line = reader.readLine()) != null)
        payload += line.toString();
}       
catch (Exception ex) {
            log.error("Post request Failed with message: " + ex.getMessage(), ex);
} finally {
    try {
        reader.close();
        os.close();
    } catch (IOException e) {
        log.error(e.getMessage(), e);
        return null;
    }
}

http 요청을 보내고 응답을 처리하는 3-d 파티 라이브러리를 사용할 수 있다.잘 알려진 제품 중 하나는 Apache commons HTTPClient일 것이다.HttpClient javadoc, HttpClient maven 아티팩트.훨씬 덜 알려져 있지만 훨씬 단순한 HTTPClient가 있다(내가 작성한 오픈 소스 MgntUtils 라이브러리의 일부).MgntUtils HttpClient javadoc, MgntUtils maven 아티팩트, MgntUtils Github.이러한 라이브러리를 사용하여 비즈니스 논리의 일부로 봄과 독립적으로 REST 요청을 보내고 응답을 받을 수 있음

Jackson을 사용하여 응답 본체를 역직렬화하는 경우 매우 간단한 해결책은request.getResponseBodyAsStream()대신에 request.getResponseBodyAsString()

여기 바닐라 자바의 대답이 있다.

import java.net.http.HttpClient;
import java.net.http.HttpResponse;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.BodyPublishers;

...
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
  .uri(targetUrl)
  .header("Content-Type", "application/json")
  .POST(BodyPublishers.ofString(requestBody))
  .build();
HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString());
String responseString = (String) response.body();

Apache commons Ulast API를 사용하면 아래와 같이 할 수 있다.

String response = Request.Post("http://www.example.com/")
                .body(new StringEntity(strbody))
                .addHeader("Accept","application/json")
                .addHeader("Content-Type","application/json")
                .execute().returnContent().asString();

참조URL: https://stackoverflow.com/questions/5769717/how-can-i-get-an-http-response-body-as-a-string

반응형