Web Services 如何解决Android中的异常

7hiiyaii  于 2023-04-21  发布在  Android
关注(0)|答案(3)|浏览(157)

我在android中编写了HttpDelete来调用REST Web服务。

public void onCreate(Bundle savedInstanceState)
    {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    TextView txt = (TextView) findViewById(R.id.textView1);
    txt.setText(getInputStreamFromUrl("http://192.168.37.241:8080/kyaw/k"));
    }

    public static String getInputStreamFromUrl(String url) {
          InputStream content = null;
          HttpResponse response = null;
          try {

            DefaultHttpClient httpclient = new DefaultHttpClient();             
            HttpDelete delete=new HttpDelete(url);
            put.setHeader("Content-Type","application/vnd.org.snia.cdmi.container");
            response = httpclient.execute(delete);
            content = response.getEntity().getContent();
          }catch (Exception e) {
            Log.e("[DELETE REQUEST]", "Network exception");
          }
            String result=response.getStatusLine().toString()+"\n"+response.getHeaders(url);
            return result;
        }

我得到一个例外

05-23 08:30:16.868: ERROR/[DELETE REQUEST](1197): Network exception
05-23 08:30:16.868: DEBUG/AndroidRuntime(1197): Shutting down VM
05-23 08:30:16.878: WARN/dalvikvm(1197): threadid=1: thread exiting with uncaught exception (group=0x40015560)
05-23 08:30:16.908: ERROR/AndroidRuntime(1197): FATAL EXCEPTION: main
05-23 08:30:16.908: ERROR/AndroidRuntime(1197): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.test/com.test.putandroid}: java.lang.NullPointerException

有人知道为什么吗?

dz6r00yl

dz6r00yl1#

你检查过清单文件的互联网权限了吗?

uwopmtnx

uwopmtnx2#

还不知道网络异常,但最后一个NPE很可能是因为前一个异常是在response通过httpclient.execute(delete)初始化之前抛出的。
您应该重写catch块,并将捕获到的异常的名称和消息写入日志。

cgfeq70w

cgfeq70w3#

在第4行的onCreate()函数中,我们发现在初始化TextView之后,您正在尝试设置一个值。
必须使用Handler对象,因为在单独的线程中无法更新UI对象。
这里是一些链接为您的帮助
https://web.archive.org/web/20200810154212/http://www.tutorialforandroid.com/2009/01/using-handler-in-android.html
https://web.archive.org/web/20130306131310/http://thedevelopersinfo.com/?p=150

相关问题