HttpUtil.java
package com.example.networktest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import okhttp3.OkHttpClient;
import okhttp3.Request;
public class HttpUtil {
public static void sendHttpRequest(final String address,final HttpCallbackListener listener) {
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection connection = null;
try {
URL url = new URL(address);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
//post的形式
//connection.setRequestMethod("POST");
// DataOutputStream out = new DataOutputStream(connection.getOutputStream());
//out.writeBytes("username=admin&password=123456");
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
InputStream in = connection.getInputStream();
//下面对获取到的输入流进行读取
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
if(listener!=null){
//回掉onFinish()方法
listener.onFinish(response.toString());
}
//return response.toString();
} catch (Exception e) {
e.printStackTrace();
if(listener!=null){
//回调onError
listener.onError(e);
}
//return e.getMessage();
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
}).start();
}
public static void sendOkHttpResponse(String address, okhttp3.Callback callback) {
//okhttp自带回调接口类型自己写的HttpCallbackListener
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(address)
.build();
//enqueue内部帮我们开好子线程了,然后子线程去执行http请求
client.newCall(request).enqueue(callback);
}
}
接口HttpCallbackListener.java
package com.example.networktest;
import okhttp3.OkHttpClient;
import okhttp3.Request;
public interface HttpCallbackListener {
void onFinish(String response);
void onError(Exception e);
}
MainActivity.java
package com.example.networktest;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import org.jetbrains.annotations.NotNull;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
TextView responseText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button sendRequest = (Button) findViewById(R.id.send_request);
responseText = (TextView) findViewById(R.id.response_text);
sendRequest.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.send_request) {
//sendRequestWithHttpURLConnection();
//sendRequestWithOkHttp();
String address = "http://www.baidu.com";
// HttpUtil.sendHttpRequest(address, new HttpCallbackListener() {
// @Override
// public void onFinish(String response) {
// //根据返回的内容执行具体的逻辑
// }
//
// @Override
// public void onError(Exception e) {
// //根据返回的内容执行具体的逻辑
// }
// });
HttpUtil.sendOkHttpResponse(address,new okhttp3.Callback(){
@Override
public void onResponse(@NotNull Call call, Response response) throws IOException {
//得到服务器返回的具体内容
String responseData = response.body().string();
}
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
}
});
}
}
private void sendRequestWithHttpURLConnection() {
// 开启线程来发送网络请求
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL("http://www.baidu.com");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
//post的形式
//connection.setRequestMethod("POST");
// DataOutputStream out = new DataOutputStream(connection.getOutputStream());
//out.writeBytes("username=admin&password=123456");
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
InputStream in = connection.getInputStream();
//下面对获取到的输入流进行读取
reader = new BufferedReader(new InputStreamReader(in));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
showResponse(response.toString());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (connection != null) {
connection.disconnect();
}
}
}
}).start();
}
private void sendRequestWithOkHttp() {
new Thread(new Runnable() {
@Override
public void run() {
try {
//创建一个client实例
OkHttpClient client = new OkHttpClient();
//创建request对象
Request request = new Request.Builder().url("http://www.baidu.com").build();
Response response = client.newCall(request).execute();
String responseData = response.body().string();
// //post 需要先构建出一个Request Body对象存放待提交的参数
// RequestBody requestBody = new FormBody.Builder()
// .add("username","admin")
// .add("password","123456")
// .build();
//在调用post方法,传入RequestBody对象
//
// Request request1 = new Request.Builder().url("http://www.baidu.com").post(requestBody).build();
showResponse(responseData);
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
private void showResponse(final String response) {
//安卓不允许子线程中进行UI操作,我们切换到主线程
runOnUiThread(new Runnable() {
@Override
public void run() {
// 在这里进行ui操作,将结果显示到页面上
responseText.setText(response);
}
});
}
}