SpringBoot 接口开发教程(httpclient客户端)

网友投稿 416 2022-08-22


SpringBoot 接口开发教程(httpclient客户端)

目录SpringBoot接口开发服务端客户端post请求get请求SpringBoot之httpclient使用引入相关依赖编写相关工具类业务代码中使用

SpringBoot接口开发

服务端

@RestController

@RequestMapping("/landary")

public class landaryController {

@RequestMapping("adduser")

public jsONObject addUser(@RequestBody JSONObject userEntity)

{

System.out.println(JSONObject.toJSONString(userEntity));

JSONObject json=new JSONObject();

json.fluentPut("code","500").fluentPut("result",userEntity);

return json;

}

@Rhttp://equestMapping("showuser")

public Object showUser()

{

return JSON.toJSONString("hhh");

}

}

客户端post请求

public static String sendSms(String uid,String title,String content){

HttpClient httpclient = new DefaultHttpClient();

String smsUrl="http://127.0.0.1:8088/landary/adduser";

HttpPost httppost = new HttpPost(smsUrl);

String strResult = "";

try {

JSONObject jobj = new JSONObject();

jobj.put("uid", uid);

jobj.put("title", title);

jobj.put("content",content);

System.out.println(jobj.toString());

// nameValuePairs.add(new BasicNameValuePair("msg", (jobj.toString())));

/* httppost.addHeader("Content-type", "application/json; charset=utf-8");

httppost.setHeader("Accept", "application/json");

httppost.setEntity(new StringEntity(jobj.toString(), Charset.forName("UTF-8")));*/

StringEntity s = new StringEntity(jobj.toString());

s.setContentEncoding("UTF-8");

s.setContentType("application/json");//发送json数据需要设置contentType

httppost.setEntity(s);

HttpResponse response = httpclient.execute(httppost);

if (response.getStatusLine().getStatusCode() == 200) {

/*读返回数据*/

String conResult = EntityUtils.toString(response

.getEntity());

System.out.println(conResult);

JSONObject sobj = new JSONObject();

sobj = JSONObject.parseObject(conResult);

String result = sobj.getString("result");

String code = sobj.getString("code");

if(code.equals("500")){

System.out.println(result);

strResult += "发送成功";

}else{

strResult += "发送失败,"+code;

}

} else {

String err = response.getStatusLine().getStatusCode()+"";

strResult += "发送失败:"+err;

}

} catch (ClientProtocolException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

return strResult;

}

get请求

/**

* 发送 get请求

*/

public void get() {

CloseableHttpClient httpclient = HttpClients.createDefault();

try {

// 创建httpget.

HttpGet httpget = new HttpGet("http://127.0.0.1:8088/landary/showuser");

System.out.println("executing request " + httpget.getURI());

// 执行get请求.

CloseableHttpResponse response = httpclient.execute(httpget);

try {

// 获取响应实体

HttpEntity entity = response.getEntity();

System.out.println("--------------------------------------");

// 打印响应状态

System.out.println(response.getStatusLine());

if (entity != null) {

// 打印响应内容长度

System.out.println("Response content length: " + entity.getContentLength());

// 打印响应内容

System.out.println("Response content: " + EntityUtils.toString(entity));

}

System.out.println("------------------------------------");

} finally {

response.close();

}

} catch (ClientProtocolException e) {

e.printStackTrace();

} catch (ParseException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

} finally {

// 关闭连接,释放资源

try {

httpclient.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

SpringBoot之httpclient使用

超文本传输协议(HTTP,HyperText Transfer Protocol)是互联网上应用最为广泛的一种网络协议。所有的WWW文件都必须遵守这个标准。而HttpClient是可以支持http相关协议的工具包

它有如下功能:

1.实现了所有的http方法(GET,POST,PUT,HEAD 等)

2.支持自动转向

3.支持 HTTPS 协议

4.支持代理服务器等

既然HttpClient使用这么广泛,则本文讲解下Spring Boot 中怎么使用HttpClient.如下:

引入相关依赖

org.apache.httpcomponents

httpclient

org.apache.httpcomponents

httpcore

org.apache.httpcomponents

httpmime

org.apache.commons

commons-lang3

3.4

commons-lang

commons-lang

2.6

com.alibaba

fastjson

1.2.4

编写相关工具类

写个http的工具类,以便业务代码直接调用,如下:

/**

* Http工具类

*/

public class HttpUtils {

/**

* 发送POST请求

* @param url 请求url

* @param data 请求数据

* @return 结果

*/

@SuppressWarnings("deprecation")

public static String doPost(String url, String data) {

CloseableHttpClient httpClient = HttpClients.createDefault();

HttpPost httpPost = new HttpPost(url);

RequestConfig requestConfig = RequestConfig.custom()

.setSocketTimeout(10000).setConnectTimeout(20000)

.setConnectionRequestTimeout(10000).build();

httpPost.setConfig(requestConfig);

String context = StringUtils.EMPTY;

if (!StringUtils.isEmpty(data)) {

StringEntity body = new StringEntity(data, "utf-8");

httpPost.setEntity(body);

}

// 设置回调接口接收的消息头

httpPost.addHeader("Content-Type", "application/json");

CloseableHttpResponse response = null;

try {

response = httpClient.execute(httpPost);

HttpEntity entity = response.getEntity();

context = EntityUtils.toString(entity, HTTP.UTF_8);

} catch (Exception e) {

e.getStackTrace();

} finally {

try {

response.close();

httpPost.abort();

httpClient.close();

} catch (Exception e) {

e.getStackTrace();

}

}

return context;

}

/**

* 解析出url参数中的键值对

* @param url url参数

* @return 键值对

*/

public static Map getRequestParam(String url) {

Map map = new HashMap();

String[] arrSplit = null;

// 每个键值为一组

arrSplit = url.split("[&]");

for (String strSplit : arrSplit) {

String[] arrSplitEqual = null;

arrSplitEqual = strSplit.split("[=]");

// 解析出键值

if (arrSplitEqual.length > 1) {

// 正确解析

map.put(arrSplitEqual[0], arrSplitEqual[1]);

} else {

if (arrSplitEqual[0] != "") {

map.put(arrSplitEqual[0], "");

}

}

}

return map;

}

}

业务代码中使用

业务中代码使用,拼装请求Url和请求数据,就可以调用工具类里的doPost()方法开始直接使用咯。如下:

private String getFileStorePath(String courtId, String seesionId){

String fileStorePath = StringUtils.EMPTY;

//请求参数

String data = "{\"courtId\":\"" + courtId + "\",\"sessionId\":\"" + seesionId + "\"}";

String fileServiceUrl="http://111.11.11.11:8086";

//发送请求,获取结果

String result = HttpUtils.doPost(fileServiceUrl + "/ms-service/voice/search", data);

if(StringUtils.isNotBlank(result)){

com.alibaba.fastjson.JSONObject jsonobject = JSON.parseObject(result);

fileStorePath = jsonobject.getString("path");

logger.info("fileStorePath = " + fileStorePath);

}

return fileStorePath;

}


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Python文件操作与面向对象(python中的面向对象详解)
下一篇:python学习路线(python自学路线及教程)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~