gpt4 book ai didi

android - HTTP POST 请求 ANDROID 4(在 2.3 中工作)?

转载 作者:太空宇宙 更新时间:2023-11-03 12:11:04 25 4
gpt4 key购买 nike

好吧,事情就是这样,我编写了一个应用程序,它通过 HTTP(发布)请求来自 Web url 的数据,数据使用 JSon 数组返回,我解析这些数组以获得我想要的。

直到使用 android 2.3.x 没有问题,但是当我在 Android 4 中测试它时,它根本不起作用。

这是我的代码:

public boolean testConexio(){

boolean status = false;

String rutaServer = "URL.php";
//Log.e("log_tag", "Ruta server: "+rutaServer);
InputStream is = null;
String result = "";
String temporal;

//Valors a demanar/enviar
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("param1",config.getUserDB())); // parametros POST!
nameValuePairs.add(new BasicNameValuePair("param2",config.getPassDB())); // parametros POST!

//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(rutaServer);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"UTF-8")); // valors POST UTF 8 coded <-- I KNOW! this is the way i need them spanishfag here
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}

//Convierte la respuesta a String
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"),8); // again, spanishfag here
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}

//Parse la respuesta JSon
try{
JSONObject jArray = new JSONObject(result);
temporal = jArray.getString("status");
if(temporal.equals("true")){
status = true;
}
Log.i("log_tag","Status: "+jArray.getString("status"));
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}

return status;
}

谁能告诉我我做错了什么?或者我需要更改的内容,我现在一直在搜索,但我无法让它在 Android 4 上运行。

谢谢!

最佳答案

你需要把它放在一个Async任务中,它不会在3.0的主线程中运行>

使用这个:

public class PostTask extends AsyncTask<Void, String, Boolean> {

@Override
protected Boolean doInBackground(Void... params) {
boolean result = false;

//All your code goes in here

//If you want to do something on the UI use progress update

publishProgress("progress");
return result;
}

protected void onProgressUpdate(String... progress) {
StringBuilder str = new StringBuilder();
for (int i = 1; i < progress.length; i++) {
str.append(progress[i] + " ");
}

}
}

你需要在异步任务之外引用它

PostTask posttask;

那么你需要启动它

posttask = new PostTask();
posttask.execute();

几天前我遇到了完全相同的问题,祝你好运

关于android - HTTP POST 请求 ANDROID 4(在 2.3 中工作)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10245731/

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