导航:首页 > 编程语言 > javahttp接口开发

javahttp接口开发

发布时间:2023-03-26 16:28:15

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_req>953943547334</request_req>");
sendStr.append("<request_time>201204094324</request_time>");
sendStr.append("<request_param>");
sendStr.append("<query_month>201203</query_month>");
sendStr.append("</request_param>");
sendStr.append("</report_data>");

BufferedReader reader = null;

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

// 接报文的地址
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);

// 开启流,写入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();
}

}
}
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);
}

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

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

// 要返回的报文
StringBuffer resultBuffer = new StringBuffer();
resultBuffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
resultBuffer.append("<report_data>");
resultBuffer.append("<respon_req>953947334</respon_req>");
resultBuffer.append("<respon_time>2012040943</respon_time>");
resultBuffer.append("<result>");
resultBuffer.append("<id>0000</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_time>20120301000000</begin_time>");
resultBuffer.append("<end_time>20120331235959</end_time>");
resultBuffer.append("<plan_quantity>50</plan_quantity>");
resultBuffer.append("<checkout_quantity>40</checkout_quantity>");
resultBuffer.append("<patrol_rate>0.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+post+xml接口

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

❸ java如何调用对方http接口

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

//构建HttpClient实例
CloseableHttpClienthttpclient=HttpClients.createDefault();//设置请求超时时间
RequestConfigrequestConfig=RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000).setConnectionRequestTimeout(60000).build();//指定POST请求
HttpPosthttppost=newHttpPost(url);
httppost.setConfig(requestConfig);//包装请求体
List<NameValuePair>params=newArrayList<NameValuePair>();params.addAll(content);
HttpEntityrequest=newUrlEncodedFormEntity(params,"UTF-8");//发送请求
httppost.setEntity(request);
=httpclient.execute(httppost);//读取响应
HttpEntityentity=httpResponse.getEntity();Stringresult=null;if(entity!=null){
result=EntityUtils.toString(entity,"UTF-8");
}

❹ 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><txcode>101</txcode><netnumber>100001</netnumber>.........</document>";

response=HttpUtil.doHttpOutput(xml, "post");
JSONObject json= JSONObject.parseObject(response);
String retcode=json.getString("retcode");
调用这个类就能获得返回的参数。。over.

}

}
}

❺ 如何用Java通过POST方法向HTTP接口传递数据

这是corejava2的例子x0dx0aURLConnectionconnection=url.openConnection();//url为http服务器地址x0dx0aconnection.setDoOutput(true);x0dx0aPrintWriteroutx0dx0a=newPrintWriter(connection.getOutputStream());//获得输出流x0dx0a//向服务器传递参数x0dx0aEnumerationenum=nameValuePairs.keys();x0dx0awhile(enum.hasMoreElements())x0dx0a{Stringname=(String)enum.nextElement();x0dx0aStringvalue=nameValuePairs.getProperty(name);x0dx0acharch;x0dx0aif(enum.hasMoreElements())ch='&'elsech='\n'x0dx0aout.print(name+"="x0dx0a+URLEncoder.encode(value)+ch);x0dx0aSystem.out.println(name+value);x0dx0a}x0dx0ax0dx0aout.close();x0dx0a//获取输入流x0dx0aBufferedReaderin;x0dx0atryx0dx0a{in=newBufferedReader(newx0dx0aInputStreamReader(connection.getInputStream()));x0dx0a}x0dx0acatch()x0dx0a{InputStreamerrx0dx0a=((HttpURLConnection)connection).getErrorStream();x0dx0aif(err==null)throwexception;x0dx0ain=newBufferedReader(newInputStreamReader(err));x0dx0a}x0dx0aStringBufferresponse=newStringBuffer();x0dx0aStringline;x0dx0a//读取数据x0dx0awhile((line=in.readLine())!=null)x0dx0aresponse.append(line+"\n");x0dx0ax0dx0ain.close();x0dx0areturnresponse.toString();x0dx0a}x0dx0a}

