2017-03-06 78 views
0

我遇到了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 ; 
    } 
} 

有谁知道解决的办法?谢谢

+0

请提供一些错误消息。 – Remario

+0

'new HttpPost(“localhost:3000/api/send”);'。你忘了协议。所以它应该是'新的HttpPost(“http:// localhost:3000/api/send”);'。但是,除非服务器与您的应用运行在同一台设备上,否则本地主机不会这样做。请告诉你的设置。你想与什么连接。 – greenapps

+0

'调用执行时崩溃'。那么你没有抓到哪个异常? – greenapps

回答

0

new HttpPost("localhost:3000/api/send");每个http请求都需要完全限定。也不要使用本地主机.Android不会以这种方式识别您的端点。我总是用ngrok来上网。切换到

new HttpPost("http://your_domain"); 

也切换到retrofit2,它使用java批注来撰写它的请求。强烈推荐。这里是一个伟大的链接开始:https://futurestud.io/tutorials/retrofit-getting-started-and-android-client

+0

非常丰富!不,不! – greenapps

+0

使用ngrok广泛投通隧道 – Remario

+0

非常感谢你 – Messerschmitt