导航:首页 > 编程语言 > java封装http

java封装http

发布时间:2022-07-19 21:35:11

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如何创建一个简单的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(); }
打字不易,望采纳,谢谢

⑶ java http 包头的问题

如下

Content-Length:

response.setHeader("Content-Length","1024");

Content-Type:

response.setContentType("application/x-download;charset=UTF-8");

希望对你有用!

⑷ JAVA 怎么实现HTTP的POST方式通讯,以及HTTPS方式传递

如果有点通讯知识,就该知道这些只是socket通讯中的报文不同而已。通过socket通讯都能实现。现在java自身提供了封装好的的接口。apache也提供了httpclient.

⑸ 如何在java中发起http和https请求

1).第一个参数url需要写全地址,即前边的http必须写上,不能只写www.qq.com这样的。

2).第二个参数是请求方式,一般接口调用会给出URL和请求方式说明。

3).第三个参数是我们在发起请求的时候传递参数到所要请求的服务器,要传递的参数也要看接口文档确定格式,一般是封装成json或xml.

4).返回内容是String类,但是一般是有格式的json或者xml。

⑹ Java如何开发http接口

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

⑺ java 如何实现 http协议传输

Java 6 提供了一个轻量级的纯 Java Http 服务器的实现。下面是一个简单的例子:

public static void main(String[] args) throws Exception{
HttpServerProvider httpServerProvider = HttpServerProvider.provider();
InetSocketAddress addr = new InetSocketAddress(7778);
HttpServer httpServer = httpServerProvider.createHttpServer(addr, 1);
httpServer.createContext("/myapp/", new MyHttpHandler());
httpServer.setExecutor(null);
httpServer.start();
System.out.println("started");
}

static class MyHttpHandler implements HttpHandler{
public void handle(HttpExchange httpExchange) throws IOException {
String response = "Hello world!";
httpExchange.sendResponseHeaders(200, response.length());
OutputStream out = httpExchange.getResponseBody();
out.write(response.getBytes());
out.close();
}
}

然后,在浏览器中访问 http://localhost:7778/myapp/

⑻ JAVA里面的HTTP是什么

java本身不提供http功能。

http是一个应用层协议,底层用到了TCP。Java提供了TCP协议,但是没有http的实现。

但是,可以在网上找到开源的http client/server实现。例如apache-common-http之类的包。

⑼ 怎么用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);
}
}
阅读全文

与java封装http相关的资料

热点内容
如何让服务器运行缓慢 浏览:238
黑马程序员入学流程 浏览:448
win732位安装python什么版本 浏览:786
压缩方式标准 浏览:558
免费低吸指标源码 浏览:182
MO命令是 浏览:46
python入门常见错误 浏览:410
改加密包名 浏览:785
程序员在线编译器 浏览:247
山东兼职程序员收费标准 浏览:424
物业管理系统项目java源码 浏览:14
林皋pdf 浏览:586
vue编译后命名 浏览:731
可以发布命令的 浏览:954
安卓系统如何领取国旗 浏览:330
chromium编译linux 浏览:471
exe在线反编译工具 浏览:367
imbatest命令 浏览:410
android自动连接指定wifi 浏览:491
用纸做超简单又解压的东西 浏览:596