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
答案 0 :(得分:0)
将您的代码置于上述方法中:
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();