okhttp 使用 post

 

java  okhttp maven pom

 

<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>com.squareup.okio</groupId>
<artifactId>okio</artifactId>
<version>1.7.0</version>
</dependency>

 

 

 

OkhttpUtils.java

 

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.FormBody.Builder;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.BufferedSink;

import com.curiousby.baoyou.cn.showandshare.application.otherapplicaition.springbootdubboconsumer.common.RespEntity;
import com.curiousby.baoyou.cn.showandshare.application.otherapplicaition.springbootdubboconsumer.common.RespEnums;
import com.curiousby.baoyou.cn.showandshare.application.otherapplicaition.springbootdubboconsumer.common.ValidatorUtil;
 
public class OkhttpUtils { 

	public static RespEntity postPipe(String url,   Map<String, Object> params) {
		RespEntity entity = new RespEntity("");
		  RequestBody requestBody = new RequestBody( ) {
				@Override
				public MediaType contentType() { 
					return  MediaType.parse("application/json;charset:UTF-8");
				}

				@Override
				public void writeTo(BufferedSink sink) throws IOException {
					sink.writeUtf8(FastJsonUtils.toJSONString(params));
				}
				  
			  };
			  
			  Request request = new Request.Builder()
		        .url(url)
		        .post(requestBody)
		        .build();
			  OkHttpClient client = new OkHttpClient();
			  Response response  = null;
			  try {
				  response = client.newCall(request).execute();
			} catch (IOException e) { 
				e.printStackTrace();
				entity.setCode(RespEnums.RESP_EXCEPTION.getCode());
				entity.setMsg(e.getMessage());
			}
			  
			  if (!response.isSuccessful()) {
				  entity.setCode(RespEnums.RESP_OTHER_RESP_CODE.getCode()); 
				}
				String result = null;
				try {
					result = response.body().string();
					entity.setData(result);
				} catch (IOException e) {
					e.printStackTrace();
					entity.setCode(RespEnums.RESP_EXCEPTION.getCode());
					entity.setMsg(e.getMessage());
				} 
		return entity;
	}
	
	public static RespEntity post(String url, Map<String, Object> headers, Map<String, Object> params) {
		RespEntity entity = new RespEntity("");
		OkHttpClient client = new OkHttpClient();
		FormBody.Builder formBuilder = new FormBody.Builder();
		if (!ValidatorUtil.isEmpty(params)) {
			for (Entry<String, Object> entry : params.entrySet()) {
				formBuilder.add(entry.getKey(), ValidatorUtil.getObjOrEmpty(entry.getValue()).toString());
				
			}
		}
		
		FormBody form = formBuilder.build();
		
		Request.Builder requestBuilder = new Request.Builder();
		//requestBuilder.addHeader("content-type", "application/json;charset:UTF-8") ;
		if (!ValidatorUtil.isEmpty(headers)) {
			for (Entry<String, Object> entry : headers.entrySet()) {
				requestBuilder.addHeader(entry.getKey(), ValidatorUtil.getObjOrEmpty(entry.getValue()).toString());
			}
		}
		requestBuilder.url(url);
		requestBuilder.post(form);
		Request request = requestBuilder.build();

		Response response = null;
		try {
			response = client.newCall(request).execute();
		} catch (IOException e) {
			e.printStackTrace();
			entity.setCode(RespEnums.RESP_EXCEPTION.getCode());
			entity.setMsg(e.getMessage());
		}
		if (!response.isSuccessful()) {
			entity.setCode(RespEnums.RESP_OTHER_RESP_CODE.getCode());
			entity.setMsg("error code : "+response.code());
		}
		String result = null;
		try {
			result = response.body().string();
			entity.setData(result);
		} catch (IOException e) {
			e.printStackTrace();
			entity.setCode(RespEnums.RESP_EXCEPTION.getCode());
			entity.setMsg(e.getMessage());
		}
		
		return entity;
	}
	
	
	

