连接到服务器时异常的原因是什么

时间:2015-06-30 05:23:23

标签: android

我正在尝试连接到服务器,但应用程序未连接,我添加了权限

<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

这是url地址(你可以连接到它)

http://justedhak.comlu.com/insert.php

这是错误:

06-30 08:21:15.332: I/System.out(4270): main calls detatch()
06-30 08:21:15.332: E/Fail 1(4270): android.os.NetworkOnMainThreadException
06-30 08:21:15.337: E/Fail 2(4270): java.lang.NullPointerException: lock == null
06-30 08:21:15.337: E/Fail 3(4270): java.lang.NullPointerException
06-30 08:21:16.802: I/System.out(4270): main calls detatch()
06-30 08:21:16.802: E/Fail 1(4270): android.os.NetworkOnMainThreadException
06-30 08:21:16.807: E/Fail 2(4270): java.lang.NullPointerException: lock == null
06-30 08:21:16.807: E/Fail 3(4270): java.lang.NullPointerException

这是我的代码:

public void insert()
{
    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

nameValuePairs.add(new BasicNameValuePair("id",id));
nameValuePairs.add(new BasicNameValuePair("name",name));

    try
    {
    HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://justedhak.comlu.com/insert.php");
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = httpclient.execute(httppost); 
                HttpEntity entity = response.getEntity();
        is = entity.getContent();
        Log.e("pass 1", "connection success ");
}
    catch(Exception e)
{
        Log.e("Fail 1", e.toString());
        Toast.makeText(getApplicationContext(), "Invalid IP Address",
        Toast.LENGTH_LONG).show();
}     

    try
    {
        BufferedReader reader = new BufferedReader
        (new InputStreamReader(is,"iso-8859-1"),8);
        StringBuilder sb = new StringBuilder();
        while ((line = reader.readLine()) != null)
    {
            sb.append(line + "\n");
        }
        is.close();
        result = sb.toString();
    Log.e("pass 2", "connection success ");
}
    catch(Exception e)
{
        Log.e("Fail 2", e.toString());
}     

try
{
        JSONObject json_data = new JSONObject(result);
        code=(json_data.getInt("code"));

        if(code==1)
        {
    Toast.makeText(getBaseContext(), "Inserted Successfully",
        Toast.LENGTH_SHORT).show();
        }
        else
        {
     Toast.makeText(getBaseContext(), "Sorry, Try Again",
        Toast.LENGTH_LONG).show();
        }
}
catch(Exception e)
{
        Log.e("Fail 3", e.toString());
}
}

可能缺少什么?

3 个答案:

答案 0 :(得分:3)

Android UI设计为单个线程(主UI线程)。因此,为了防止UI中断,您无法在UI线程中进行网络调用。

自Androidv2.3(我认为)以来,他们引入了此异常,因此错误的编码实践不会影响整体Android体验。

您必须在单独的线程中进行调用。 Android提供了一个简单的包装器,而不是传统的Java Runnable(或Thread),称为(非常有创意)AsyncTask。这是documentation的链接。 (你可能也想问谷歌叔叔,他知道一切)

一个简短的示例用法(从Android Dev网站无耻地复制):

private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
     protected Long doInBackground(URL... urls) {
         int count = urls.length;
         long totalSize = 0;
         for (int i = 0; i < count; i++) {
             totalSize += Downloader.downloadFile(urls[i]);
             publishProgress((int) ((i / (float) count) * 100));
             // Escape early if cancel() is called
             if (isCancelled()) break;
         }
         return totalSize;
     }

     protected void onProgressUpdate(Integer... progress) {
         setProgressPercent(progress[0]);
     }

     protected void onPostExecute(Long result) {
         showDialog("Downloaded " + result + " bytes");
     }
 }

然后从您的活动电话

 new DownloadFilesTask().execute(url1, url2, url3);

答案 1 :(得分:1)

为此你需要使用Asynchtask或线程。 或者查看以下链接 How to fix android.os.NetworkOnMainThreadException?

答案 2 :(得分:1)

这里你在主线程中调用网络是不允许的。您可以使用两种方式解决此问题

  1. 在AsyncTask的doInBackground中进行网络调用。
  2. 如果您不想使用AsyncTask,请使用严格模式。