OkHttp的简单使用(附带完整代码)

113 阅读3分钟

先导入包 okhttp的 和 Gson的

implementation "com.squareup.okhttp3:okhttp:4.9.0"
implementation 'com.google.code.gson:gson:2.8.5'

UI 就是五个按钮

<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="getRequest"
android:text="get请求"/>

<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="postRequest"
android:text="post请求"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="getWithParams"
android:text="getWithParams"/>

<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="getFile"
android:text="getFile"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="getFiles"
android:text="getFiles"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="downLoadFiles"
android:text="downLoadFiles"/>

\

第一个

获取文本数据普通接口

public class MainActivity extends AppCompatActivity {

public static final String BASE_URL = "http://10.0.2.2:9102";\ private static final String TAG = "MainActivity";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

public void getRequest(View view) {
*//要有客户端 就类似我们要有一个浏览器
*OkHttpClient okHttpClient = new OkHttpClient.Builder()
.connectTimeout(10000, TimeUnit.MILLISECONDS)
.build();
*//创建请求内容
*Request request = new Request.Builder()
.get()
.url(BASE_URL+"/get/text")
.build();
*//用浏览器client创建请求任务
*Call call = okHttpClient.newCall(request);
*//异步请求
*call.enqueue(new Callback() {
@Override
public void onFailure(@NonNull Call call, @NonNull IOException e) {
Log.d(TAG,"onFailure "+e.toString());
}

@Override
public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
int code = response.code();
if (code == HttpURLConnection.HTTP_OK){
Log.d(TAG,"response code ->" + code);
ResponseBody body = response.body();
Log.d(TAG,"response body ->"+ body.string());
}
}
});

}\

提交评论


public void postRequest(View view) {
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.connectTimeout(10000, TimeUnit.MILLISECONDS)
.build();
*//要提交的内容
*CommentItem commentItem = new CommentItem("123456","这是我的评论");
Gson gson = new Gson();
String jsonStr = gson.toJson(commentItem);
MediaType mediaType = MediaType.parse("application/json");
RequestBody requestBody = RequestBody.create(jsonStr, mediaType);
Request request = new Request.Builder()
.post(requestBody)
.url(BASE_URL+"/post/comment")
.build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(@NonNull Call call, @NonNull IOException e) {
Log.d(TAG,"onFailure " + e.toString());
}

@Override
public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
int code = response.code();
if (code==HttpURLConnection.HTTP_OK){
ResponseBody body = response.body();
if (body != null) {
Log.d(TAG,"result ->"+body.string());

}

}
}
});

}\

get带参数请求


public void getWithParams(View view) {
Map<String,String> params = new HashMap<>();
params.put("keyword","我的关键字");
params.put("page","12");
params.put("order","0");
startRequest(params);
}

private void startRequest(Map<String, String> params) {
if (params!=null && params.size()>0){
StringBuilder sb = new StringBuilder("?");
Iterator<Map.Entry<String, String>> iterator = params.entrySet().iterator();
while (iterator.hasNext()){
Map.Entry<String, String> next = iterator.next();
sb.append(next.getKey());
sb.append("=");
sb.append(next.getValue());
if (iterator.hasNext()){
sb.append("&");
}
Log.d(TAG,"sb result ->"+sb.toString());
}
{
*//要有客户端 就类似我们要有一个浏览器
*OkHttpClient okHttpClient = new OkHttpClient.Builder()
.connectTimeout(10000, TimeUnit.MILLISECONDS)
.build();
*//创建请求内容
*Request request = new Request.Builder()
.get()
.url(BASE_URL+"/get/param"+sb)
.build();
*//用浏览器client创建请求任务
*Call call = okHttpClient.newCall(request);
*//异步请求
*call.enqueue(new Callback() {
@Override
public void onFailure(@NonNull Call call, @NonNull IOException e) {
Log.d(TAG,"onFailure "+e.toString());
}

@Override
public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
int code = response.code();
if (code == HttpURLConnection.HTTP_OK){
Log.d(TAG,"response code ->" + code);
ResponseBody body = response.body();
Log.d(TAG,"response body ->"+ body.string());
}
}
});

}

}
}\

单文件上传


public void getFile(View view) {
ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},1);
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(10000, TimeUnit.MILLISECONDS)
.build();
File file = new File("/storage/emulated/0/Pictures/IMG_20220417_121032.jpg");
MediaType fileType = MediaType.parse("image/jpg");
RequestBody fileBody = RequestBody.create(file,fileType);
RequestBody requestBody = new MultipartBody.Builder()
.addFormDataPart("file",file.getName(),fileBody)
.build();
Request request = new Request.Builder()
.post(requestBody)
.url(BASE_URL+"/file/upload")
.build();

Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(@NonNull Call call, @NonNull IOException e) {
Log.d(TAG,"onFailure" + e.toString());
}

@Override
public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
int code = response.code();
if (code == HttpURLConnection.HTTP_OK){
ResponseBody body = response.body();
if (body!=null ){
String string = body.string();
Log.d(TAG,"result ->" + string);
}
}
}
});
}\

多文件上传


public void getFiles(View view) {
{ OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(10000, TimeUnit.MILLISECONDS)
.build();
File file = new File("/storage/emulated/0/Pictures/IMG_20220417_121032.jpg");
File file1 = new File("/storage/emulated/0/Pictures/IMG_20220417_125027.jpg");

MediaType fileType = MediaType.parse("image/jpg");
RequestBody fileBody = RequestBody.create(file,fileType);
RequestBody fileBody1 = RequestBody.create(file1,fileType);

RequestBody requestBody = new MultipartBody.Builder()
.addFormDataPart("files",file.getName(),fileBody)
.addFormDataPart("files",file1.getName(),fileBody1)
.build();
Request request = new Request.Builder()
.post(requestBody)
.url(BASE_URL+"/files/upload")
.build();

Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(@NonNull Call call, @NonNull IOException e) {
Log.d(TAG,"onFailure" + e.toString());
}

@Override
public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
int code = response.code();
if (code == HttpURLConnection.HTTP_OK){
ResponseBody body = response.body();
if (body!=null ){
String string = body.string();
Log.d(TAG,"result ->" + string);
}
}
}
});
}

}

public void downLoadFiles(View view) {
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(10000, TimeUnit.MILLISECONDS)
.build();
Request request = new Request.Builder()
.get()
.url(BASE_URL+"/download/3")
.build();

Call call = client.newCall(request);
new Thread(new Runnable() {

private InputStream inputStream;
private FileOutputStream fos;

@Override
public void run() {
try {
Response response = call.execute();
Headers headers = response.headers();
for (int i = 0; i < headers.size(); i++) {
String key = headers.name(i);
String value = headers.value(i);
Log.d(TAG,"key ->" + key+"value->"+value);
}
String contentType = headers.get("Content-disposition");
String fileName = contentType.replace("attachment; filename=", "");
File outFile = new File(MainActivity.this.getExternalFilesDir(Environment.DIRECTORY_PICTURES)+File.separator+fileName);
Log.d(TAG,"outFile ->"+outFile);
if (outFile.getParentFile().exists()) {
outFile.mkdir();
}
if (outFile.exists()) {
outFile.createNewFile();
}
fos = new FileOutputStream(outFile);
if (response.body()!=null){
inputStream = response.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();
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if (fos!=null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (inputStream!=null){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

}
}).start();
}
}