package com.youkeda.test.http;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import org.apache.commons.lang3.StringUtils;
public class GetPage {
// okHttpClient 实例
private OkHttpClient okHttpClient;
public GetPage() {
// 定义一个client
okHttpClient = new OkHttpClient();
}
/**
* 根据输入的url,读取页面内容并返回
*/
public String getPageContentSync(String url) {
// 参数判断,未输入参数则直接返回
if (StringUtils.isBlank(url)) {
return null;
}
// 定义一个request
Request request = new Request.Builder().url(url).build();
// 使用client去请求
Call call = okHttpClient.newCall(request);
String result = null;
try {
// 获得返回结果
result = call.execute().body().string();
System.out.println("call " + url + " , content's size=" + result.length());
} catch (IOException e) {
System.out.println("request " + url + " error . ");
e.printStackTrace();
}
return result;
}
public static void main(String[] args) {
GetPage getPage = new GetPage();
String content = getPage.getPageContentSync("http://www.taobao.com");
System.out.println(content);
}
}
Get同步请求
<!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp -->
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.1.0</version>
</dependency>
<!-- 字符串操作工具库 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
public String getPageContentSync(String url) {
// 参数判断,未输入参数则直接返回
if (StringUtils.isBlank(url)) {
return null;
}
//2.定义一个request
Request request = new Request.Builder().url(url).build();
//3.使用client去请求
Call call = okHttpClient.newCall(request);
String result = null;
try {
//4.获得返回结果
result = call.execute().body().string();
System.out.println("call " + url + " , content's size=" + result.length());
} catch (IOException e) {
System.out.println("request " + url + " error . ");
e.printStackTrace();
}
return result;
}
package com.youkeda.test.http;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import org.apache.commons.lang3.StringUtils;
public class PageOperator{
// okHttpClient 实例
private OkHttpClient okHttpClient;
public PageOperator() {
// 定义一个client
okHttpClient = new OkHttpClient();
}
/**
* 根据输入的url,读取页面内容并返回
*/
public String getPageContentSync(String url) {
// 参数判断,未输入参数则直接返回
if (StringUtils.isBlank(url)) {
return null;
}
// 定义一个request
Request request = new Request.Builder().url(url).build();
// 使用client去请求
Call call = okHttpClient.newCall(request);
String result = null;
try {
// 获得返回结果
result = call.execute().body().string();
System.out.println("call " + url + " , content's size=" + result.length());
} catch (IOException e) {
System.out.println("request " + url + " error . ");
e.printStackTrace();
}
return result;
}
public static void main(String[] args) {
PageOperator getPage = new PageOperator();
String content = getPage.getPageContentSync("http://www.baidu.com");
System.out.println(content);
}
}