【发布时间】:2017-03-16 11:58:31
【问题描述】:
我是 android 新手,我知道这个问题以前问过很多次,但我找不到适合我的情况的解决方案。我想将password 和username 发送到服务器并检查它。它返回 JSON 对象,我检查对象的值是零还是一。问题是在 catch 中获取消息
请求失败:android.os.networkonmainthreadException
这是我的代码
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_loginpage);
editTextUserName = (EditText) findViewById(R.id.user);
editTextPassword = (EditText) findViewById(R.id.password);
message=(TextView) findViewById(R.id.mess);
String username = editTextUserName.getText().toString();
String password = editTextPassword.getText().toString();
Button send =(Button)findViewById(R.id.send);
send.setOnClickListener(
new View.OnClickListener(){
@Override
public void onClick(View view) {
// invokeLogin();
clickbuttonRecieve();
}
}
);
}
public void clickbuttonRecieve() {
try {
JSONObject json = new JSONObject();
String username = editTextUserName.getText().toString();
String password = editTextPassword.getText().toString();
json.put("userName",username);
json.put("password", password);
int timeconnection=3000;
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams,
timeconnection);
HttpConnectionParams.setSoTimeout(httpParams, timeconnection);
HttpClient client = new DefaultHttpClient(httpParams);
//
//String url = "http://10.0.2.2:8080/sample1/webservice2.php?" +
// "json={\"UserName\":1,\"FullName\":2}";
String url = "http://phone.tmsline.com/checkuser";
HttpPost request = new HttpPost(url);
request.setEntity(new ByteArrayEntity(json.toString().getBytes(
"UTF8")));
request.setHeader("json", json.toString());
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
// If the response does not enclose an entity, there is no need
if (entity != null) {
JSONObject jsonget = new JSONObject();
String login = jsonget.getString("msg");
if (login.toString().equalsIgnoreCase("1")){
Toast.makeText(this, "Request success: " + login,
Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(this, "Request failed: " + login,
Toast.LENGTH_LONG).show();
}
}
} catch (Throwable t) {
Toast.makeText(this, "Request failed: " + t.toString(),
Toast.LENGTH_LONG).show();
}
}
php 代码(注意:php 代码不是我写的,其他人负责或者那个)
public function check_user(Request $request){
$username = $request->username;
$password = $request->password;
if (Auth::attempt(['username' => $username, 'password' => $password])) {
// return view('test',['user'=>$username]);
return response()->json(['msg','1']);
}
return response()->json(['msg','0']);
}
【问题讨论】:
-
使用
AsyncTask做网络相关的动作 -
在 Android 中使用 Retrofit2 或 Volley 进行网络调用。