❶ 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 內存 網路 等等。當然具體也要看你要測試什麼樣的介面,弄懂介面的協議再測試。希望能幫到你。