在Android中,使用NanoHTTPD庫實現POST請求需要遵循以下步驟:
在你的Android項目的build.gradle
文件中添加NanoHTTPD庫的依賴:
dependencies {
implementation 'org.nanohttpd:nanohttpd:2.4.6'
}
在你的代碼中創建一個繼承自NanoHTTPD
的類,并重寫onCreate()
和handle()
方法。
import org.nanohttpd. NanoHTTPD;
import org.nanohttpd.server.Server;
public class MyNanoHTTPD extends NanoHTTPD {
public MyNanoHTTPD(int port) {
super(port);
}
@Override
public Response onCreate() {
return new Response("Hello World");
}
@Override
public Response handle(String uri, Method method, Map<String, String> headers, Map<String, String> parameters, byte[] body) {
if (method == Method.POST) {
// 處理POST請求
return handlePostRequest(uri, headers, parameters, body);
} else {
// 處理其他請求
return new Response("Method Not Allowed");
}
}
private Response handlePostRequest(String uri, Map<String, String> headers, Map<String, String> parameters, byte[] body) {
// 在這里處理POST請求,例如獲取參數、保存數據等
// 返回響應
return new Response("POST request received");
}
}
在你的Activity或其他適當的位置創建MyNanoHTTPD
實例并啟動服務器。
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int port = 8080;
MyNanoHTTPD server = new MyNanoHTTPD(port);
server.start();
}
}
你可以使用Android的HttpURLConnection
或者第三方庫(如OkHttp
)來發送POST請求到你的NanoHTTPD服務器。以下是一個使用HttpURLConnection
的示例:
private void sendPostRequest() {
new Thread(new Runnable() {
@Override
public void run() {
try {
URL url = new URL("http://localhost:8080/your-uri");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
String params = "key1=value1&key2=value2";
connection.setFixedLengthStreamingMode(params.getBytes().length);
DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(params);
outputStream.flush();
outputStream.close();
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// 處理響應
} else {
// 處理錯誤
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
現在,當你運行你的Android應用并發送POST請求到NanoHTTPD服務器時,服務器應該能夠正確處理并返回響應。