❻ java多线程,调用http接口报错,java.net.ConnectException: Connection refused: connect

能成功首先排除防火墙或端口开发问题;
其次确定你连接的端口是否有最大连接数限制(类似mysql有最大连接线程数);
还有就是对应服务的拒绝策略是啥,默认丢弃

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

1.修改web.xml文件
<!-- 模拟HTTP的调用,写的一个http接口 --> <servlet> <servlet-name>TestHTTPServer</servlet-name> <servlet-class>com.atoz.http.SmsHTTPServer</servlet-class> </servlet> <servlet-mapping> <servlet-name>TestHTTPServer</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(); }
打字不易,望采纳,谢谢

❽ javaweb、jsp中调用外部的http接口

import java.net.*;
import java.io.*;

public class URLReader {
public static void main(String[] args) throws Exception {
URL yahoo = new URL("http://www..com/query.jsp?param1=value2¶m2=value2");
BufferedReader in = new BufferedReader(
new InputStreamReader(
yahoo.openStream()));

String inputLine;

while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);

in.close();
}
}

❾ Java中ServletRequest接口与HttpServletRequest接口有什么区别

HttpServletRequest接口是继承自ServletRequest接口的。增加了和HTTP相关的碰空一些方法。
而所谓的request(在JSP中使用的)其实只是规范中的一个名称而已。笑尺瞎它当然是一个对象,但并不是SUN提供的,这是由各个不同的Servlet提供商编写的,SUN只是规定这个类要实现HttpServletRequest接口,并且困扮规定了各个方法的用途,但具体是什么类是由各个提供商自己决定的。
ServletResponse与HttpServletResponse的同上

❿ java使用HttpResponse请求其他系统的接口,对应Postman的设置

首先弄懂测试的需求,比如接口功能测试需求是什么(什么样的输入参数,返回什么样的输禅宴出)、接口性能测试需求是什么(最大支持多少并发访问,后台服务器资源配置极限是多少等等)
然后选择一款接口测试工具(一般推荐 POSTMAN JMETER等等),也可以自己开发接口工具。
编写接口功能测试和性能测试的用例(这个和一般的黑盒测试用例差不多,预置条件,测试步骤,预期结果)
使用测试工具或者脚本,执行测试用例。含提交BUG,跟踪BUG闭环等等。
分析测试结果,正清出具测试报告。
PS:接口的功能测举袭前试很简单,一般是访问的URL,带什么参数,然后什么加密方式,然后看返回值符不符合预期就可以了,把各种正常异常情况考虑到。接口性能测试的话除了要设置集合点并发访问后台接口,然后还要在后台服务器加监控,以便于检测系统资源,一般通用的监控指标CPU 内存 网络 等等。当然具体也要看你要测试什么样的接口,弄懂接口的协议再测试。希望能帮到你。

阅读全文

与javahttp接口开发相关的资料

热点内容
七星彩软件app怎么下载 浏览:213
32单片机的重映射哪里改 浏览:816
为什么前端不用刷算法题 浏览:706
对称加密系统和公钥加密系统 浏览:428
历史地理pdf 浏览:604
物联网云服务器框架 浏览:648
sybaseisql命令 浏览:183
android权威编程指南pdf 浏览:661
哪些软件属于加密软件 浏览:646
文件夹75丝什么意思 浏览:468
最便宜sop8单片机 浏览:964
图解周易预测学pdf 浏览:418
c盘莫名奇妙多了几个文件夹 浏览:169
贵州花溪门票优惠app哪个好 浏览:803
如何说话不会让人有被命令的感觉 浏览:438
哪里可下载湘工惠app 浏览:265
福特python 浏览:312
pdf转换成word表格 浏览:353
无线远端服务器无响应是什么意思 浏览:672
两位整数倒序输出python 浏览:783