當前位置:首頁 » 編程語言 » 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