很久没有用servlet的交互技术,生疏的遭不住。现在简单的说说servlet中http接口的创建及调用,便于大家理解,使用。
先说说服务端,就是提供服务方的代码:
pom.xml
junit
junit
3.8.1
test
javax.servlet
javax.servlet-api
3.1.0
provided
首先是提供一个接口的代码如下:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author cwc
* @date 2018年7月9日
* @version 1.0.0
* @description:创建一个Http接口
*/
public class SetInfo extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
//判断请求报文是否来自代维系统的ip地址
String ip = request.getRemoteHost();
// 获取收到的报文
BufferedReader reader = request.getReader();
String line = "";
StringBuffer inputString = new StringBuffer();
while ((line = reader.readLine()) != null) {
inputString.append(line);
System.out.println("接受到的数据"+line);
}
//如有必要,可以在报文中增加其他验证和加密的参数
//解析获取到的报文,根据ip地址、其他验证、加密等等来判断请求报文的服务器是否有权限
//如果请求验证合格,则根据请求的参数装配返回的报文
// 要返回的报文,append后面就添加你想要返回的报文,返回的数据可以结合你后面处理逻辑的业务层
StringBuffer resultBuffer = new StringBuffer();
resultBuffer.append("");
resultBuffer.append("");
resultBuffer.append("953947334 ");
resultBuffer.append("20120402113943 ");
resultBuffer.append("");
resultBuffer.append("线路 ");
resultBuffer.append("王加和 ");
resultBuffer.append("20120301000000 ");
resultBuffer.append("20120331235959 ");
resultBuffer.append("50 ");
resultBuffer.append("40 ");
resultBuffer.append("0.80 ");
resultBuffer.append("");
resultBuffer.append("");
resultBuffer.append(" ");
// 设置发送报文的格式
response.setContentType("text/xml");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
out.println(resultBuffer.toString());
out.flush();
out.close();
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
//将get方法放入post中,为安全性
doGet(request,response);
}
}
配置web.xml
Archetype Created Web Application
third
mytest.server.SetInfo
third
/SetInfo
之后就是服务的调用,先说说使用java自带的HttpURLConnection,这里不需要导入什么jar包,直接写个类调用就好。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* @author cwc
* @date 2018年7月7日
* @version 1.0.0
* @description: 调用http接口
*/
public class GetConsumer {
public static void main(String[]args) throws Exception{
System.out.println("开始发送接收——————————————————————————");
// tOne();
String url ="http://localhost:8080/myServers/SetInfo";
getURLContent(url);
}
public static void tOne() throws Exception{
System.out.println("调用servlet开始=================");
StringBuffer sendStr = new StringBuffer();
sendStr.append("");
sendStr.append("");
sendStr.append("953943547334 ");
sendStr.append("2012040211394324 ");
sendStr.append("");
sendStr.append("201203 ");
sendStr.append(" ");
sendStr.append(" ");
BufferedReader reader = null;
try {
String strMessage = "";
StringBuffer buffer = new StringBuffer();
// 接报文的地址
URL uploadServlet = new URL(
"http://localhost:8080/myServers/SetInfo");
HttpURLConnection servletConnection = (HttpURLConnection) uploadServlet
.openConnection();
// 设置连接参数
servletConnection.setRequestMethod("POST");
servletConnection.setDoOutput(true);
servletConnection.setDoInput(true);
servletConnection.setAllowUserInteraction(true);
// 开启流,写入XML数据
OutputStream output = servletConnection.getOutputStream();
System.out.println("发送的报文:");
System.out.println(sendStr.toString());
output.write(sendStr.toString().getBytes());
output.flush();
output.close();
// 获取返回的数据
InputStream inputStream = servletConnection.getInputStream();
reader = new BufferedReader(new InputStreamReader(inputStream));
while ((strMessage = reader.readLine()) != null) {
buffer.append(strMessage);
}
System.out.println("接收返回值:" + buffer);
} catch (java.net.ConnectException e) {
throw new Exception();
} finally {
if (reader != null) {
reader.close();
}
}
}
/**
* 程序中访问http数据接口
*/
public static String getURLContent(String urlStr) {
/** 网络的url地址 */
URL url = null;
/** http连接 */
HttpURLConnection httpConn = null;
/**//** 输入流 */
BufferedReader in = null;
StringBuffer sb = new StringBuffer();
try {
url = new URL(urlStr);
in = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
String str = null;
while ((str = in.readLine()) != null) {
sb.append(str);
}
} catch (Exception ex) {
} finally {
try {
if (in != null) {
in.close();
}
} catch (IOException ex) {
}
}
String result = sb.toString();
System.out.println(result);
return result;
}
}
补充:使用httpClient的方式调用
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
/**
* @author cwc
* @date 2018年7月10日
* @version 1.0.0
* @description:通过httpClient调用接口
*/
public class MyHttpClient {
public static void main(String[]args){
getHttpData();
}
public static void getHttpData(){
//1.使用默认的配置的httpclient
CloseableHttpClient client = HttpClients.createDefault();
HttpGet httpGet = null;
InputStream inputStream = null;
CloseableHttpResponse response = null;
try {
//2.使用get方法,传递参数
URI url =new URIBuilder()
.setScheme("http")
.setHost("192.168.100.6:8080")//ip:port
.setPath("/detail/index.htm")//接口
.setParameter("mkdirName", "/MyTestTwoooooo")//key,value
.setParameter("fileName", "/MyTestTwo/One")
.build();
System.out.println(url);
httpGet = new HttpGet(url);
//3.执行请求,获取响应
response = client.execute(httpGet);
//看请求是否成功,这儿打印的是http状态码
System.out.println(response.getStatusLine().getStatusCode());
//4.获取响应的实体内容,就是我们所要抓取得网页内容
HttpEntity entity = response.getEntity();
//5.将其打印到控制台上面
if (entity != null) {
inputStream = entity.getContent();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
方法比较简单,代码可以直接复制使用。
继续加油,最近有些懒了。