无法从网址获取json

时间:2016-07-27 11:17:14

标签: java android json

我必须创建简单的登录页面,输入用户名和密码后,我们点击提交按钮。当我们点击提交按钮然后它进入服务器并检查用户名和其他信息如果信息匹配然后它移动到下一个活动,否则什么也不会发生。下面是我的代码。从服务器获得响应后我不知道该怎么办。

package com.example.dev_1.myapplication;
import android.app.DownloadManager;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.net.Uri
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.lang.ref.ReferenceQueue;
import java.net.HttpURLConnection;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.sql.Connection;
public class MainActivity extends AppCompatActivity {
  Button button;
    String connectionString, params;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final EditText username = (EditText) findViewById(R.id.editText);
        final EditText password = (EditText) findViewById(R.id.editText2);
        Button button = (Button) findViewById(R.id.button1);
        button.setOnClickListener((new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (v.getId() == R.id.button1) {
                    String userNameString = username.getText().toString();
                    String passwordString = password.getText().toString();
                    String url = "http://122.160.78.189:82/androidserver/LoginSalesPerson";
                        String params = null;
                        try {
                        params = "user=" + URLEncoder.encode(userNameString, "UTF-8") + "&password=" + URLEncoder.encode(passwordString, "UTF-8") + "&appVersion=1.26";
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    JSONArray dataJsonArr = null;
                    new Mytask().execute(url, params);
                }
              }
        }));
    }
    private void checkLogin(String result) throws JSONException {
        String url = "http://122.160.78.189:82/androidserver/LoginSalesPerson";
        JSONArray user = null;
        try{
            // Creating new JSON Parser
            ///JSONParser jParser = new JSONParser();
            // Getting JSON from URL
           // JSONObject json = jParser.getJSONFromUrl(url);
            if (result != null)
            {
                //JSONObject emp=(new JSONObject(url).getJSONObject("username"));
            JSONObject emp = new JSONObject(result.toString());
            String username=emp.getString("userName");
            //String  empspassword=emp.getString("password");
                String str="username:"+username;
                Intent intent = new Intent(MainActivity.this, Main2Activity.class);
             intent.putExtra("username", str);
              startActivity(intent);}
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
    //   EditText usernameString = (EditText) findViewById(R.id.editText);
        //  String str = usernameString.getText().toString();
        // if (sharedPreferences.equals(str)) {
        //  Intent intent = new Intent(MainActivity.this, Main2Activity.class);
        //  intent.putExtra("username", str);
//startActivity(intent);
// To retrieve value from shared preference in another activity
        //   sharedPreferences = getApplicationContext().getSharedPreferences(
        //         "sharedPrefName", 0);
        // id = sharedPreferences.getString("key_name", "defaultvalue");
    class Mytask extends AsyncTask<String, Void, String> {
        // Runs in UI before background thread is called
        @Override
        protected void onPreExecute() {
            setProgressBarVisibility(true);
            // Do something like display a progress bar
        }
        // This is run in a background thread
        @Override
        protected String doInBackground(String... params) {
            return getFromServer(params[0], params[1]);
        }
        // This runs in UI when background thread finishes
        @Override
        protected void onPostExecute(String result) {
            try {
                checkLogin(result);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
   public String getFromServer(String connectionString, String params) {
            String response = "";
            try {
                // android.os.Debug.waitForDebugger();
                URL url = new URL(connectionString);
                HttpURLConnection con = (HttpURLConnection) url.openConnection();
                con.setConnectTimeout(10 * 1000); //10 Seconds
                con.setRequestMethod("POST");
                con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                con.setRequestProperty("Content-Length", "" + Integer.toString(params.getBytes().length));
                con.setRequestProperty("Content-Language", "en-US");
                con.setUseCaches(false);
                con.setDoInput(true);
                con.setDoOutput(true);
                DataOutputStream wr = new DataOutputStream(con.getOutputStream());
                wr.writeBytes(params);
                wr.flush();
                wr.close();
                InputStream is = con.getInputStream();
                response = read(is);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                return response;
            }
        }
        private String read(InputStream in) {
            BufferedReader reader;
            StringBuilder response = new StringBuilder();
            try {
                reader = new BufferedReader(new InputStreamReader(in));
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                return response.toString();
            }
        }
    }
}

0 个答案:

没有答案