布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="getRequest"
android:onClick="getRequest"
android:textAllCaps="false"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="postComment"
android:onClick="postComment"
android:textAllCaps="false"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="postFile"
android:onClick="postFile"
android:textAllCaps="false"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="postFiles"
android:onClick="postFiles"
android:textAllCaps="false"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="downloadFile"
android:onClick="downloadFile"
android:textAllCaps="false"/>
</LinearLayou>
代码:
public class OkHttpActivity extends AppCompatActivity {
private static final String BASE_URL = "http://10.0.2.2:9102";
private static final String BASE_URL2 = "https://api.apiopen.top/videoCategoryDetails?id=14";
private static final String TAG = "OkHttpActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_okhttp);
}
public void getRequest(View view) {
//要有客户端,类似我们要一个浏览器
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(10000, TimeUnit.MILLISECONDS)
.build();
//创建请求内容
Request request = new Request.Builder()
.get()
// .url(BASE_URL + "/get/text")
.url(BASE_URL2)
.build();
//用client去创建请求任务
Call task = client.newCall(request);
//异步请求
task.enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
Log.d(TAG, "onFailure: ======== " + e.toString());
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
int code = response.code();
Log.d(TAG, "code ============: " + code);
if (code == HttpURLConnection.HTTP_OK) {
ResponseBody body = response.body();
Log.d(TAG, "body: =========== " + body.string());
}
}
});
}
public void postComment(View view) {
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(10000, TimeUnit.MILLISECONDS)
.build();
//要提交的内容
CommentItem commentItem = new CommentItem("23425245", "浪费空间的说法");
Gson gson = new Gson();
String jsonStr = gson.toJson(commentItem);
MediaType mediaType = MediaType.parse("application/json");
RequestBody requestBody = RequestBody.create(jsonStr, mediaType);
/*RequestBody requestBody = new RequestBody() {
@Nullable
@Override
public MediaType contentType() {
return null;
}
@Override
public void writeTo(@NotNull BufferedSink bufferedSink) throws IOException {
}
};*/
Request request = new Request.Builder()
.post(requestBody)
.url(BASE_URL + "/post/comment")
.build();
Call task = client.newCall(request);
task.enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
Log.d(TAG, "onFailure: ------ " + e.toString());
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
int code = response.code();
Log.d(TAG, "code ============== " + code);
if (code == HttpURLConnection.HTTP_OK) {
ResponseBody body = response.body();
if (body != null) {
Log.d(TAG, "body: =========" + body.string());
}
}
}
});
}
public void postFile(View view) {
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(10000, TimeUnit.MILLISECONDS)
.build();
File file = new File("/sdcard/Android/data/com.example.network/files/Pictures/10.png");
MediaType fileType = MediaType.parse("image/png");
RequestBody fileBody = RequestBody.create(file, fileType);
RequestBody requestBody = new MultipartBody.Builder()
.addFormDataPart("file", file.getName(), fileBody)
.build();
//创建请求内容
Request request = new Request.Builder()
.url(BASE_URL + "/file/upload")
.post(requestBody)
.build();
Call task = client.newCall(request);
task.enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
Log.d(TAG, "onFailure: ==========" + e.toString());
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
int code = response.code();
Log.d(TAG, "code: ========= " + code);
if (code == HttpURLConnection.HTTP_OK) {
ResponseBody body = response.body();
if (body != null) {
String result = body.string();
Log.d(TAG, "result: ====== " + result);
}
}
}
});
}
public void postFiles(View view) {
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(10000, TimeUnit.MILLISECONDS)
.build();
File fileOne = new File("/sdcard/Android/data/com.example.network/files/Pictures/10.png");
File fileTwo = new File("/sdcard/Download/wiseshouye_522d1971807db8d246aba7372aa208f4.png");
MediaType fileType = MediaType.parse("image/png");
RequestBody fileOneBody = RequestBody.create(fileOne, fileType);
RequestBody fileTwoBody = RequestBody.create(fileTwo, fileType);
RequestBody requestBody = new MultipartBody.Builder()
.addFormDataPart("files", fileOne.getName(), fileOneBody)
.addFormDataPart("files", fileTwo.getName(), fileTwoBody)
.build();
//创建请求内容
Request request = new Request.Builder()
.url(BASE_URL + "/files/upload")
.post(requestBody)
.build();
Call task = client.newCall(request);
task.enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
Log.d(TAG, "onFailure: ==========" + e.toString());
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
int code = response.code();
Log.d(TAG, "code: ========= " + code);
if (code == HttpURLConnection.HTTP_OK) {
ResponseBody body = response.body();
if (body != null) {
String result = body.string();
Log.d(TAG, "result: ====== " + result);
}
}
}
});
}
public void downloadFile(View view) {
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(10000, TimeUnit.MILLISECONDS)
.build();
Request request = new Request.Builder()
.get()
.url(BASE_URL + "/download/5")
.build();
final Call task = client.newCall(request);
//异步请求
task.enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
Log.d(TAG, "onFailure: =======" + e.toString());
e.printStackTrace();
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
int code = response.code();
Log.d(TAG, "code: ==========" + code);
if (code == HttpURLConnection.HTTP_OK) {
downFileSych(response.body().byteStream(),response.headers());
}
}
});
//同步请求
/* new Thread(new Runnable() {
@Override
public void run() {
try {
Response execute = task.execute();
int code = execute.code();
if (code == HttpURLConnection.HTTP_OK) {
Headers headers = execute.headers();
for (int i = 0; i < headers.size(); i++) {
String key = headers.name(i);
String value = headers.value(i);
Log.d(TAG, key + "==========" + value);
}
downFile(execute, headers);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();*/
}
private void downFile(Response execute, Headers headers) throws IOException {
String contentType = headers.get("Content-disposition");
String fileName = contentType.replace("attachment; filename=", "");
File outFile = new File(OkHttpActivity.this.getExternalFilesDir(Environment.DIRECTORY_PICTURES) + File.separator + fileName);
Log.d(TAG, "outFile ============ " + outFile);
if (!outFile.getParentFile().exists()) {
outFile.mkdirs();
}
if (!outFile.exists()) {
outFile.createNewFile();
}
InputStream inputStream = null;
FileOutputStream fos = new FileOutputStream(outFile);
if (execute.body() != null) {
inputStream = execute.body().byteStream();
byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer, 0, buffer.length)) != -1) {
fos.write(buffer, 0, len);
}
fos.flush();
}
IOUtils.closeIO(fos);
IOUtils.closeIO(inputStream);
}
private void downFileSych(InputStream inputStream, Headers headers) throws IOException {
String contentType = headers.get("Content-disposition");
String fileName = contentType.replace("attachment; filename=", "");
File outFile = new File(OkHttpActivity.this.getExternalFilesDir(Environment.DIRECTORY_PICTURES) + File.separator + fileName);
Log.d(TAG, "outFile ============ " + outFile);
if (!outFile.getParentFile().exists()) {
outFile.mkdirs();
}
if (!outFile.exists()) {
outFile.createNewFile();
}
FileOutputStream fos = new FileOutputStream(outFile);
byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer, 0, buffer.length)) != -1) {
fos.write(buffer, 0, len);
}
IOUtils.closeIO(fos);
IOUtils.closeIO(inputStream);
}
}