簡體   English   中英

從 android 中的 API 獲取數據

[英]Data fetching from an API in android

在此處輸入圖像描述

我試圖從具有key的 API 中獲取數據。 但是在 output 中,它說"app key not found"

我已經在 Postman 上對其進行了測試,並且可以正常工作。

這是我的代碼:

public class fetchData extends AsyncTask<Void,Void,Void> {
    String data="";
    @Override
    protected Void doInBackground(Void... voids) {

        try {
            URL url=new URL("https://app.inyek.com/app_api/api_extra/all_order.php?");

            HttpURLConnection con=(HttpURLConnection) url.openConnection();
            con.setRequestMethod("POST");
            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded/json;charset=UTF-8");
            con.setRequestProperty("app_key","whatever");
            con.setDoOutput(true);


}

在PostMan中,app key是怎么指定的? 是通過 HTTP header 嗎? (對不起,我會添加評論,但我沒有足夠的聲譽)

還是將其指定為 GET 參數? 在后一種情況下,請嘗試以下操作:

URL url=new URL("https://app.inyek.com/app_api/api_extra/all_order.php?app_key=YOUR_KEY");

歡迎來到 Stack Exchange,首先我建議您不要將 API 密鑰放在問題和/或圖像中。 因為它們可能很敏感並且可能被惡意用戶濫用。 隨意編輯您的問題並將其刪除。

要回答您的查詢,我認為您需要以 json 格式將內容寫入 http 請求正文。 這可以按照以下網頁上的指南完成: https://www.baeldung.com/httpurlconnection-post

綜上,需要創建一個output stream,直接將內容寫入其中。

我強烈建議您制作一個擴展 AsyncTask 的抽象 HttpRequestTask。 在這個抽象的祖先中,您可以創建一些輔助方法來讀取您的輸入,如下所示:

/**
 * HttpRequestTask is an abstract extension of an AsyncTask for HTTP Requests.
 *
 * @param <P>
 *      Type for parameter(s) to doInBackground (can be Void if none provided)
 * @param <R>
 *      Type for result of request (can be Void if ignored, or using listeners.)
 */
public abstract class HttpRequestTask<P, R> extends AsyncTask<P, Integer, R>
{
    private static final String TAG = "HttpRequestTask";

    // Post form encoded requests, get back JSON response
    private static final RequestMethod DEFAULT_REQUEST_METHOD = RequestMethod.POST;
    private static final String DEFAULT_CONTENT_TYPE = "application/x-www-form-urlencoded;charset=UTF-8;";
    private static final String DEFAULT_ACCEPT = "application/json;";
    private static final int DEFAULT_TIMEOUT = 8000; // 8 seconds
    private static final String CHARSET = "UTF-8";

    protected static final String NULL_CONTEXT = "Context is null.";
    protected static final String INVALID_RESPONSE = "The server did not send back a valid response.";

    // Request methods supported by back-end
    protected enum RequestMethod
    {
        GET("GET"),
        POST("POST");

        private final String method;

        RequestMethod(String method)
        {
            this.method = method;
        }

        @Override
        public String toString()
        {
            return this.method;
        }
    }

    /**
     * ALWAYS use application context here to prevent memory leaks.
     *
     */
    protected HttpRequestTask(@NonNull final Context context)
    {
        this.context = context;
    }

    protected void verifyConnection() throws IOException
    {
        if (!SystemUtil.isInternetAvailable(context))
        {
            throw new IOException("Internet is unavailable.");
        }
    }

    /**
     * Creates and opens a URLConnection for the url parameter, as well as setting request options.
     *
     * @param url
     *      to connect to.
     *
     * @return opened HTTPURLConnection for POSTing data to ctservices.
     */
    protected HttpURLConnection getURLConnection(URL url) throws IOException
    {
        return this.getURLConnection(url, DEFAULT_REQUEST_METHOD, DEFAULT_CONTENT_TYPE,
                DEFAULT_ACCEPT, DEFAULT_TIMEOUT);
    }

    /**
     * Creates and opens a URLConnection for the url parameter, as well as setting request options.
     *
     * @param url
     *      to connect to.
     *
     * @return opened HTTPURLConnection
     */
    protected HttpURLConnection getURLConnection(@NonNull final URL url,
                                                                                             @NonNull final RequestMethod requestMethod,
                                                                                             @NonNull final String contentType,
                                                                                             @Nullable final String accept, final int timeout)
            throws IOException
    {
        verifyConnection();

        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod(requestMethod.toString());
        urlConnection.setRequestProperty("Content-Type", contentType);

        if (accept != null && !accept.isEmpty())
        {
            urlConnection.setRequestProperty("Accept", accept);
        }

        urlConnection.setReadTimeout(timeout);
        urlConnection.setConnectTimeout(timeout);
        urlConnection.setUseCaches(false);
        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(true);
        return urlConnection;
    }

    /**
     * Creates and opens a URLConnection for the url parameter, but does not set any request options.
     *
     * @param url
     *      to connect to.
     *
     * @return opened HTTPURLConnection without parameters set.
     */
    protected HttpURLConnection getBasicURLConnection(URL url) throws IOException
    {
        if (!SystemUtil.isInternetAvailable(applicationContext.get()))
        {
            throw new IOException("Internet is unavailable.");
        }

        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        return urlConnection;
    }

    /**
     * Write a JSONObject of request parameters to the output stream as form-encoded data.
     *
     * @param urlConnection
     *      opened urlConnection with output enabled (done by getURLConnection).
     * @param params
     *      to write to request.
     *
     * @throws IOException
     *      problem writing to output stream
     */
    protected void writeParams(HttpURLConnection urlConnection, JSONObject params) throws IOException
    {
        OutputStream outputStream = urlConnection.getOutputStream();
        BufferedWriter outWriter = new BufferedWriter(new OutputStreamWriter(outputStream,
                StandardCharsets.UTF_8));

        String urlParams = this.encodeJSONObject(params);

        outWriter.write(urlParams);
        outWriter.flush();
        outWriter.close();
        outputStream.close();
    }

    /**
     * Reads the response of a URLConnection from the input stream and puts it in a string.
     *
     * @param urlConnection
     *      opened urlConnection with input enabled (done by getURLConnection).
     *
     * @return response string
     *
     * @throws IOException
     *      problem reading input stream
     */
    protected String readResponse(HttpURLConnection urlConnection) throws IOException
    {
        InputStream inputStream = null;

        try
        {
            /* If we failed to connect will throw a SocketResponseTimeoutException,
             * which is an IOException. */
            int responseCode = urlConnection.getResponseCode();

            if (HttpURLConnection.HTTP_OK != responseCode)
            {
                throw new IOException("Bad response code - " + responseCode);
            }

            inputStream = urlConnection.getInputStream();
            final String response = parseInputStream(inputStream);
            urlConnection.disconnect();
            return response;
        }
        finally
        {
            if (inputStream != null)
            {
                try
                {
                    inputStream.close();
                }
                catch (Exception e) {}
            }
        }
    }

    protected Context getContext()
    {
        return this.context;
    }

    protected String getString(final int resId)
    {
        return getContext().getString(resId);
    }

    /**
     * Encodes a JSONObject as a form-data URL string.
     *
     * @param jo
     *      to encode
     *
     * @return encoded URL string
     */
    private String encodeJSONObject(JSONObject jo)
    {
        StringBuilder sb = new StringBuilder();
        boolean first = true;
        Iterator<String> itr = jo.keys();
        String key;
        Object val;

        try
        {
            while (itr.hasNext())
            {
                key = itr.next();
                val = jo.get(key);

                if (first)
                {
                    first = false;
                }
                else
                {
                    sb.append('&');
                }

                sb.append(URLEncoder.encode(key, CHARSET));
                sb.append('=');
                sb.append(URLEncoder.encode(val.toString(), CHARSET));
            }
        }
        catch (JSONException | UnsupportedEncodingException e) {}

        return sb.toString();
    }

    private String parseInputStream(InputStream is) throws IOException
    {
        BufferedReader br = null;

        try
        {
            br = new BufferedReader(new InputStreamReader(is));
            StringBuilder sb = new StringBuilder();
            String line;

            while ((line = br.readLine()) != null)
            {
                sb.append(line);
            }

            return sb.toString();
        }
        finally
        {
            if (br != null)
            {
                try
                {
                    br.close();
                }
                catch (Exception e) {}
            }
        }
    }

    /**
     * Merges any properties of b into a that don't already have a key match in a.
     *
     * @param a
     *      merging to
     * @param b
     *      merging from
     *
     * @return a with any unique values from b
     */
    protected JSONObject mergeJSONObjects(JSONObject a, JSONObject b)
    {
        if (b == null)
        {
            return a;
        }
        if (a == null)
        {
            return b;
        }

        try
        {
            Iterator<String> bItr = b.keys();
            String key;
            while (bItr.hasNext())
            {
                key = bItr.next();
                if (!a.has(key))
                {
                    a.put(key, b.get(key));
                }
            }

            return a;
        }
        catch (Exception ex)
        {
            Log.e(TAG, ex.getClass().getSimpleName() + " in mergeJSONObjects: " + ex.getMessage() +
                    '\n' + Log.getStackTraceString(ex));
            return a;
        }
    }
}

然后您可以擴展您的 HttpRequestTask 以輕松發出網絡請求:

public class ExampleNetworkTask extends HttpRequestTask<Void, Void>
{
    private static final String TAG = "ExampleNetworkTask";

    private final SimpleListener successListener;
    private final StringListener errorListener;
    private final String servicesUrl;

    public static void start(@NonNull final Context context,
                             @Nullable final SimpleListener successListener,
                             @Nullable final StringListener errorListener)
        throws IllegalArgumentException
    {
        if (context == null)
        {
            throw new IllegalArgumentException(NULL_CONTEXT);
        }

        new ExampleNetworkTask(context, successListener, errorListener).execute();
    }

    private ExampleNetworkTask(@NonNull final Context context,
                               @Nullable final SimpleListener successListener,
                               @Nullable final StringListener errorListener)
    {
        super(context);

        this.servicesUrl = SystemUtil.getServiceUrl(getContext(), R.string.example_service);
        this.successListener = successListener;
        this.errorListener = errorListener;
    }

    @Override
    protected Void doInBackground(Void... voids)
    {
        try
        {
            final HttpURLConnection urlConnection = super.getURLConnection(new URL(servicesUrl));

            final JSONObject params = new JSONObject();

            // Add params
            params.put("app_key", appKey);
            params.put("order_number", orderNumber);
            // ...

            // Send request, read parse response
            super.writeParams(urlConnection, params);
            final String response = super.readResponse(urlConnection);
            final JSONObject responseObj = new JSONObject(response);

            // Handle response
        }
        catch (Exception ex)
        {
            final String msg = ex.getLocalizedMessage();
            Log.e(TAG, ex.getClass().getSimpleName() + ": " + msg  + '\n' +
                    Log.getStackTraceString(ex));

            // Handle network exceptions and other exceptions here.
        }
        return null;
    }
}

感謝你們。 最后我使用 OkHttpClient 得到了答案:這是代碼:

 OkHttpClient client = new OkHttpClient();

            MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
            RequestBody body = RequestBody.create(mediaType, "app_key=whatever");
            Request request = new Request.Builder()
                    .url("https://app.inyek.com/app_api/api_extra/all_order.php")
                    .post(body)
                    .addHeader("Content-Type", "application/x-www-form-urlencoded")
                    .addHeader("key", "whatever")
                    .addHeader("cache-control", "no-cache")
                    .addHeader("Postman-Token", "whatever")
                    .build();

            Response response = client.newCall(request).execute();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM