我遇到了httpclient问题。我调试了应用程序,并在调用execute函数时崩溃。下面的代码:Android:应用程序在AsyncTask中执行httpclient.execute时崩溃
public class MyAsyncTask extends AsyncTask<String, String, String> {
GridView mGridView;
Activity mContex;
public MyAsyncTask(Activity contex) {
this.mContex = contex;
}
@Override
protected String doInBackground(String... params) {
//fetch data
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("localhost:3000/api/send");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("email", params[1]));
nameValuePairs.add(new BasicNameValuePair("name", params[0]));
nameValuePairs.add(new BasicNameValuePair("gender", "male"));
nameValuePairs.add(new BasicNameValuePair("result", "lazy bee"));
nameValuePairs.add(new BasicNameValuePair("age", "28"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
return "success";
}
}
我在这里呼吁MyAsyncTask,从片段和传递活动:
public class SendResultPageFragment extends Fragment implements View.OnClickListener {
EditText name, email;
MyAsyncTask task;
public static SendResultPageFragment newInstance() {
return new SendResultPageFragment();
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_screen_slide_send_result, container, false);
rootView.findViewById(R.id.result_next_button).setOnClickListener(this);
name = (EditText)rootView.findViewById(R.id.name_txt);
email = (EditText)rootView.findViewById(R.id.email_txt);
return rootView;
}
@Override
public void onClick(View view) {
this.task = new MyAsyncTask(getActivity());
this.task.execute(this.name.getText().toString(), this.email.getText().toString());
return ;
}
}
有谁知道解决的办法?谢谢
请提供一些错误消息。 – Remario
'new HttpPost(“localhost:3000/api/send”);'。你忘了协议。所以它应该是'新的HttpPost(“http:// localhost:3000/api/send”);'。但是,除非服务器与您的应用运行在同一台设备上,否则本地主机不会这样做。请告诉你的设置。你想与什么连接。 – greenapps
'调用执行时崩溃'。那么你没有抓到哪个异常? – greenapps