我是 android 新手,我尝试了一个简单的 HTTP Post,我有一个工作但成为你不能在主类中发布的错误消息。经过一些谷歌研究后,我找到了一个替代方案——异步任务——但我无法完全理解为什么这个简单的示例不起作用。
谁能帮我?
先感谢您。
new MyAsyncTask().execute().toString();
}
class MyAsyncTask extends AsyncTask<String, Integer, Double> {
// private ProgressBar pb;
//pb=(ProgressBar);
//pb.setVisibility(View.GONE);
@Override
protected Double doInBackground(String... params) {
postData(params[0]);
return null;
}
protected void onPostExecute(Double result){
// pb.setVisibility(View.GONE);
Toast.makeText(getApplicationContext(), "command sent",
Toast.LENGTH_LONG).show();
}
// protected void onProgressUpdate(Integer... progress){
// pb.setProgress(progress[0]);
//}
public void postData(String valueIWantToSend) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("url(got a real one here)");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("myHttpData", valueIWantToSend));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// Log.i("CATCH Read from server", "error");
} catch (IOException e) {
// Log.i("CATCH Read from server", "error");
}
}
}
11-11 15:08:32.768 357-394/? E/lights:write_int 无法打开 /sys/class >/sec/sec_touchkey/brightness
11-11 15:10:45.503 110-259/? E/SurfaceFlinger﹕SurfaceFlinger translucent=1 >isOpaque=0 isExternalDisplayLayer=0 isExternalBlockLayer0
11-11 15:04:57.643 28774-28790/? E/AndroidRuntime:致命异常:AsyncTask #1 java.lang.RuntimeException:在 java.util.concurrent.FutureTask$Sync 的 android.os.AsyncTask$3.done(AsyncTask.java:299) 处执行 doInBackground() 时发生错误.innerSetException(FutureTask.java:273) 在 java.util.concurrent.FutureTask.setException(FutureTask.java:124) 在 java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307) 在 java.util。 concurrent.FutureTask.run(FutureTask.java:137) at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230) at >java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076) at > java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569) 在 java。lang.Thread.run(Thread.java:856) 引起:java.lang.IllegalStateException:目标主机不能为空,或在>参数中设置。scheme=null,host=null,path=vlothopc.dyndns-home.com/mobile.asp at >org.apache.http.impl.client.DefaultRequestDirector.determineRoute(DefaultRequestDirector.j>ava:591) at >org.apache .http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:293>) 在 >org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555) 在 >org.apache.http.impl。 client.AbstractHttpClient.execute(AbstractHttpClient.java:487) at >org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465) at >com.example.miniapp2.MainActivity$1$MyAsyncTask.postData(MainActivity .java: