我遇到了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 ;
}
}
有人知道解决方案吗?感谢
答案 0 :(得分:0)
new HttpPost("localhost:3000/api/send");
每个http请求都需要完全限定。也不要使用本地host.Android不会识别你的端点那样。我总是用ngrok向互联网广播。切换到
new HttpPost("http://your_domain");
也切换到retrofit2,它使用java注释来组成其请求。强烈推荐。这是一个很好的链接:https://futurestud.io/tutorials/retrofit-getting-started-and-android-client