在java開發(fā)中,發(fā)起http請(qǐng)求是非常常見的需求,常用的有HttpClient,下面聊一下okhttp3的請(qǐng)求方式。
1、引入okhttp3依賴
<dependency>
<groupId>io.github.admin4j</groupId>
<artifactId>http</artifactId>
<version>0.4.0</version>
</dependency>
2、提供springboot工程及http接口
@RestController
public class HelloController {
/**
* @description: get請(qǐng)求
*/
@GetMapping("/hello")
public String hello(@RequestParam String name) {
return "hello," + name;
}
/**
* @description: get請(qǐng)求
*/
@GetMapping("hello2/{name}")
public String hello2(@PathVariable("name") String name) {
return "hello2," + name;
}
/**
* @description: post請(qǐng)求
*/
@PostMapping("hello3")
public String hello3(@RequestBody Map map) {
return map.get("name").toString();
}
/**
* @description: form表單請(qǐng)求
*/
@RequestMapping("hello4")
public String hello4(@RequestParam Map map) {
return map.get("name").toString();
}
/**
* @description: post請(qǐng)求
*/
@RequestMapping("hello5")
public Object hello5(@RequestBody Map map) {
return map;
}
}
3、http請(qǐng)求文章來源:http://www.zghlxwxcb.cn/news/detail-539743.html
public class App {
public static void main(String[] args) {
System.out.println("Hello World!");
// get
//okhttp3.Response getResponse = HttpUtil.get("", Pair.of("", ""));
JSONObject getResponse = HttpJsonUtil.get("http://localhost:8080/hello", Pair.of("name", "liubei"));
System.out.println("get=" + getResponse);
// post
//okhttp3.Response postResponse = HttpUtil.post("", "");
Map<String, Object> params = new HashMap<>(16);
params.put("name", "admin");
JSONObject postResponse = HttpJsonUtil.post("http://localhost:8080/hello3", params);
System.out.println("post=" + postResponse);
// form
Map<String, Object> formParams = new HashMap<>(16);
formParams.put("name", "sunquan");
//okhttp3.Response formResponse = HttpUtil.postForm("", formParams);
Object formResponse = HttpJsonUtil.postForm("http://localhost:8080/hello4", formParams);
System.out.println("form=" + formResponse);
}
}
4、請(qǐng)求結(jié)果
get請(qǐng)求
post請(qǐng)求
form表單請(qǐng)求
可見發(fā)起http請(qǐng)求還是挺方便的,感興趣的小伙伴可以試試~~~///(v)\~~~文章來源地址http://www.zghlxwxcb.cn/news/detail-539743.html
到了這里,關(guān)于Java之okhttp3請(qǐng)求方式的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!