티스토리 뷰

Spring Boot 프로젝트에 OkHttpClient로 동기와 비동기 방식으로 post요청하는 방법

 

1. Maven에 Dependency추가

<!-- https://mvnrepository.com/artifact/com.squareup.okhttp/okhttp -->
  <dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>3.4.2</version>
  </dependency>

 

2. 동기 요청방법

package com.example.demo;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.junit.jupiter.api.Test;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Dispatcher;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class OkHttpTest {
	
	private static final MediaType MEDIA_TYPE = MediaType.parse("text/plain");
	
	@Test
	public void test() throws IOException {
		  ExecutorService executorService = Executors.newSingleThreadExecutor();
		    Dispatcher dispatcher2 = new Dispatcher(executorService);
		   
			OkHttpClient client = new OkHttpClient();
			
			String fileName = "C:\\upload/1234.txt";
			
			    RequestBody requestBody = new MultipartBody.Builder()
			            .setType(MultipartBody.FORM)
			            .addFormDataPart("name", "tester1")
			            .addFormDataPart("file", "1234.jpeg",
			                RequestBody.create(MEDIA_TYPE, new File(fileName)))
			            .build();
			   
			    Request request = new Request.Builder()
			        .url("http://localhost:8080/attachment")
			        .post(requestBody)
			        .build();
			   
			    System.out.println(request);
			    
			    try (Response response = client.newCall(request).execute()) {
			        //return response.body().string();
			    }
			   
			   client.dispatcher().executorService().shutdown();
	}
}

 

3. 비동기 요청방법

package com.example.demo;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.junit.jupiter.api.Test;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Dispatcher;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class OkHttpTest {
	
	private static final MediaType MEDIA_TYPE = MediaType.parse("text/plain");
	
	@Test
	public void test() throws IOException {
		  ExecutorService executorService = Executors.newSingleThreadExecutor();
		    Dispatcher dispatcher2 = new Dispatcher(executorService);
		   
			OkHttpClient client = new OkHttpClient();
			
			String fileName = "C:\\upload/1234.txt";
			
			    RequestBody requestBody = new MultipartBody.Builder()
			            .setType(MultipartBody.FORM)
			            .addFormDataPart("name", "tester1")
			            .addFormDataPart("file", "1234.txt",
			                RequestBody.create(MEDIA_TYPE, new File(fileName)))
			            .build();
			   
			    Request request = new Request.Builder()
			        .url("http://localhost:8080/attachment")
			        .post(requestBody)
			        .build();
			   
			    System.out.println(request);
			    
			    client.newCall(request).enqueue(new Callback() {
			   
			        @Override public void onFailure(Call call, IOException e) {
			          System.out.println("fail: "+request);
			          e.printStackTrace();
			        }
			
			        @Override public void onResponse(Call call, Response response) throws IOException {
			          System.out.println("response in");
			          try (ResponseBody responseBody = response.body()) {
			        System.out.println("success: ");
			           
			        if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
			           
			          }
			        }
			   });
			   
			   client.dispatcher().executorService().shutdown();
	}
}

 

'java' 카테고리의 다른 글

[Java] 연산자와 제어문  (0) 2021.03.21
[Java] 언어의 기원  (0) 2021.03.14
[Java] OAuth인증을 통해 Request Token, Access Token 발급받기  (0) 2020.11.25
[Java] return true; return false;  (0) 2020.05.21
gradle Kotlin Groovy  (0) 2020.05.18
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/01   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함