HttpURLConnection的基本使用
@Test
public void test3() {
HttpURLConnection connection = null;
try {
URL url = new URL("http://www.baidu.com");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(10000);
connection.setReadTimeout(10000);
connection.connect();
if (connection.getResponseCode() == 200) {
InputStream inputStream = connection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String res = "";
String line;
while ((line = bufferedReader.readLine()) != null) {
res += line;
}
System.out.println(res);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
OkHttp的使用
@Test
public void test4() throws IOException {
//okhttp get请求方式
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder()
.url("http://www.baidu.com")
.get()
.build();
okhttp3.Response response = okHttpClient.newCall(request).execute();
if (response.isSuccessful()) {
ResponseBody body = response.body();
System.out.println(body.string());
}
}
@Test
public void test5() throws IOException {
//okhttp post请求
//OkHttp客户端
OkHttpClient okHttpClient = new OkHttpClient();
//请求体
RequestBody build = new FormBody.Builder()
.add("aaa", "aaa")
.build();
//请求对象
Request request = new Request.Builder()
.url("http://www.baidu.com")
.post(build)
.build();
okhttp3.Response response = okHttpClient.newCall(request).execute();
if (response.isSuccessful()) {
ResponseBody body = response.body();
String string = body.string();
System.out.println(string);
}
}
public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
@Test
public void postJson() throws IOException {
//申明给服务端传递一个json串
//创建一个OkHttpClient对象
OkHttpClient okHttpClient = new OkHttpClient();
//创建一个RequestBody(参数1:数据类型 参数2传递的json串)
//json为String类型的json数据
RequestBody requestBody = RequestBody.create(JSON, "{}");
//创建一个请求对象
Request request = new Request.Builder()
.url("http://www.baidu.com")
.post(requestBody)
.build();
//发送请求获取响应
okhttp3.Response response = okHttpClient.newCall(request).execute();
//判断请求是否成功
if (response.isSuccessful()) {
ResponseBody body = response.body();
//打印服务端返回结果
System.out.println(body.string());
}
}
网友评论