본문으로 바로가기

Java로 http request보내서 string 받기 with okhttp

category Language/JAVA 2018.12.24 12:31

Java로 http request보내서 string 받기 with okhttp


okhttp site 문서

http://square.github.io/okhttp/



사용방법 관련 블로그 포스트

https://www.codexpedia.com/android/okhttp-3-example-in-android/



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
 
import java.io.IOException;
 
public class HttpCaller {
    OkHttpClient client = new OkHttpClient();
 
    String run(String url) throws IOException {
        Request request = new Request.Builder()
                .url(url)
                .build();
 
        Response response = client.newCall(request).execute();
        return response.body().string();
    }
    public static void main(String[] args) throws IOException {
        String url = "http://www.google.com";
        String responseString = new HttpCaller().run(url);
        System.out.println(responseString);
    }
}
cs


결과

<!doctype html><html itemscope="" itemtype="http://schema.org/WebPage" lang="ko"><head><meta content="text/html; charset=UTF-8" http-equiv="Content-Type"><meta content="/logos/doodles/2018/holidays-2018-northern-hemisphere-day-2-5676669204430848-law.gif" itemprop="image"><meta 

--- 중략 ---

&#48372;&#45236;&#49464;&#50836;! #GoogleDoodle" property="og:description"><meta content="summary_large_image" property="twitter:card"><meta content="@GoogleDoodles" property="twitter:site">(function(){var r=['aa','async','ipv6','mu','sf'];google.plm(r);})();</script>     </body></html>


google.com에 요청을 보내고 응답을 받는 코드이다.


end.




댓글을 달아 주세요