关于http接口开发java的信息

网友投稿 272 2023-03-19


本篇文章给大家谈谈http接口开发java,以及对应的知识点,希望对各位有所帮助,不要忘了收藏本站喔。 今天给各位分享http接口开发java的知识,其中也会对进行解释,如果能碰巧解决你现在面临的问题,别忘了关注本站,现在开始吧!

本文目录一览:

java如何创建一个简单的http接口?

1.修改web.xml文件
<!-- 模拟HTTPhttp接口开发java的调用http接口开发java,写http接口开发java的一个http接口 -- <servlet <servlet-nameTestHTTPServer</servlet-name <servlet-classcom.atoz.http.SmsHTTPServer</servlet-class </servlet <servlet-mapping <servlet-nameTestHTTPServer</servlet-name <url-pattern/httpServer</url-pattern </servlet-mapping
2.新建SmsHTTPServer.java文件
package com.atoz.http;
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;
import com.atoz.action.order.SendSMSAction; import com.atoz.util.SpringContextUtil;
public class SmsHTTPServer extends HttpServlet { private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); PrintWriter out = response.getWriter(); String content = request.getParameter("content"); //String content = new String(request.getParameter("content").getBytes("iso-8859-1"), "utf-8"); String mobiles = request.getParameter("mobiles"); String businesscode = request.getParameter("businesscode"); String businesstype = request.getParameter("businesstype"); if (content == null || "".equals(content) || content.length() <= 0) { System.out.println("http call failed,参数content不能为空,程序退出"); } else if (mobiles == null || "".equals(mobiles) || mobiles.length() <= 0) { System.out.println("http call failed,参数mobiles不能为空,程序退出"); } else { /*SendSMSServiceImpl send = new SendSMSServiceImpl();*/ SendSMSAction sendSms = (SendSMSAction) SpringContextUtil.getBean("sendSMS"); sendSms.sendSms(content, mobiles, businesscode, businesstype); System.out.println("---http call success---"); } out.close(); }
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } }
3.调用http接口
String content = "测试"; content = URLEncoder.encode(content, "utf-8"); String url = "http://localhost:8180/atoz_2014/httpServer?content=" + content + "mobiles=15301895007"; URL httpTest; try { httpTest = new URL(url); BufferedReader in; try { in = new BufferedReader(new InputStreamReader( httpTest.openStream())); String inputLine = null; String resultMsg = null; //得到返回信息的xml字符串 while ((inputLine = in.readLine()) != null) if(resultMsg != null){ resultMsg += inputLine; }else { resultMsg = inputLine; } in.close(); } catch (MalformedURLException e) { e.printStackTrace(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }
打字不易http接口开发java,望采纳http接口开发java,谢谢

怎么用java写一个http接口

一个servlet接口就可以http接口开发java了啊:

HTTP Header 请求实例

下面的实例使用 HttpServletRequest 的 getHeaderNames() 方法读取 HTTP 头信息。该方法返回一个枚举http接口开发java,包含与当前的 HTTP 请求相关的头信息。

一旦我们有一个枚举http接口开发java,我们可以以标准方式循环枚举http接口开发java,使用 hasMoreElements() 方法来确定何时停止,使用 nextElement() 方法来获取每个参数的名称。

//导入必需的 java 库
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/DisplayHeader")
//扩展 HttpServlet 类
public class DisplayHeader extends HttpServlet {
// 处理 GET 方法请求的方法
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
// 设置响应内容类型
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String title = "HTTP Header 请求实例 - 菜鸟教程实例";
String docType =
"<!DOCTYPE html \n";
out.println(docType +
"<html\n" +
"<head<meta charset=\"utf-8\"<title" + title + "</title</head\n"+
"<body bgcolor=\"#f0f0f0\"\n" +
"<h1 align=\"center\"" + title + "</h1\n" +
"<table width=\"100%\" border=\"1\" align=\"center\"\n" +
"<tr bgcolor=\"#949494\"\n" +
"<thHeader 名称</th<thHeader 值</th\n"+
"</tr\n");
Enumeration headerNames = request.getHeaderNames();
while(headerNames.hasMoreElements()) {
String paramName = (String)headerNames.nextElement();
out.print("<tr<td" + paramName + "</td\n");
String paramValue = request.getHeader(paramName);
out.println("<td " + paramValue + "</td</tr\n");
}
out.println("</table\n</body</html");
}
// 处理 POST 方法请求的方法
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}

java开发接口利用http协议传输数据

5.1请求程序代码
public void sendMessage() throws Exception {
System.out.println("调用servlet开始=================");
StringBuffer sendStr = new StringBuffer();
sendStr.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?");
sendStr.append("<report_data");
sendStr.append("<request_req953943547334</request_req");
sendStr.append("<request_time2012040211394324</request_time");
sendStr.append("<request_param");
sendStr.append("<query_month201203</query_month");
sendStr.append("</request_param");
sendStr.append("</report_data");

BufferedReader reader = null;

try {
String strMessage = "";
StringBuffer buffer = new StringBuffer();

// 接报文http接口开发java的地址
URL uploadServlet = new URL(
"http://localhost:9090/TestTransfers");

HttpURLConnection servletConnection = (HttpURLConnection) uploadServlet
.openConnection();
// 设置连接参数
servletConnection.setRequestMethod("POST");
servletConnection.setDoOutput(true);
servletConnection.setDoInput(true);
servletConnection.setAllowUserInteraction(true);

// 开启流http接口开发java,写入XML数据
OutputStream output = servletConnection.getOutputStream();
System.out.println("发送http接口开发java的报文http接口开发java:");
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();
}

}
}
5.2响应程序代码
public class TestTransfers extends HttpServlet {

private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
}

