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