android.os.NetworkOnMainThreadException json requete post


HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://recrutement.stb.com.tn:1010/PlateformeApi_Externe/api/Authorize/");
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList< NameValuePair >(5);
nameValuePairs.add(new BasicNameValuePair("username", "sami"));
nameValuePairs.add(new BasicNameValuePair("password", "stb"));
nameValuePairs.add(new BasicNameValuePair("AuthMethod", "FormsAuthentication"));

try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Log.d("myapp", "works till here. 2");
try {
HttpResponse response = httpclient.execute(httppost);
Log.d("myapp", "response " + response.getEntity());
String responseBody = EntityUtils.toString(response.getEntity());
Toast.makeText(MainActivity.this,"ok"+responseBody,Toast.LENGTH_LONG).show();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}

});

}}

android.os.NetworkOnMainThreadException

将上面的代码放在这样的方法中:

public void callToNetwork(){
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://recrutement.stb.com.tn:1010/PlateformeApi_Externe/api/Authorize/");
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList< NameValuePair >(5);
nameValuePairs.add(new BasicNameValuePair("username", "sami"));
nameValuePairs.add(new BasicNameValuePair("password", "stb"));
nameValuePairs.add(new BasicNameValuePair("AuthMethod", "FormsAuthentication"));

try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Log.d("myapp", "works till here. 2");
try {
HttpResponse response = httpclient.execute(httppost);
Log.d("myapp", "response " + response.getEntity());
String responseBody = EntityUtils.toString(response.getEntity());
Toast.makeText(MainActivity.this,"ok"+responseBody,Toast.LENGTH_LONG).show();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}}}}

创建一个内部类,如下所示:

public class logIn extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... voids) {
callToNetwork();
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
Toast.makeText(getApplicationContext(), "Results from method if    any", Toast.LENGTH_LONG).show();
}
@Override
protected void onPreExecute() {
//Show something on ui like Progress Dialog etc here
super.onPreExecute();
}
}

然后创建一个实例,如下所示:

logIn logIn = new logIn();
logIn.execute();

最新更新