protected void doPost(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);
}

//如有必要,可以在报文中增加其http接口开发java他验证和加密的参数
//解析获取到的报文,根据ip地址、其他验证、加密等等来判断请求报文的服务器是否有权限

//如果请求验证合格,则根据请求的参数装配返回的报文

// 要返回的报文
StringBuffer resultBuffer = new StringBuffer();
resultBuffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?");
resultBuffer.append("<report_data");
resultBuffer.append("<respon_req953947334</respon_req");
resultBuffer.append("<respon_time20120402113943</respon_time");
resultBuffer.append("<result");
resultBuffer.append("<id0000</id");
resultBuffer.append("<comment成功</comment");
resultBuffer.append("</result");
resultBuffer.append("<items");
resultBuffer.append("<item");
resultBuffer.append("<county长治县</county");
resultBuffer.append("<company铁通</company");
resultBuffer.append("<speciality线路</speciality");
resultBuffer.append("<personnel王加和</personnel");
resultBuffer.append("<begin_time20120301000000</begin_time");
resultBuffer.append("<end_time20120331235959</end_time");
resultBuffer.append("<plan_quantity50</plan_quantity");
resultBuffer.append("<checkout_quantity40</checkout_quantity");
resultBuffer.append("<patrol_rate0.80</patrol_rate");
resultBuffer.append("</item");
//......
//......
//......
//循环组装响应的报文

resultBuffer.append("</items");
resultBuffer.append("</report_data");

// 设置发送报文的格式
response.setContentType("text/xml");
response.setCharacterEncoding("UTF-8");

PrintWriter out = response.getWriter();
out.println(resultBuffer.toString());
out.flush();
out.close();
}
}

java http调用接口书写?

1、直接用servlet就可以http接口开发javahttp接口开发java,request.getInputStream()http接口开发java,然后解析xml,然后你http接口开发java的业务操作,组装XML,response.getOutputStream()写出去就OK了4但这个性能低,而且还要依赖web容器imq2、socket实现http协议,把HTTP协议好好看看,自己解析(其实就是字符串的操作哦)。3、你要是只做客户端的话可以用httpClient284几行代码搞定了

java如何使用http方式调用第三方接口?最好有代码~谢谢

