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