首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android 客戶端與 Java 服務端數據交互:基於 HTTP 協議的 RESTful API 設計

     編輯:程式設計綜合問答

架構圖

Android App (Retrofit/OkHttp) 
    │  HTTP/JSON
    ▼
Nginx (反向代理、SSL終止)
    │
    ▼
Spring Boot / Servlet (Controller → Service → Repository)
    │  JDBC / JPA
    ▼
MySQL / PostgreSQL

Android 端關鍵代碼

// Retrofit 接口
public interface ApiService {
    @POST("order/grab")
    Call> grabOrder(@Body GrabRequest request);
}

// 調用
Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://api.example.com/")
    .addConverterFactory(GsonConverterFactory.create())
    .build();
ApiService api = retrofit.create(ApiService.class);
api.grabOrder(new GrabRequest(orderId)).enqueue(new Callback>() {
    @Override public void onResponse(Call> call, Response> resp) {
        if (resp.isSuccessful() && resp.body().isSuccess()) {
            showBuyerInfo(resp.body().getData().getBuyer());
        }
    }
    @Override public void onFailure(Call> call, Throwable t) { ... }
});

服務端關鍵代碼

@RestController
@RequestMapping("/order")
public class OrderController {
    @PostMapping("/grab")
    public BaseResponse grab(@RequestBody GrabRequest req) {
        Order order = orderService.grab(req.getOrderId(), getCurrentUserId());
        return BaseResponse.success(order);
    }
}

優勢

  • 跨語言、跨平台、防火牆友好。
  • 成熟生態:Retrofit/OkHttp、Spring Boot、Swagger 文檔自動生成。
  • 支持 HTTPS、OAuth2/JWT 鑒權、限流、熔斷等企業級特性。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved