okhttp3 POST请求application/x-www-form-urlencoded如何跳过FormBody表单元素的编码

 okhttp3  application/x-www-form-urlencoded请求如何跳过FormBody表单元素的编码

使用 RequestBody.Companion. create

public class OkHttpUtil {

	public static String postMap(String url, Map param) throws UnsupportedEncodingException {
		// 创建一个OkHttpClient对象
		OkHttpClient okHttpClient = new OkHttpClient();

		// 创建一个RequestBody(参数1:数据类型 参数2传递的json串)
		FormBody.Builder builder = new FormBody.Builder();

		for (String key : param.keySet()) {
			Object obj = param.get(key);
			if (obj != null) {
				builder.addEncoded(key, param.get(key).toString());
			} else {
				builder.addEncoded(key, "");
			}
		}
		FormBody  requestBody = builder.build();

		// 创建一个请求对象
		Request request = new Request.Builder().url(url).post(requestBody).build();
		// 发送请求获取响应
		try {
			Response response = okHttpClient.newCall(request).execute();
			// 判断请求是否成功
			if (response.isSuccessful()) {
				// 打印服务端返回结果
				return response.body().string();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "{}";
	}

	public static String postMap1(String url,  Map param) {
		// 创建一个OkHttpClient对象
		OkHttpClient okHttpClient = new OkHttpClient();

		StringBuilder builder = new StringBuilder();

		param.forEach((name, value) ->{
			if (builder.length() != 0) {
				builder.append('&');
			}
			builder.append(name);
			if (value != null) {
				builder.append('=');
				builder.append(value);
			}

		});

		//return builder.toString();

		RequestBody requestBody = RequestBody.create(MediaType.get("application/x-www-form-urlencoded"), builder.toString());

		// 创建一个请求对象
		Request request = new Request.Builder().url(url).post(requestBody).build();
		// 发送请求获取响应
		try {
			Response response = okHttpClient.newCall(request).execute();
			// 判断请求是否成功
			if (response.isSuccessful()) {
				String body = response.body().string();
				// 打印服务端返回结果
				return body;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "{}";
	}
}

你可能感兴趣的:(Java,java,jvm,spring,restful)