gpt4 book ai didi

android - 弃用的方法,我如何用新的方法替换它

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:43:14 27 4
gpt4 key购买 nike

我对一些已弃用的方法有疑问,尤其是我在此处发布的方法。

我想要的很简单:使用 http post 将数据发送到服务器 ---> 使用我从客户端收到的数据进行查询 --> 发送回复

我正在尝试使用 API 6.0 开发 Android 应用程序,但我的所有方法都已弃用,我必须更改哪些内容才能将我的代码转换为新的?

public class ReadServer extends Activity {
String result;
public String readserver(String id_data, String data){
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("myurl/queryMobile.php");
StringBuilder builder = new StringBuilder();
String json = "";
//Build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate(id_data, data);
//Convert JSONObject to JSON to String
json = jsonObject.toString();

//Set json to StringEntity
StringEntity se = new StringEntity(json);
//Set httpPost Entity
httpPost.setEntity(se);
//Set some headers to inform server about the type of the content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");

//Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
//Receive response as inputStream
StatusLine statusLine = httpResponse.getStatusLine();
int statusCode = statusLine.getStatusCode();
//Convert input stream to string
AlertDialog.Builder alertDialog;

switch(statusCode){
case 200:
HttpEntity entity = httpResponse.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line="";
try{
while ((line = reader.readLine()) != null) {
builder.append(line);
result = builder.toString();
}
}catch(Exception e){
alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("400 Bad Request");
alertDialog.setMessage("Non è stato possibile soddisfare la tua richiesta, riprova più tardi.");
alertDialog.show();
}
break;

case 500:
alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("500 Internal Server Error");
alertDialog.setMessage("Non è stato possibile soddisfare la tua richiesta, riprova più tardi.");
alertDialog.show();
break;

case 503:
alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("503 Service Unavailable");
alertDialog.setMessage("Il server di ....non è al momento disponibile, riprova più tardi.");
alertDialog.show();
break;

case 504:
alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("504 Gateway Timeout");
alertDialog.setMessage("Il server di ....è momentaneamente sovraccarico, riprova più tardi.");
alertDialog.show();
break;

default:
alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("Si è verificato un errore");
alertDialog.setMessage("Errore 001" +"\n"+"Non è stato possibile soddisfare la tua richiesta, riprova più tardi.");
alertDialog.show();
break;
}
}catch(Exception e){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("Si è verificato un errore");
alertDialog.setMessage("Errore 001" + "\n" + "Non è stato possibile soddisfare la tua richesta, riprova più tardi.");
alertDialog.show();
}
return result;
}
}

我试图改变一些方法,但我不知道如何转换一些程序,例如:

setEntity, HttpResponse, StatusLine...

我绝对需要用新的方法更改已弃用的方法,我不能更改所有代码。

编辑 1:例如,在我的 MainActivity 中:

 ReadServer read = new ReadServer();
String result = read.readserver("list_news","homepage");

我的类 ReadServer 输入两个参数:

public String readserver(String id_data, String data){
...
jsonObject.accumulate(id_data, data); // in a jsonObject i put two params
...
}

我做了一个 Http Post,我的数据被发送到我的服务器(我的 php 页面)

$raw = file_get_contents('php://input');
$value = json_decode($raw, true);
$list_news = $value['list_news'];

此时我得到了我的数据,我可以进行查询了:

if (isset($list_news)) {
switch($list_news){
case "homepage":
$q = "SELECT
FROM
WHERE ";

最佳答案

我认为您可以引用我的以下示例代码,然后将其逻辑用于您的应用:

private class POSTRequest extends AsyncTask<Void, Void, String> {

@Override
protected String doInBackground(Void... voids) {
String address = "http://192.16.1.100:24780/api/token";
HttpURLConnection urlConnection;
String requestBody;
Uri.Builder builder = new Uri.Builder();
Map<String, String> stringMap = new HashMap<>();
stringMap.put("grant_type", "password");
stringMap.put("username", "bnk");
stringMap.put("password", "bnkpwd");

Iterator entries = stringMap.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry entry = (Map.Entry) entries.next();
builder.appendQueryParameter(entry.getKey().toString(), entry.getValue().toString());
entries.remove();
}
requestBody = builder.build().getEncodedQuery();

try {
URL url = new URL(address);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
// urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
OutputStream outputStream = new BufferedOutputStream(urlConnection.getOutputStream());
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "utf-8"));
writer.write(requestBody);
writer.flush();
writer.close();
outputStream.close();

JSONObject jsonObject = new JSONObject();
InputStream inputStream;
// get stream
if (urlConnection.getResponseCode() < HttpURLConnection.HTTP_BAD_REQUEST) {
inputStream = urlConnection.getInputStream();
} else {
inputStream = urlConnection.getErrorStream();
}
// parse stream
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String temp, response = "";
while ((temp = bufferedReader.readLine()) != null) {
response += temp;
}
// put into JSONObject
jsonObject.put("Content", response);
jsonObject.put("Message", urlConnection.getResponseMessage());
jsonObject.put("Length", urlConnection.getContentLength());
jsonObject.put("Type", urlConnection.getContentType());

return jsonObject.toString();
} catch (IOException | JSONException e) {
return e.toString();
}
}

@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.i(LOG_TAG, "POST\n" + result);
}
}

更新:

使用您的 PHP 代码,您可以尝试以下更新:

...
JSONObject json = new JSONObject();
json.put("key1", "sample value...");
requestBody = json.toString();
URL url = new URL(address);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type", "application/json");
OutputStream outputStream = new BufferedOutputStream(urlConnection.getOutputStream());
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "utf-8"));
writer.write(requestBody);
writer.flush();
writer.close();
outputStream.close();
...

您可以在 Deprecated HTTP Classes 阅读更多内容.

其他好的方案供大家引用:

希望这对您有所帮助!

关于android - 弃用的方法,我如何用新的方法替换它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33584038/

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