代碼如下:
岳麓網(wǎng)站制作公司哪家好,找創(chuàng)新互聯(lián)!從網(wǎng)頁設(shè)計、網(wǎng)站建設(shè)、微信開發(fā)、APP開發(fā)、成都響應(yīng)式網(wǎng)站建設(shè)等網(wǎng)站項目制作,到程序開發(fā),運營維護。創(chuàng)新互聯(lián)成立與2013年到現(xiàn)在10年的時間,我們擁有了豐富的建站經(jīng)驗和運維經(jīng)驗,來保證我們的工作的順利進行。專注于網(wǎng)站建設(shè)就選創(chuàng)新互聯(lián)。
import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import net.sf.json.JSONObject; public class InterfaceRequest { //模擬向騰訊云發(fā)送接口 //接口 private final static String URL = "https://console.tim.qq.com/v4/im_open_login_svc/account_import?"; /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { // TODO Auto-generated method stub //連接服務(wù)器 HttpURLConnection connection = connection(URL); DataOutputStream out = new DataOutputStream( connection.getOutputStream()); JSONObject obj = new JSONObject(); obj.element("Identifier", "hehe"); System.out.println(obj.toString()); // 向騰訊請求傳入編碼為UTF-8格式的json數(shù)據(jù) out.write(obj.toString().getBytes("UTF-8")); out.flush(); out.close(); //獲得服務(wù)器返回的結(jié)果 BufferedReader reader = new BufferedReader(new InputStreamReader( connection.getInputStream())); String lines; StringBuffer sb = new StringBuffer(""); while ((lines = reader.readLine()) != null) { lines = new String(lines.getBytes(), "utf-8"); sb.append(lines); } reader.close(); } public static HttpURLConnection connection(String URL ) throws IOException { URL url = new URL(URL); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("POST"); connection.setUseCaches(false); connection.setInstanceFollowRedirects(true); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); connection.connect(); return connection; // TODO Auto-generated method stub } }
以上這篇java以json格式向后臺服務(wù)器接口發(fā)送請求的實例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持創(chuàng)新互聯(lián)。