使用Web URL登录时出现问题

时间:2015-03-25 12:20:20

标签: android url login android-asynctask

我正在开发一个应用程序,我必须使用网站URL创建登录。我正在做的代码如下。

public class MainActivity extends Activity {

EditText e1,e2;
Button b;
private static final String TAG_SUCCESS = "success";
private static String url_new_user = "http://192.168.2.145/social";

//private ProgressDialog pDialog;

JSONParser jsonParser = new JSONParser();

     @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        e1=(EditText)findViewById(R.id.editText1);
        e2=(EditText)findViewById(R.id.editText2);
        b = (Button)findViewById(R.id.button1);

        b.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                 new CreateNewProduct().execute();

            }
        });

     }

     class CreateNewProduct extends AsyncTask<String, String, String>{

        protected String doInBackground(String... args) {
            String  username = e1.getText().toString();
            String   passwd =  e2.getText().toString();


            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("e1", username));
            params.add(new BasicNameValuePair("e2", passwd));


         // getting JSON Object
            // Note that create product url accepts POST method
            JSONObject json = jsonParser.makeHttpRequest(url_new_user,  "POST", params);

         // check log cat from response
           Log.d("Create Response", json.toString());
           // System.out.println(json);

            // check for success tag
            try {
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    // successfully created a user
                    Intent i = new Intent(getApplicationContext(), Second.class);
                    startActivity(i);

                    // closing this screen
                    finish();
                } else {
                    // failed to create user
                    Log.d("failed to create user", json.toString());

                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }
     }     
    }  

这是我的JSONParser类:

public class JSONParser{

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}

// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
        List<NameValuePair> params) {

    // Making HTTP request
    try {

        // check for request method
        if(method == "POST"){
            // request method is POST
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        }else if(method == "GET"){
            // request method is GET
            DefaultHttpClient httpClient = new DefaultHttpClient();
            String paramString = URLEncodedUtils.format(params, "utf-8");
            url += "?" + paramString;
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }            


    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

}

public JSONObject getJSONFromUrl(final String url) {

    // Making HTTP request
    try {
        // Construct the client and the HTTP request.
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        // Execute the POST request and store the response locally.
        HttpResponse httpResponse = httpClient.execute(httpPost);
        // Extract data from the response.
        HttpEntity httpEntity = httpResponse.getEntity();
        // Open an inputStream with the data content.
        is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        // Create a BufferedReader to parse through the inputStream.
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        // Declare a string builder to help with the parsing.
        StringBuilder sb = new StringBuilder();
        // Declare a string to store the JSON object data in string form.
        String line = null;

        // Build the string until null.
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }

        // Close the input stream.
        is.close();
        // Convert the string builder data to an actual string.
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // Try to parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // Return the JSON Object.
    return jObj;

}

public JSONObject makeHttpRequest(String url_new_user, String method,
        String[] params) {
    // TODO Auto-generated method stub
    return null;
}
}

在此屏幕截图中捕获了我得到的错误:

I am getting error in doInBackground (), perhaps, but dont understand the reason

  

在单词中发布错误日志......

     

03-25 18:15:35.184:E / AndroidRuntime(834):致命异常:AsyncTask#1   03-25 18:15:35.184:E / AndroidRuntime(834):java.lang.RuntimeException:执行doInBackground()时发生错误   03-25 18:15:35.184:E / AndroidRuntime(834):在android.os.AsyncTask $ 3.done(AsyncTask.java:278)   03-25 18:15:35.184:E / AndroidRuntime(834):at java.util.concurrent.FutureTask $ Sync.innerSetException(FutureTask.java:273)   03-25 18:15:35.184:E / AndroidRuntime(834):at java.util.concurrent.FutureTask.setException(FutureTask.java:124)   03-25 18:15:35.184:E / AndroidRuntime(834):at java.util.concurrent.FutureTask $ Sync.innerRun(FutureTask.java:307)   03-25 18:15:35.184:E / AndroidRuntime(834):at java.util.concurrent.FutureTask.run(FutureTask.java:137)   03-25 18:15:35.184:E / AndroidRuntime(834):在android.os.AsyncTask $ SerialExecutor $ 1.run(AsyncTask.java:208)   03-25 18:15:35.184:E / AndroidRuntime(834):at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)   03-25 18:15:35.184:E / AndroidRuntime(834):at java.util.concurrent.ThreadPoolExecutor $ Worker.run(ThreadPoolExecutor.java:569)   03-25 18:15:35.184:E / AndroidRuntime(834):at java.lang.Thread.run(Thread.java:856)   03-25 18:15:35.184:E / AndroidRuntime(834):引起:java.lang.NullPointerException   03-25 18:15:35.184:E / AndroidRuntime(834):at com.project1.MainActivity $ CreateNewProduct.doInBackground(MainActivity.java:73)   03-25 18:15:35.184:E / AndroidRuntime(834):at com.project1.MainActivity $ CreateNewProduct.doInBackground(MainActivity.java:1)   03-25 18:15:35.184:E / AndroidRuntime(834):在android.os.AsyncTask $ 2.call(AsyncTask.java:264)   03-25 18:15:35.184:E / AndroidRuntime(834):at java.util.concurrent.FutureTask $ Sync.innerRun(FutureTask.java:305)   03-25 18:15:35.184:E / AndroidRuntime(834):... 5 more

0 个答案:

没有答案