SpringBoot使用OkHttp


参考文章:

导入依赖:

<dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>3.6.0</version>
</dependency>

调用POST方法:

MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
Request request = new Request.Builder()
	.url(dataAddr)
	.post(RequestBody.create(mediaType, reqJsonStr))
	.build();
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.newCall(request).enqueue(new Callback() {
	@Override
	public void onFailure(Call call, IOException e) {
		log.error("onFailure: {} ",e.getMessage());
	}

	@Override
	public void onResponse(Call call, Response response) throws IOException {
		//先使用String进行接收
		String responseStr = response.body().string();
		log.info("responseStr: "+responseStr);

		JSONObject resJSONObject = JSON.parseObject(responseStr);
		if (resJSONObject.get("code").equals(200)) {
			JSONArray jsonArray = (JSONArray) resJSONObject.get("data");
			//进行业务处理
		}
	}
});


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM