You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android开发:WebView中如何将二维码URI关联到HTTP请求?

Hey there! As someone who’s fumbled through early Android dev hurdles, I totally get how it feels to connect working features into a cohesive flow. Let’s walk through exactly how to attach that scanned QR code URI to your API requests—we’ll cover both native Android requests and requests from the web content in your WebView, since both are common in WebApps.


1. If you’re making the API request from native Android code (e.g., OkHttp/Retrofit)

First, let’s assume you already have the scanned URI stored in a string, like String scannedQrUri = "the_uri_you_got_from_qr_scanner". Here’s how to plug it into your request:

Using OkHttp (simple HTTP client)

// Initialize OkHttpClient (you can reuse this instance across requests)
OkHttpClient client = new OkHttpClient();

// Build your API URL with the QR URI as a query parameter (adjust based on your API's requirements)
HttpUrl apiUrl = HttpUrl.parse("https://your-api-domain.com/your-endpoint")
        .newBuilder()
        .addQueryParameter("qr_uri", scannedQrUri) // Attach URI as a URL parameter
        .build();

// Create the request
Request request = new Request.Builder()
        .url(apiUrl)
        .build();

// Execute the request (MUST run on a background thread—never the main thread!)
client.newCall(request).enqueue(new Callback() {
    @Override
    public void onFailure(Call call, IOException e) {
        // Handle request failures (e.g., no internet, server error)
        e.printStackTrace();
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        if (response.isSuccessful()) {
            String responseData = response.body().string();
            // Process the successful API response here
        } else {
            // Handle non-200 status codes
        }
    }
});

Using Retrofit (type-safe client for APIs)

First, define your API interface:

public interface YourApiService {
    // Adjust the HTTP method and parameter based on your API's specs
    @GET("your-endpoint")
    Call<YourResponseModel> sendQrUri(@Query("qr_uri") String scannedQrUri);
}

Then call the API:

// Set up Retrofit
Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("https://your-api-domain.com/")
        .addConverterFactory(GsonConverterFactory.create()) // For JSON parsing
        .build();

YourApiService apiService = retrofit.create(YourApiService.class);

// Execute the request
Call<YourResponseModel> call = apiService.sendQrUri(scannedQrUri);
call.enqueue(new Callback<YourResponseModel>() {
    @Override
    public void onResponse(Call<YourResponseModel> call, Response<YourResponseModel> response) {
        if (response.isSuccessful()) {
            YourResponseModel data = response.body();
            // Use the parsed response data
        }
    }

    @Override
    public void onFailure(Call<YourResponseModel> call, Throwable t) {
        t.printStackTrace();
    }
});

2. If you’re making the API request from the web content in your WebView

You’ll need to pass the scanned URI from native Android code to the JavaScript environment in your WebView, then let the frontend handle the API call.

Step 1: Enable JavaScript in your WebView

WebSettings webSettings = yourWebView.getSettings();
webSettings.setJavaScriptEnabled(true);

Step 2: Pass the scanned URI to the frontend JS

Once you have the QR URI, use evaluateJavascript() to send it to the web content:

String scannedQrUri = "the_uri_you_got_from_qr_scanner";
// Call a JavaScript function in your web app to receive the URI
yourWebView.evaluateJavascript("window.processScannedQr('" + scannedQrUri + "')", new ValueCallback<String>() {
    @Override
    public void onReceiveValue(String value) {
        // Optional: Handle any response from the JS function
    }
});

Step 3: Handle the URI in your frontend code

In your web app’s JavaScript, define the function to receive the URI and attach it to the API request:

function processScannedQr(qrUri) {
    // Encode the URI to handle special characters (critical for valid URLs!)
    const encodedUri = encodeURIComponent(qrUri);
    
    // Make the API request with the URI
    fetch(`https://your-api-domain.com/your-endpoint?qr_uri=${encodedUri}`)
        .then(response => response.json())
        .then(data => {
            // Process the API response in your web app
        })
        .catch(error => {
            console.error("API request failed:", error);
        });
}

Quick Extra Tips

  • Permissions: Don’t forget to add internet access to your AndroidManifest.xml:
    <uses-permission android:name="android.permission.INTERNET" />
    
  • URI Validation: Before sending the URI to the API, do a quick check to ensure it’s a valid format (e.g., using Uri.parse(scannedQrUri) != null) to avoid sending garbage data.
  • Thread Safety: If your QR scanner runs on a background thread, use a Handler or LiveData to safely pass the URI to the thread handling the API request (prevents race conditions).

内容的提问来源于stack exchange,提问作者César Hurtaud

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 11:02:29