導航:首頁 > 編程語言 > javahttp介面調用

javahttp介面調用

發布時間:2023-04-04 06:12:26

java如何調用對方http介面 新手虛心求教

importjava.io.BufferedReader;
importjava.io.DataOutputStream;
importjava.io.InputStreamReader;
importjava.net.HttpURLConnection;
importjava.net.URL;
importjava.net.URLEncoder;

publicclassDemoTest1{

publicstaticfinalStringGET_URL="http://112.4.27.9/mall-back/if_user/store_list?storeId=32";
//publicstaticfinalStringPOST_URL="http://112.4.27.9/mall-back/if_user/store_list";
//妙兜測試介面
publicstaticfinalStringPOST_URL="http://121.40.204.191:8180/mdserver/service/installLock";

/**
*介面調用GET
*/
(){
try{
URLurl=newURL(GET_URL);//把字元串轉換為URL請求地址
HttpURLConnectionconnection=(HttpURLConnection)url.openConnection();//打開連接
connection.connect();//連接會話
//獲取輸入流
BufferedReaderbr=newBufferedReader(newInputStreamReader(connection.getInputStream(),"UTF-8"));
Stringline;
StringBuildersb=newStringBuilder();
while((line=br.readLine())!=null){//循環讀取流
sb.append(line);
}
br.close();//關閉流
connection.disconnect();//斷開連接
System.out.println(sb.toString());
}catch(Exceptione){
e.printStackTrace();
System.out.println("失敗!");
}
}

/**
*介面調用POST
*/
(){
try{
URLurl=newURL(POST_URL);

//將url以open方法返回的urlConnection連接強轉為HttpURLConnection連接(標識一個url所引用的遠程對象連接)
HttpURLConnectionconnection=(HttpURLConnection)url.openConnection();//此時cnnection只是為一個連接對象,待連接中

//設置連接輸出流為true,默認false(post請求是以流的方式隱式的傳遞參數)
connection.setDoOutput(true);

//設置連接輸入流為true
connection.setDoInput(true);

//設置請求方式為post
connection.setRequestMethod("POST");

//post請求緩存設為false
connection.setUseCaches(false);

//設置該HttpURLConnection實例是否自動執行重定向
connection.setInstanceFollowRedirects(true);

//設置請求頭裡面的各個屬性(以下為設置內容的類型,設置為經過urlEncoded編碼過的from參數)
//application/x-javascripttext/xml->xml數據application/x-javascript->json對象application/x-www-form-urlencoded->表單數據
//;charset=utf-8必須要,不然妙兜那邊會出現亂碼【★★★★★】
connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded;charset=utf-8");

//建立連接(請求未開始,直到connection.getInputStream()方法調用時才發起,以上各個參數設置需在此方法之前進行)
connection.connect();

//創建輸入輸出流,用於往連接裡面輸出攜帶的參數,(輸出內容為?後面的內容)
DataOutputStreamdataout=newDataOutputStream(connection.getOutputStream());

Stringapp_key="app_key="+URLEncoder.encode("","utf-8");//已修改【改為錯誤數據,以免信息泄露】
Stringagt_num="&agt_num="+URLEncoder.encode("10111","utf-8");//已修改【改為錯誤數據,以免信息泄露】
Stringpid="&pid="+URLEncoder.encode("BLZXA150401111","utf-8");//已修改【改為錯誤數據,以免信息泄露】
Stringdepartid="&departid="+URLEncoder.encode("10007111","utf-8");//已修改【改為錯誤數據,以免信息泄露】
Stringinstall_lock_name="&install_lock_name="+URLEncoder.encode("南天大門","utf-8");
Stringinstall_address="&install_address="+URLEncoder.encode("北京育新","utf-8");
Stringinstall_gps="&install_gps="+URLEncoder.encode("116.350888,40.011001","utf-8");
Stringinstall_work="&install_work="+URLEncoder.encode("小李","utf-8");
Stringinstall_telete="&install_telete="+URLEncoder.encode("13000000000","utf-8");
Stringintall_comm="&intall_comm="+URLEncoder.encode("一切正常","utf-8");

//格式parm=aaa=111&bbb=222&ccc=333&ddd=444
Stringparm=app_key+agt_num+pid+departid+install_lock_name+install_address+install_gps+install_work+install_telete+intall_comm;

//將參數輸出到連接
dataout.writeBytes(parm);

//輸出完成後刷新並關閉流
dataout.flush();
dataout.close();//重要且易忽略步驟(關閉流,切記!)

//System.out.println(connection.getResponseCode());

//連接發起請求,處理伺服器響應(從連接獲取到輸入流並包裝為bufferedReader)
BufferedReaderbf=newBufferedReader(newInputStreamReader(connection.getInputStream(),"UTF-8"));
Stringline;
StringBuildersb=newStringBuilder();//用來存儲響應數據

//循環讀取流,若不到結尾處
while((line=bf.readLine())!=null){
//sb.append(bf.readLine());
sb.append(line).append(System.getProperty("line.separator"));
}
bf.close();//重要且易忽略步驟(關閉流,切記!)
connection.disconnect();//銷毀連接
System.out.println(sb.toString());

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

publicstaticvoidmain(String[]args){
//httpURLConectionGET();
httpURLConnectionPOST();
}
}

㈡ java調用基於http+post+xml介面

1、直接用servlet就可以了,request.getInputStream(),然後解析xml,然後你的業務操作,組裝XML,response.getOutputStream()寫出去就OK了。
但這個性能低,而且還要依賴web容器。
2、socket實現http協議,把HTTP協議好好看看,自己解析(其實就是字元串的操作哦)。
3、你要是只做客戶端的話可以用httpClient,幾行代碼搞定了

㈢ 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如何使用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介面

方法:祥侍只要New一個Map,然後把要傳遞的參數以鍵值畢宴肆手轎對的形式存入Map即可。
private void Example() {
String url =地址;
Map<String, String> param = new HashMap<String, String>();
p.put("ParamName", "ParamValue");
String html = this.visitURL(url, param);
}

㈥ 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

㈦ JAVA怎麼調用介面

String sendPost(String jsonStr, String path)x0dx0a throws IOException {x0dx0a byte[] data = jsonStr.getBytes();x0dx0a java.net.URL url = new java.net.URL(path);x0dx0a java.net.HttpURLConnection conn = x0dx0a (java.net.HttpURLConnection) url.openConnection();x0dx0a conn.setRequestMethod("POST");x0dx0a conn.setConnectTimeout(5 * 1000);// 設置連接超時時間為5秒 x0dx0a conn.setReadTimeout(20 * 1000);// 設置讀取超時時間為20秒 x0dx0a // 使用 URL 連接進行輸出,則將 DoOutput標志設置為 truex0dx0a conn.setDoOutput(true);x0dx0a x0dx0a conn.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");x0dx0a //conn.setRequestProperty("Content-Encoding","gzip");x0dx0a conn.setRequestProperty("Content-Length", String.valueOf(data.length));x0dx0a OutputStream outStream = conn.getOutputStream();// 返回寫入到此連接的輸出流x0dx0a outStream.write(data);x0dx0a outStream.close();//關閉流x0dx0a String msg = "";// 保存調用http服務後的響應信息x0dx0a // 如果請求響應頌旅碼是200,則表示成功x0dx0a if (conn.getResponseCode() == 200) {x0dx0a // HTTP服務端返回的編碼坦櫻陪是UTF-8,故必須設置為UTF-8,保持編碼統一,否則會出現中文亂碼x0dx0a BufferedReader in = new BufferedReader(new InputStreamReader(x0dx0a (InputStream) conn.getInputStream(), "UTF-8"));x0dx0a msg = in.readLine();x0dx0a in.close();x0dx0a }x0dx0a conn.disconnect();// 斷開連接讓蠢x0dx0a return msg;x0dx0a }

㈧ 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介面報錯,java.net.ConnectException: Connection refused: connect

能成功首先排除防火牆或埠開發問題;
其次確定你連接的埠是否有最大連接數限制(類似mysql有最大連接線程數);
還有就是對應服務的拒絕策略是啥,默認丟棄

閱讀全文

與javahttp介面調用相關的資料

熱點內容
php論壇實訓報告 瀏覽:403
java日期字元串轉換成日期 瀏覽:135
linuxsftp連接 瀏覽:934
光伏日發電量演算法 瀏覽:125
小肚皮app怎麼才有vip 瀏覽:616
php全形轉換半形 瀏覽:927
java字元序列 瀏覽:539
杭州編譯分布式存儲區塊鏈 瀏覽:575
材料壓縮曲線 瀏覽:247
linux命令排序 瀏覽:151
手機熱點加密為啥連接不上電腦 瀏覽:979
編譯器合並計算 瀏覽:959
android音頻曲線 瀏覽:343
linuxftp自動登錄 瀏覽:802
運行編譯後網頁 瀏覽:70
閱讀app怎麼使用 瀏覽:319
centos防火牆命令 瀏覽:432
命令行變更 瀏覽:332
linux設備和驅動 瀏覽:207
加密貨幣騙局破案 瀏覽:345