欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

okhttp的学习与简单使用 博客分类: 杂烩 okhttp 

程序员文章站 2024-02-20 13:21:22
...
官方地址:https://github.com/square/okhttp/
一个处理网络请求的开源项目,是安卓端最火热的轻量级框架
 <dependency>
     <groupId>com.squareup.okhttp3</groupId>
     <artifactId>okhttp</artifactId>
     <version>3.10.0</version>
  </dependency>
    


简单测试okhttp Get请求
package com.sb.okhttp.okhttp;

import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class Test {
	// 创建OkhttpClient对象
	OkHttpClient client = new OkHttpClient();
	
	/**
	 * okhttp get 同步请求
	 */
	public void testGet(String url) {
		Request request = new Request.Builder().get().url(url) // 请求地址
				.build();// 创建Request对象、
		Response response = null;
		try {
			// 执行请求并获取Response对象
			response = client.newCall(request).execute();
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (null != response) {
			if (response.isSuccessful()) {// 请求成功
				System.out.println(response.code());// 状态码
				System.out.println(response.message());// message
				try {
					String res = response.body().string();
					System.out.println(res);
				} catch (IOException e) {
					e.printStackTrace();
				}
			} else {
				System.out.println("请求失败");
			}
		} else {
			System.out.println("请求失败");
		}
	}
	
	/**
	 * okhttp get 异步请求
	 */
	public void asynchronousGet(String url){
		Request request = new Request.Builder().get().url(url) // 请求地址
				.build();// 创建Request对象
		client.newCall(request).enqueue(new Callback() {
			public void onResponse(Call arg0, Response response) throws IOException {
				//注:onResponse 回调会在子线程中执行,而不是主线程
				if (response.isSuccessful()) {// 请求成功
					System.out.println(response.code());// 状态码
					System.out.println(response.message());// message
					try {
						String res = response.body().string();
						System.out.println(res);
					} catch (IOException e) {
						e.printStackTrace();
					}
				} else {
					System.out.println("请求失败");
				}
			}
			//注:onFailure 回调会在子线程中执行,而不是主线程
			public void onFailure(Call arg0, IOException arg1) {
				System.out.println("请求失败");
			}
			
		});
	}
	
	public static void main(String[] args) {
		Test t = new Test();
		String url = "http://www.baidu.com";
		//t.testGet(url);
		t.asynchronousGet(url);
	}
}



测试okhttp Post请求
package com.sb.okhttp.okhttp;

import java.io.File;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class TestPost {
	//数据类型json
	public static final MediaType mediaType = MediaType.parse("application/json;charset=utf-8");
	//数据类型File
	public static final MediaType mediaType_file = MediaType.parse("File/*");
	
	OkHttpClient client = new OkHttpClient();
	
	/**
	 * Post提交Json数据
	 * @param url   提交的地址
	 * @param json  提交啊的json数据
	 * @return  返回post之后返回的结果数据
	 */
	public String postJson(String url,String json){
		RequestBody body = RequestBody.create(mediaType,json);
		Request request = new Request.Builder().url(url).post(body).build();
		Response response = null;
		try {
			response = client.newCall(request).execute();
			if(null!=response){
				if(response.isSuccessful()){
					return response.body().string();
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * okhttp  模拟表单提交
	 * @param url post的地址
	 */
	public void postKeyValue(String url ){
		FormBody.Builder formBody = new FormBody.Builder();//创建表单请求体
		formBody.add("name","zbb");
		formBody.add("age","26");
		Request request = new Request.Builder()   //创建请求对象
		                  .url(url)
		                  .post(formBody.build()) //传递请求体
		                  .build();
		client.newCall(request).enqueue(new Callback() {
			public void onResponse(Call call, Response res) throws IOException {
				//请求成功响应后回调
				if(res.isSuccessful()){
					String result = res.body().string();
					System.out.println(result);
				}
			}
			
			public void onFailure(Call call, IOException arg1) {
				//请求失败后回调
				//....此处代码省略
			}
		});
	}
	
	/**
	 * okhttp 上传File对象
	 * @param filePath  file路径
	 * @param url 提交到的地址
	 */
	public void postFile(String filePath,String url){
		File file = new File(filePath);
		RequestBody body = RequestBody.create(mediaType_file,file);
		Request request = new Request.Builder()
							.url(url)
							.post(body)
							.build();
	    client.newCall(request).enqueue(new Callback() {
			public void onResponse(Call arg0, Response arg1) throws IOException {
				//请求成功响应后的回调
				//.....
			}
			
			public void onFailure(Call arg0, IOException arg1) {
				//请求失败后的回调
				//.....
			}
		});
	}
	
	/**
	 * okhttp post 既传递表单参数也提交File
	 * @param file 文件对象
	 * @param url 提交到的地址
	 */
	public void postMultipartBody(File file,String url){
		MultipartBody body = new MultipartBody.Builder()
		                     .setType(MultipartBody.FORM)
		                     .addFormDataPart("name","zbb")
		                     .addFormDataPart("age","26")
		                     .addFormDataPart("f",file.getName(),
		                    		 RequestBody.create(mediaType_file,file))
		                     .build();
		Request request = new Request.Builder()
		                  .url(url)
		                  .post(body)
		                  .build();
		client.newCall(request).enqueue(new Callback() {
			public void onResponse(Call arg0, Response arg1) throws IOException {
				//请求成功响应后的回调
				//.....
			}
			
			public void onFailure(Call arg0, IOException arg1) {
				//请求失败后的回调
				//.....
			}
		});
	}
	
	public static void main(String[] args) {
		
	}
    
}

相关标签: okhttp