development

Java에서 http 응답 본문을 문자열로 어떻게 얻을 수 있습니까?

big-blog 2020. 6. 22. 07:20
반응형

Java에서 http 응답 본문을 문자열로 어떻게 얻을 수 있습니까?


http://hc.apache.org/httpclient-legacy/apidocs/org/apache/commons/httpclient/HttpMethod.html 및 여기에 예제와 같이 아파치 공통점으로 가져 오는 방법이 있다는 것을 알고 있습니다.

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

그러나 나는 이것이 더 이상 사용되지 않는다고 생각합니다. Java에서 http get 요청을 만들고 응답 본문을 스트림이 아닌 문자열로 얻는 다른 방법이 있습니까?


내가 생각할 수있는 모든 라이브러리는 스트림을 반환합니다. 당신은 사용할 수 있습니다 IOUtils.toString()에서 아파치 코 몬즈 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입니다.


내 작업 프로젝트의 두 가지 예가 있습니다.

  1. 사용 EntityUtils하여HttpEntity

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

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

다음은 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 클라이언트 라이브러리를 사용하여 응답을 문자열로 액세스하는 간단한 방법입니다.

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);

How about just this?

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

The Answer by McDowell is correct one. However if you try other suggestion in few of the posts above.

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

Then it will give you illegalStateException stating that content is already consumed.


We can use the below code also to get the HTML Response in java

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);

    }
}

Here's a lightweight way to do so:

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

With of course responseString containing website's response and response being type of HttpResponse, returned by HttpClient.execute(request)


Following is the code snippet which shows better way to handle the response body as a String whether it's a valid response or error response for the HTTP POST request:

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;
    }
}

You can use a 3-d party library that sends Http request and handles the response. One of the well-known products would be Apache commons HTTPClient: HttpClient javadoc, HttpClient Maven artifact. There is by far less known but much simpler HTTPClient (part of an open source MgntUtils library written by me): MgntUtils HttpClient javadoc, MgntUtils maven artifact, MgntUtils Github. Using either of those libraries you can send your REST request and receive response independently from Spring as part of your business logic


If you are using Jackson to deserialize the response body, one very simple solution is to use request.getResponseBodyAsStream() instead of request.getResponseBodyAsString()

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

반응형