gpt4 book ai didi

java - 从android中的API获取数据

转载 作者:行者123 更新时间:2023-12-01 23:10:17 25 4
gpt4 key购买 nike

enter image description here

我尝试从具有key的API获取数据。但在输出中它显示“找不到应用程序 key ”。

我已经在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);


}

最佳答案

我强烈建议您创建一个扩展 AsyncTask 的 Abstract 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;
}
}

关于java - 从android中的API获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58379740/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com