当前位置:首页 » 编程语言 » javahttp接口

javahttp接口

发布时间: 2022-10-03 06:52:39

1. 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.

}

}
}

2. java 开发HTTP接口

response.write("<?xml version=\"1.0\" encoding=\"utf-8\"?><root><proct><fruit name=\"orange\" /></proct></root>");这是最基本的实现.

3. 求助,Java中如何根据一个http接口

public void test(Long clusterId,boolean monitorSendAllFlag) {
boolean result=false;
try {
String url ="http://www.xxx.com/xxx/xxx.action";
String json= HttpConfigUtil.getHttpResponse(url);
System.out.println(json);

} catch (Exception e) {
e.printStackTrace();
}

}

public static String getHttpResponse(String allConfigUrl) {
BufferedReader in = null;
StringBuffer result = null;
try {

URI uri = new URI(allConfigUrl);
URL url = uri.toURL();
URLConnection connection = url.openConnection();
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Charset", "utf-8");

connection.connect();

result = new StringBuffer();
//读取URL的响应
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result.append(line);
}

return result.toString();

} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}

return null;

}

4. java http调用接口书写

rest接口的话可以使用

RestTemplate

Stringuri="http://example.com/hotels/1/bookings";

PostMethodpost=newPostMethod(uri);
Stringrequest=//createbookingrequestcontent
post.setRequestEntity(newStringRequestEntity(request));

httpClient.executeMethod(post);

if(HttpStatus.SC_CREATED==post.getStatusCode()){
Headerlocation=post.getRequestHeader("Location");
if(location!=null){
System.out.println("Creatednewbookingat:"+location.getValue());
}
}

api文档参考http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/remoting.html#rest-client-access

5. java课程培训机构分享什么是Java接口

Java接口(英文:Interface),在JAVA编程语言中是一个抽象类型,是抽象方法的集合,接口通常以interface来声明。一个类通过继承接口的方式,从而来继承接口的抽象方法,以下是java课程培训机构http://www.kmbdqn.com/为大家搜索整理的Java接口是什么,希望能给大家带来帮助,更多专业知识请及时关注海文IT知识频道!



接口并不是类,编写接口的方式和类很相似,但是它们属于不同的概念。类描述对象的属性和方法。接口则包含类要实现的方法。


除非实现接口的类是抽象类,否则该类要定义接口中的所有方法。


接口无法被实例化,但是可以被实现。一个实现接口的类,必须实现接口内所描述的所有方法,否则就必须声明为抽象类。另外,在Java中,接口类型可用来声明一个变量,他们可以成为一个空指针,或是被绑定在一个以此接口实现的对象。


接口与类相似点:


一个接口可以有多个方法。


接口文件保存在.java结尾的文件中,文件名使用接口名。


接口的字节码文件保存在.class结尾的文件中。


接口相应的字节码文件必须在与包名称相匹配的目录结构中。


接口与类的区别:


接口不能用于实例化对象。


接口没有构造方法。


接口中所有的方法必须是抽象方法。


接口不能包含成员变量,除了static和final变量。


接口不是被类继承了,而是要被类实现。


接口支持多重继承。


6. 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");
}

7. 怎么用java写一个http接口

一个servlet接口就可以了啊:

HTTP Header 请求实例

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

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

//导入必需的java库
importjava.io.IOException;
importjava.io.PrintWriter;
importjava.util.Enumeration;

importjavax.servlet.ServletException;
importjavax.servlet.annotation.WebServlet;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;

@WebServlet("/DisplayHeader")

//扩展HttpServlet类
{

//处理GET方法请求的方法
publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException
{
//设置响应内容类型
response.setContentType("text/html;charset=UTF-8");

PrintWriterout=response.getWriter();
Stringtitle="HTTPHeader请求实例-菜鸟教程实例";
StringdocType=
"<!DOCTYPEhtml> ";
out.println(docType+
"<html> "+
"<head><metacharset="utf-8"><title>"+title+"</title></head> "+
"<bodybgcolor="#f0f0f0"> "+
"<h1align="center">"+title+"</h1> "+
"<tablewidth="100%"border="1"align="center"> "+
"<trbgcolor="#949494"> "+
"<th>Header名称</th><th>Header值</th> "+
"</tr> ");

EnumerationheaderNames=request.getHeaderNames();

while(headerNames.hasMoreElements()){
StringparamName=(String)headerNames.nextElement();
out.print("<tr><td>"+paramName+"</td> ");
StringparamValue=request.getHeader(paramName);
out.println("<td>"+paramValue+"</td></tr> ");
}
out.println("</table> </body></html>");
}
//处理POST方法请求的方法
publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{
doGet(request,response);
}
}

8. Java如何开发http接口

有时间去看看servlet的源码····

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

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

10. 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(); }
打字不易,望采纳,谢谢

热点内容
安卓上哪里下大型游戏 发布:2024-12-23 15:10:58 浏览:189
明日之后目前适用于什么配置 发布:2024-12-23 14:56:09 浏览:56
php全角半角 发布:2024-12-23 14:55:17 浏览:829
手机上传助手 发布:2024-12-23 14:55:14 浏览:733
什么样的主机配置吃鸡开全效 发布:2024-12-23 14:55:13 浏览:830
安卓我的世界114版本有什么 发布:2024-12-23 14:42:17 浏览:711
vbox源码 发布:2024-12-23 14:41:32 浏览:279
诗经是怎么存储 发布:2024-12-23 14:41:29 浏览:661
屏蔽视频广告脚本 发布:2024-12-23 14:41:24 浏览:420
php解析pdf 发布:2024-12-23 14:40:01 浏览:820