使用okhttp构造http请求发送给服务端
主函数启动springbooot,@Controller注解声明是一个控制器,@RequestMapping配置URL和方法之间的映射,向http://localhost:8080/hi发送空请求即可触发test方法,可以测出请发送处理时延。
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
@Controller
@SpringBootApplication
public class HttpClientExample {
public static final MediaType FORM = MediaType.parse("multipart/form-data; boundary=something");
public String post(OkHttpClient client, String url) throws IOException {
byte[] aa = new byte[684091];
String str = new String(aa);
RequestBody body = RequestBody.create(FORM,str);
Request request = new Request.Builder().url(url)
.post(body).build();
Response response = client.newCall(request).execute();
return response.body().string();
}
@RequestMapping("/hi")
@ResponseBody
public String test()
{
OkHttpClient client = new OkHttpClient();
try {
long start = System.currentTimeMillis();
String res = new HttpClientExample().post(client, "填入http的url");
long end = System.currentTimeMillis();
System.out.println("程序运行时间: "+(end-start)+"ms");
return res;
} catch (IOException e) {
e.printStackTrace();
return "error_e";
}
}
public static void main(String[] args) {
SpringApplication.run(HttpClientExample.class, args);
}
}