我是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']);
}
答案 0 :(得分:0)
您应该使用不同的线程发送Epoch 1/1
23/718 [..............................] - ETA: 522s - loss: 8.4146
请求而不是主(UI)线程。您只需使用AsyncTask,Here就是一个很好的例子。
或者甚至更好地使用volley或okhttp,因为它们默认情况下异步处理请求。
答案 1 :(得分:0)
requested failed:android.os.networkonmainthreadException
您无法在主线程中运行网络请求。你应该创建新的线程。获取它的最简单方法是使用异步任务https://stackoverflow.com/a/24399320/2717821
但在生产中不建议使用。非常流行的方法是使用RxJava https://github.com/ReactiveX/RxJava
答案 2 :(得分:0)
我已经改变了你的方法(clickbuttonRecieve)并编写了Convertor Method for Convert InputStream to String(ConvertInputStreamToString):
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();
InputStream inputStream = response.getEntity().getContent();
String result = ConvertInputStreamToString(inputStream);
// If the response does not enclose an entity, there is no need
if (result!= null) {
JSONObject jsonget = new JSONObject(result);
if(jsonget.has("msg")){
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();
}
}
private static String ConvertInputStreamToString(InputStream inputStream)
throws NaabException {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputStream));
StringBuilder builder = new StringBuilder();
String line = "";
while ((line = reader.readLine()) != null) {
builder.append(line);
}
return builder.toString();
} catch (IOException e) {
throw new NaabException(e);
} catch (Exception e) {
throw new NaabException(e);
}
}