可以使用apache.commons下的一个httpclient的库,c#使用的asp.net下使用webapi对外提供http服务,然后发布在iis服务器上,就可以对外暴露接口了
一,引入apache.commons依赖
![](https://img-blog.csdnimg.cn/1e763367f1b446a880b5c8a89dc031c8.png)
二,在你需要调用的接口中编辑请求信息,比如数据格式,编码格式等
废话不多说,直接上代码,不过这里要区分一下,get请求和post请求是有区别的,其次post请求参数的格式也好多种,我这边只列举json格式的;
//get请求
@GetMapping("/web/get")
public String getHttp() {
String responseMsg = "";
HttpClient httpClient = new HttpClient();
GetMethod getMethod = new GetMethod("http://192.168.31.124:8086/actionApi/UserInfo/Getsstring");
getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler());
try {
httpClient.executeMethod(getMethod);
ByteArrayOutputStream out = new ByteArrayOutputStream();
InputStream in = getMethod.getResponseBodyAsStream();
int len = 0;
byte[] buf = new byte[1024];
while((len=in.read(buf))!=-1){
out.write(buf, 0, len);
}
responseMsg = out.toString("UTF-8");
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
//释放连接
getMethod.releaseConnection();
}
return responseMsg;
}
//post请求
@PostMapping("/add/user")
public String postHttp(Student student) throws UnsupportedEncodingException, JsonProcessingException {
ObjectMapper JSON=new ObjectMapper();
String responseMsg = "";
String json=JSON.writeValueAsString(student);
HttpClient httpClient = new HttpClient();
httpClient.getParams().setContentCharset("UTF-8");
PostMethod postMethod = new PostMethod("http://192.168.31.124:8086/actionApi/UserInfo/InsertData");
RequestEntity entity = new StringRequestEntity(json,"application/json", "UTF-8");
postMethod.setRequestEntity(entity);
try {
httpClient.executeMethod(postMethod);
ByteArrayOutputStream out = new ByteArrayOutputStream();
InputStream in = postMethod.getResponseBodyAsStream();
int len = 0;
byte[] buf = new byte[1024];
while((len=in.read(buf))!=-1){
out.write(buf, 0, len);
}
responseMsg = out.toString("UTF-8");
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
postMethod.releaseConnection();
}
return responseMsg;
}