星号是IP地址和端口号
public class HttpUtil {
private final static Log log = LogFactory.getLog(HttpUtil.class);
public static String doHttpOutput(String outputStr,String method) throws Exception {
Map map = new HashMap();
String URL = "http://****/interface/http.php" ;
String result = "";
InputStream is = null;
int len = 0;
int tmp = 0;
OutputStream output = null;
BufferedOutputStream objOutput = null;
String charSet = "gbk";
System.out.println("URL of fpcy request");
System.out.println("=============================");
System.out.println(URL);
System.out.println("=============================");
HttpURLConnection con = getConnection(URL);
try {
output = con.getOutputStream();
objOutput = new BufferedOutputStream(output);
objOutput.write(outputStr.getBytes(charSet));
objOutput.flush();
output.close();
objOutput.close();
int responseCode = con.getResponseCode();
if (responseCode == 200) {
is = con.getInputStream();
int dataLen = is.available();
int retry = 5;
while (dataLen == 0 retry 0) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
dataLen = is.available();
retry--;
log.info("未获取到任何数据,尝试重试,当前剩余次数" + retry);
}
log.info("获取到报文单位数据长度:" + dataLen);
byte[] bytes = new byte[dataLen];
while ((tmp = is.read()) != -1) {
bytes[len++] = (byte) tmp;
if (len == dataLen) {
dataLen = bytes.length + dataLen;
byte[] newbytes = new byte[dataLen];
for (int i = 0; i < bytes.length; i++) {
newbytes[i] = bytes[i];
}
bytes = newbytes;
}
}
result = new String(bytes, 0, len, charSet);
} else {
String responseMsg = "调用接口失败,返回错误信息:" + con.getResponseMessage() + "(" + responseCode + ")";
System.out.println(responseMsg);
throw new Exception(responseMsg);
}
} catch (IOException e2) {
log.error(e2.getMessage(), e2);
throw new Exception("接口连接超时!,请检查网络");
}
con.disconnect();
System.out.println("=============================");
System.out.println("Contents of fpcy response");
System.out.println("=============================");
System.out.println(result);
Thread.sleep(1000);
return result;
}
private static HttpURLConnection getConnection(String URL) throws Exception {
Map map = new HashMap();
int rTimeout = 15000;
int cTimeout = 15000;
String method = "";
method = "POST";
boolean useCache = false;
useCache = false;
HttpURLConnection con = null;
try {
con = (HttpURLConnection) new URL(URL).openConnection();
} catch (IOException e) {
log.error(e.getMessage(), e);
throw new Exception("URL不合法!");
}
try {
con.setRequestMethod(method);
} catch (ProtocolException e) {
log.error(e.getMessage(), e);
throw new Exception("通信协议不合法!");
}
con.setConnectTimeout(cTimeout);
con.setReadTimeout(rTimeout);
con.setUseCaches(useCache);
con.setDoInput(true);
con.setDoOutput(true);
log.info("当前连接信息: URL:" + URL + "," + "Method:" + method
+ ",ReadTimeout:" + rTimeout + ",ConnectTimeOut:" + cTimeout
+ ",UseCaches:" + useCache);
return con;
}
public static void main(String[] args) throws Exception {
String xml="<?xml version=\"1.0\" encoding=\"GBK\" ?<document<txcode101</txcode<netnumber100001</netnumber.........</document";
response=HttpUtil.doHttpOutput(xml, "post");
JSONObject json= JSONObject.parseObject(response);
String retcode=json.getString("retcode");
调用这个类就能获得返回的参数。。over.
}
}
}

java如何调用对方http接口

你是指发送http请求吗,可以使用Apache 的 HttpClient

        //构建HttpClient实例
        CloseableHttpClient httpclient = HttpClients.createDefault();        //设置请求超时时间
        RequestConfig requestConfig = RequestConfig.custom()                .setSocketTimeout(60000)                .setConnectTimeout(60000)                .setConnectionRequestTimeout(60000)                .build();        //指定POST请求
        HttpPost httppost = new HttpPost(url);
        httppost.setConfig(requestConfig);        //包装请求体
        List<NameValuePair params = new ArrayList<NameValuePair();        params.addAll(content);
        HttpEntity request = new UrlEncodedFormEntity(params, "UTF-8");        //发送请求
        httppost.setEntity(request);
        CloseableHttpResponse httpResponse = httpclient.execute(httppost);        //读取响应
        HttpEntity entity = httpResponse.getEntity();        String result = null;        if (entity != null) {
            result = EntityUtils.toString(entity, "UTF-8");
        }
关于http接口开发java和的介绍到此就结束了,不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站。 http接口开发java的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于、http接口开发java的信息别忘了在本站进行查找喔。

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

上一篇:java开发之spring webflow实现上传单个文件及多个文件功能实例
下一篇:详解使用webpack打包编写一个vue
相关文章

 发表评论

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