同學,你是否有經歷過等接口等到想打人的地步!不怕,用 Node.js 很快就能自己寫出接口,想怎樣測就怎樣測!
開發工具和環境配置,請谷歌度娘:
IDE:https://code.visualstudio.com/
node:https://nodejs.org/en/
win10 下 node 環境配置:nodejs zip壓縮版安裝與配置
PS:想想好像不一定要 IDE,直接用文本編輯器寫代碼,然後改成.js結尾,運行該文件就行(node xxx.js) ~
用 Node.js 寫測試接口,運行起來:
// 導入http模塊
var http = require("http");
// 創建 http server,並傳入回調函數,回調函數接收request和response對象
http.createServer(function (request, response) {
// 獲得http請求的method和url
console.log(request.method + ': ' + request.url);
// 定義了一個post變量,用於暫存請求體的信息,每當接收到請求體數據,累加到post中
var post = "";
request.on("data", function (chunk) {
post += chunk;
});
// 在end事件觸發後,通過querystring.parse將post解析爲真正的POST請求格式,然後向客戶端返回。
request.on("end", function () {
console.log("——————請求結束 post = " + post.toString() + "——————");
// 將http響應200寫入response, 同時設置Content-Type
response.writeHead(200, { "Content-Type": "text/plain;charset=utf8" });
response.write("{code:200,msg=\"請求成功\"}");
response.end();
});
}).listen(8888);// 讓服務器監聽8888端口
console.log("——————服務器啓動——————");
寫個 Android demo:
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView textView = (TextView) findViewById(R.id.tv);
textView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
textView.setText("開始請求");
new Thread(new Runnable() {
@Override
public void run() {
final String result = doPost("user_name=HaHa&submission_date=" + System.currentTimeMillis());
runOnUiThread(new Runnable() {
@Override
public void run() {
textView.setText(result);
}
});
}
}).start();
}
});
}
//post請求
public static String doPost(String json) {
try {
// 創建URL對象,設置請求url
URL url = new URL("http://xxx.xxx.xxx.xx:8888/test");// cmd:ipconfig
// 調用URL對象的openConnection( )來獲取HttpURLConnection對象實例
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 請求方法爲POST
conn.setRequestMethod("POST");
// 設置連接超時爲5秒
conn.setConnectTimeout(5000);
// 允許輸入輸出
conn.setDoInput(true);
conn.setDoOutput(true);
// 不能緩存
conn.setUseCaches(false);
// 至少要設置的兩個請求頭
// 設置頭部信息
conn.setRequestProperty("headerdata", "headerdata");
// 一定要設置 Content-Type 要不然服務端接收不到參數
conn.setRequestProperty("Content-Type", "application/Json; charset=UTF-8");
// 輸出流包含要發送的數據,要注意數據格式編碼
OutputStream op = conn.getOutputStream();
// 輸出流向服務器寫入數據
op.write(json.getBytes());
// 服務器返回東西了,先對響應碼判斷
String result = null;
if (conn.getResponseCode() == 200) {
// 用getInputStream()方法獲得服務器返回的輸入流
InputStream in = conn.getInputStream();
// 流轉換爲二進制數組,read()是轉換方法
byte[] data = new byte[1024];
in.read(data);
result = new String(data, "UTF-8");
in.close();
return result;
} else {
return String.valueOf(conn.getResponseCode());
}
} catch (Exception e) {
e.printStackTrace();
return e.getMessage();
}
}
}
過程中遇到的問題:
1、必須滴:
<uses-permission android:name="android.permission.INTERNET"/>
2、Android 高版本聯網失敗報錯:Cleartext HTTP traffic to xxx not permitted
《Android高版本聯網失敗報錯:Cleartext HTTP traffic to xxx not permitted解決方法》
<application
android:usesCleartextTraffic="true"
... ...>
... ...
</application>
3、java.net.SocketTimeoutException: failed to connect to /xxx.xxx.xx.xx (port xxx) after xxx
《java.net.SocketTimeoutException: failed to connect to /192.168.1.104 (port 80) after 10000ms》
移動端和開發電腦要在同個局域網,然後關閉防火牆
參考文章:
1、https://blog.csdn.net/gisuuser/article/details/77748779
2、https://www.cnblogs.com/gamedaybyday/p/6637933.html
3、https://www.liaoxuefeng.com/wiki/1022910821149312/1023025830950720
4、https://www.cnblogs.com/lazyli/p/10790101.html