【问题标题】:Check user name and password using JSON使用 JSON 检查用户名和密码
【发布时间】:2017-03-16 11:58:31
【问题描述】:

我是 android 新手,我知道这个问题以前问过很多次,但我找不到适合我的情况的解决方案。我想将passwordusername 发送到服务器并检查它。它返回 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 进行网络调用。

标签: php android json server


【解决方案1】:

您应该使用不同的线程来发送HTTP 请求,而不是在主 (UI) 线程上。您可以简单地使用AsyncTaskHere 就是很好的例子。 或者甚至更好地使用volleyokhttp,因为它们默认异步处理请求。

【讨论】:

    【解决方案2】:

    requested failed:android.os.networkonmainthreadException

    您不能在主线程中运行网络请求。您应该创建新线程。最简单的方法是使用 Async Task https://stackoverflow.com/a/24399320/2717821

    但在生产中不建议这样做。非常流行的方法是使用 RxJava https://github.com/ReactiveX/RxJava

    【讨论】:

      【解决方案3】:

      我已经改变了你的方法(clickbuttonRecieve)并写了Converter 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);
          }
      
      }
      

      【讨论】:

        猜你喜欢
        • 2017-11-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-12
        • 2013-02-06
        • 2016-09-24
        • 2013-02-21
        相关资源
        最近更新 更多