	public static void postAsynchronize(String url, Map<String, Object> params) {
		OkHttpClient client = new OkHttpClient();
		Builder builder = new FormBody.Builder();
		for (Entry<String, Object> entry : params.entrySet()) {
			builder.add(entry.getKey(),
					ValidatorUtil.getObjOrEmpty(entry.getValue()).toString());
		}
		FormBody form = builder.build();

		Request request = new Request.Builder().url(url).post(form).build();

		Call call = client.newCall(request);
		call.enqueue(new Callback() {
			@Override
			public void onFailure(Call call, IOException e) {
				// 访问失败, 打印访问地址
				Request r = call.request();
				System.out.println("请求失败: " + r.url());
				System.out.println(r.body());
			}

			@Override
			public void onResponse(Call call, Response response)
					throws IOException {
				System.out.println("请求有响应" + call.request().url());
				System.out.println("响应码: " + response.code());
				System.out.println("请求内容: " + response.body().string());
			}
		});
	}

	public static void postSynchronize(String url, Map<String, Object> params) {
		OkHttpClient client = new OkHttpClient();
		Builder builder = new FormBody.Builder();
		for (Entry<String, Object> entry : params.entrySet()) {
			builder.add(entry.getKey(), ValidatorUtil.getObjOrEmpty(entry.getValue()).toString());
			
		}
		FormBody form = builder.build();

		Request request = new Request.Builder().url(url).post(form).build();

		Response response = null;
		try {
			response = client.newCall(request).execute();
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (!response.isSuccessful()) {

		}
		String result = null;
		try {
			result = response.body().string();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	
	
	public static void uploadFile(String url,File file, Map<String, Object> params) {
		  //还是先创建客户端
        OkHttpClient client = new OkHttpClient();
        //待上传文件
      //  MultipartBody.Part part = MultipartBody.Part .createFormData("upload", file.getName(), RequestBody.create(MultipartBody.FORM, file));
        MultipartBody multipartBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("username", "lulu")//这个参数在服务器端可以接收到
                .addFormDataPart("upload", file.getName(), RequestBody.create(MultipartBody.FORM, file))
                .build();

        Request request = new Request.Builder()
                .url("http://127.0.0.1:8080/test")
                .post(multipartBody)
                .build();
        Call call = client.newCall(request);

        try {
            Response response = call.execute();
            if (response.isSuccessful()) {
                System.out.println(response.body().string());
            } else {
                System.out.println("访问失败:" + response.code());
            }

        } catch (IOException e) {
            e.printStackTrace();
        }


	}
	
	
}

 

RespEntity .java

 

public class RespEntity implements Serializable{

	 private int code;
	 private String msg;
	 private Object data;
	 private long timestamp ;
	
	 public RespEntity() {  }
	 
	 
	 public RespEntity(Object data ) {
		this.code = RespEnums.RESP_HTTP_SUCCESS.getCode();
		this.msg = RespEnums.RESP_HTTP_SUCCESS.getDesc();
		this.data = data;
		this.timestamp = System.currentTimeMillis();
	 }


	public int getCode() {
		return code;
	}
	public void setCode(int code) {
		this.code = code;
	}
	public String getMsg() {
		return msg;
	}
	public void setMsg(String msg) {
		this.msg = msg;
	}
	public Object getData() {
		return this.data;
	}
	public void setData(Object data) {
		this.data = data;
	}
	public long getTimestamp() {
		return timestamp;
	}
	public void setTimestamp(long timestamp) {
		this.timestamp = timestamp;
	}
}

 

RespEnums .java

public enum RespEnums {
	
	RESP_HTTP_SUCCESS(0,"000","HTTP SUCCESS")
	,RESP_HTTP_ERROR(100,"100","HTTP ERROR")
	
	,RESP_SUCCESS(200,"200","SUCCESS")
	,RESP_VALID_SUCCESS(210,"210","VALID SUCCESS")
	,RESP_VALID_FAIL(211,"211","VALID FAIL")
	,RESP_ERROR(400,"400","ERROR")
	
	,RESP_ERROR_PARAMS_NULL(401,"401","param is null")
	,RESP_ERROR_AUTH_FAIL(402,"402","auth fail")
	,RESP_ERROR_PARAMS_FAIL(403,"403","param fail")
	
	,RESP_OTHER_RESP_CODE(499,"499","OTHER_RESP_CODE")
	,RESP_EXCEPTION(500,"500","EXCEPTION")
	
	
	
	;

	private int code;
    private String sourceCode;
    private String desc;
    
    
    private RespEnums(int code, String sourceCode, String desc){
        this.setCode(code);
        this.setSourceCode(sourceCode);
        this.setDesc(desc);
    }


    /**
     * 根据编码获得基础编码对象
     * @param sourceCode
     * @return
     */
    public static RespEnums getBaseBySourceCode(String sourceCode){
    	RespEnums bc = null;
        for(RespEnums baseCodeEnum : RespEnums.values()){
            if (baseCodeEnum.sourceCode.equals(sourceCode)){
                bc = baseCodeEnum;
                break;
            }
        }
        return  bc;
    }

    /**
     * 根据编码获得基础编码对象
     * @param code
     * @return
     */
    public static RespEnums getBaseByCode(int code){
    	RespEnums bc = null;
        for(RespEnums baseCodeEnum : RespEnums.values()){
            if (baseCodeEnum.code == code ){
                bc = baseCodeEnum;
                break;
            }
        }
        return  bc;
    }


	public int getCode() {
		return code;
	}


	public void setCode(int code) {
		this.code = code;
	}


	public String getSourceCode() {
		return sourceCode;
	}


	public void setSourceCode(String sourceCode) {
		this.sourceCode = sourceCode;
	}


	public String getDesc() {
		return desc;
	}


	public void setDesc(String desc) {
		this.desc = desc;
	}

}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

捐助开发者 

在兴趣的驱动下,写一个免费的东西,有欣喜,也还有汗水,希望你喜欢我的作品,同时也能支持一下。 当然,有钱捧个钱场(支持支付宝和微信 以及扣扣群),没钱捧个人场,谢谢各位。

 

个人主页http://knight-black-bob.iteye.com/



 
 
 谢谢您的赞助,我会做的更好!

<think> 我们正在讨论如何使用OkHttp进行POST请求。根据引用内容,我们可以构建一个简单的示例。 首先,我们需要引入OkHttp的依赖(如引用[1]所示): <dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <version>4.9.1</version> </dependency> 然后,我们可以参考引用[2]中关于POST请求的部分,它提供了几种不同的POST请求方式,包括: 1. 发送JSON字符串 2. 发送application/x-www-form-urlencoded格式的数据 3. 上传文件 下面我将分别介绍这几种方式: ### 1. 发送JSON字符串 如果你需要发送一个JSON字符串到服务器,你可以这样写: ```java import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; public class OkHttpPostExample { public static void main(String[] args) { OkHttpClient client = new OkHttpClient(); // 设置JSON媒体类型 MediaType JSON = MediaType.parse("application/json; charset=utf-8"); // 创建请求体 String json = "{\"username\":\"example\", \"password\":\"example\"}"; RequestBody body = RequestBody.create(JSON, json); // 创建请求 Request request = new Request.Builder() .url("https://api.example.com/login") .post(body) // 使用POST方法 .build(); try (Response response = client.newCall(request).execute()) { System.out.println("Response: " + response.body().string()); } catch (Exception e) { e.printStackTrace(); } } } ``` ### 2. 发送application/x-www-form-urlencoded格式的数据 这种格式通常用于表单提交,数据格式为键值对。 ```java import okhttp3.FormBody; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; public class OkHttpPostForm { public static void main(String[] args) { OkHttpClient client = new OkHttpClient(); // 构建表单数据 RequestBody formBody = new FormBody.Builder() .add("username", "example") .add("password", "example") .build(); Request request = new Request.Builder() .url("https://api.example.com/login") .post(formBody) .build(); try (Response response = client.newCall(request).execute()) { System.out.println("Response: " + response.body().string()); } catch (Exception e) { e.printStackTrace(); } } } ``` ### 3. 上传文件 上传文件需要构建一个MultipartBody。 ```java import okhttp3.*; import java.io.File; public class OkHttpPostFile { public static void main(String[] args) { OkHttpClient client = new OkHttpClient(); // 设置文件路径 File file = new File("path_to_file.txt"); // 构建MultipartBody MediaType MEDIA_TYPE_TEXT = MediaType.parse("text/plain"); RequestBody requestBody = new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("file", file.getName(), RequestBody.create(file, MEDIA_TYPE_TEXT)) .addFormDataPart("other_field", "其他字段值") .build(); Request request = new Request.Builder() .url("https://api.example.com/upload") .post(requestBody) .build(); try (Response response = client.newCall(request).execute()) { System.out.println("Response: " + response.body().string()); } catch (Exception e) { e.printStackTrace(); } } } ``` 注意:以上代码示例中,异常处理使用了简单的打印,实际使用时可能需要更细致的处理。此外,OkHttpClient实例通常应该重用,而不是每次请求都创建新的实例。 另外,引用[2]中还提到了忽略Https证书验证的方法,但一般情况下不推荐在生产环境中忽略证书验证,因为它会降低安全性。 希望这些示例能够帮助你使用OkHttp进行POST请求。 §§相关问题§§ 1. 如何设置OkHttp请求的超时时间? 2. 如何在OkHttp中添加请求头(Headers)? 3. 如何处理OkHttp的异步请求? </think> 以下是使用OkHttp调用POST接口的详细方法,涵盖不同数据格式的请求方式: ### 基础POST请求步骤 1. **添加依赖**(Maven项目): ```xml <dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <version>4.9.1</version> </dependency> ``` 2. **核心代码结构**: ```java OkHttpClient client = new OkHttpClient(); // 构建请求体 RequestBody requestBody = ... // 根据数据类型创建 Request request = new Request.Builder() .url("https://api.example.com/endpoint") .post(requestBody) // 关键:声明为POST请求 .addHeader("Content-Type", "application/json") // 设置内容类型 .build(); try (Response response = client.newCall(request).execute()) { System.out.println(response.body().string()); } catch (IOException e) { e.printStackTrace(); } ``` ### 不同数据格式的POST实现 #### 1. 发送JSON数据 ```java MediaType JSON = MediaType.parse("application/json; charset=utf-8"); String json = "{\"name\":\"John\", \"age\":30}"; RequestBody body = RequestBody.create(json, JSON); Request request = new Request.Builder() .url("https://api.example.com/users") .post(body) .build(); ``` #### 2. 发送表单数据 ```java RequestBody formBody = new FormBody.Builder() .add("username", "testUser") .add("password", "pass123") .build(); Request request = new Request.Builder() .url("https://api.example.com/login") .post(formBody) .build(); ``` #### 3. 文件上传(Multipart) ```java MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png"); File file = new File("avatar.png"); RequestBody body = new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("file", file.getName(), RequestBody.create(file, MEDIA_TYPE_PNG)) .addFormDataPart("description", "用户头像") .build(); Request request = new Request.Builder() .url("https://api.example.com/upload") .post(body) .build(); ``` ### 关键注意事项 1. **请求头设置**: 通过`.addHeader()`方法添加必要的请求头,如: ```java .addHeader("Authorization", "Bearer token123") .addHeader("User-Agent", "MyApp/1.0") ``` 2. **超时控制**(推荐配置): ```java OkHttpClient client = new OkHttpClient.Builder() .connectTimeout(10, TimeUnit.SECONDS) .readTimeout(30, TimeUnit.SECONDS) .build(); ``` 3. **响应处理**: ```java try (Response response = client.newCall(request).execute()) { if (response.isSuccessful()) { String responseData = response.body().string(); // 处理响应数据 } else { System.err.println("请求失败: " + response.code()); } } ``` ### 完整示例(JSON POST) ```java import okhttp3.*; public class PostExample { public static void main(String[] args) throws IOException { OkHttpClient client = new OkHttpClient(); MediaType JSON = MediaType.parse("application/json; charset=utf-8"); String jsonBody = "{\"title\":\"测试标题\", \"content\":\"请求内容\"}"; Request request = new Request.Builder() .url("https://jsonplaceholder.typicode.com/posts") .post(RequestBody.create(jsonBody, JSON)) .addHeader("Accept", "application/json") .build(); try (Response response = client.newCall(request).execute()) { System.out.println(response.body().string()); } } } ``` ### 常见问题解决 - **中文乱码**:确保请求体使用`charset=utf-8` - **HTTPS证书问题**:使用`TrustManager`忽略证书验证(仅测试环境使用)[^2] - **连接池优化**:复用`OkHttpClient`实例(避免每次创建新对象)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值