尝试建立 Http 连接时应用程序强制关闭

Posted

技术标签:

【中文标题】尝试建立 Http 连接时应用程序强制关闭【英文标题】:App force closing when trying to make Http connection 【发布时间】:2012-10-16 14:26:52 【问题描述】:

这是我的第一个安卓应用。我正在发布我用于 HTTP 连接的代码(不是我的,这是来自一个教程站点)。问题是当我按下下载文本的按钮时,它会显示进度对话框并且应用程序强制关闭。我正在发布代码。

package com.example.httpconnectsample;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class Httpconnectionsample extends Activity 

private Button getImageButton;
private Button getTextButton;
private ProgressDialog progressDialog;  
private Bitmap bitmap = null;
private String text = null;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_httpconnectionsample);

    getImageButton = (Button)findViewById(R.id.Button01);
    getTextButton = (Button)findViewById(R.id.Button02);

    getImageButton.setOnClickListener( new OnClickListener() 

        @Override
        public void onClick(View v) 
            downloadImage("http://www.android.com/media/wallpaper    /gif/android_logo.gif");

        
    );

    getTextButton.setOnClickListener(new OnClickListener() 

        @Override
        public void onClick(View v) 
            downloadText("http://xyz.com")
        
    );



private void downloadImage(String urlStr) 
    progressDialog = ProgressDialog.show(this, "", "Fetching Image...");
    final String url = urlStr;

    new Thread() 
        public void run() 
            InputStream in = null;
            Message msg = Message.obtain();
            msg.what = 1;
            try 
                in = openHttpConnection(url);
                bitmap = BitmapFactory.decodeStream(in);
                Bundle b = new Bundle();
                b.putParcelable("bitmap", bitmap);
                msg.setData(b);
                in.close();
             catch (IOException e1) 
                e1.printStackTrace();
            
            messageHandler.sendMessage(msg);    

        
    .start();



private void downloadText(String urlStr) 
    progressDialog = ProgressDialog.show(this, "", "Fetching Text...");
    final String url = urlStr;

    new Thread () 
        public void run() 
            int BUFFER_SIZE = 2000;
            InputStream in = null;
            Message msg = Message.obtain();
            msg.what=2;
            try 
                in = openHttpConnection(url);

                InputStreamReader isr = new InputStreamReader(in);
                int charRead;
                  text = "";
                  char[] inputBuffer = new char[BUFFER_SIZE];

                      while ((charRead = isr.read(inputBuffer))>0)
                                          
                          //---convert the chars to a String---
                          String readString = 
                              String.copyValueOf(inputBuffer, 0, charRead);                    
                          text += readString;
                          inputBuffer = new char[BUFFER_SIZE];
                      
                     Bundle b = new Bundle();
                        b.putString("text", text);
                        msg.setData(b);
                      in.close();

            catch (IOException e) 
                e.printStackTrace();
            
            messageHandler.sendMessage(msg);
        
    .start();



private InputStream openHttpConnection(String urlStr) 
    InputStream in = null;
    int resCode = -1;

    try 
        URL url = new URL(urlStr);
        URLConnection urlConn = url.openConnection();

        if (!(urlConn instanceof HttpURLConnection)) 
            throw new IOException ("URL is not an Http URL");
        

        HttpURLConnection httpConn = (HttpURLConnection)urlConn;
        httpConn.setAllowUserInteraction(false);
        httpConn.setInstanceFollowRedirects(true);
        httpConn.setRequestMethod("GET");
        httpConn.connect(); 

        resCode = httpConn.getResponseCode();     


        if (resCode == HttpURLConnection.HTTP_OK) 
            in = httpConn.getInputStream();                                 
            

     catch (MalformedURLException e) 
        e.printStackTrace();
     catch (IOException e) 
        e.printStackTrace();
    
    return in;


private Handler messageHandler = new Handler() 

    public void handleMessage(Message msg) 
        super.handleMessage(msg);
        switch (msg.what) 
                /*case 1:
            ImageView img = (ImageView) findViewById(R.id.imageview01);
            img.setImageBitmap((Bitmap)(msg.getData().getParcelable("bitmap")));
            break; */
        case 2:
            TextView text = (TextView) findViewById(R.id.textview01);
            text.setText(msg.getData().getString("text"));
            break;
        
        progressDialog.dismiss();
    
;

以下是我的 XML

   <?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/scrollView1"
    android:layout_
    android:layout_ >

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_
android:layout_ >

<Button
    android:id="@+id/Button02"
    android:layout_
    android:layout_
    android:layout_marginRight="24dp"
    android:text="Button" />

<Button
    android:id="@+id/Button01"
    android:layout_
    android:layout_
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true"
    android:layout_marginRight="56dp"
    android:text="Button" />

<TextView
    android:id="@+id/textview01"
    android:layout_
    android:layout_
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/Button02"
    android:layout_marginTop="39dp"

    tools:context=".Httpconnectionsample" />



</RelativeLayout>
</ScrollView>

以下是日志:-

   10-26 15:22:43.660: D/ddm-heap(23866): Got feature list request
   10-26 15:22:48.930: W/System.err(23866): java.net.SocketException: Permission denied     (maybe missing INTERNET permission)
   10-26 15:22:48.940: W/System.err(23866):     at    org.apache.harmony.luni.platform.OSNetworkSystem.createStreamSocketImpl(Native Method)
   10-26 15:22:48.945: W/System.err(23866):     at org.apache.harmony.luni.platform.OSNetworkSystem.createStreamSocket(OSNetworkSystem.java:187)
   10-26 15:22:48.945: W/System.err(23866):     at org.apache.harmony.luni.net.PlainSocketImpl.create(PlainSocketImpl.java:266)
   10-26 15:22:48.950: W/System.err(23866):     at  java.net.Socket.checkClosedAndCreate(Socket.java:889)
   10-26 15:22:48.950: W/System.err(23866):     at java.net.Socket.connect(Socket.java:1036)
   10-26 15:22:48.950: W/System.err(23866):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.<init>  (HttpConnection.java:62)
  10-26 15:22:48.950: W/System.err(23866):  at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnectionManager$ConnectionPool.getHttpConnection(HttpConnectionManager.java:145)
 10-26 15:22:48.950: W/System.err(23866):   at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnectionManager.getConnection(HttpConnectionManager.java:67)
 10-26 15:22:48.960: W/System.err(23866):   at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnection.getHTTPConnection(HttpURLConnection.java:821)
 10-26 15:22:48.960: W/System.err(23866):   at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:807)
 10-26 15:22:48.965: W/System.err(23866):   at com.example.httpconnectsample.Httpconnectionsample.openHttpConnection(Httpconnectionsample.java:142)
 10-26 15:22:48.965: W/System.err(23866):   at com.example.httpconnectsample.Httpconnectionsample.access$3(Httpconnectionsample.java:126)
 10-26 15:22:48.965: W/System.err(23866):   at com.example.httpconnectsample.Httpconnectionsample$5.run(Httpconnectionsample.java:97)
 10-26 15:22:48.965: W/dalvikvm(23866): threadid=15: thread exiting with uncaught exception (group=0x4001b180)
10-26 15:22:48.995: E/AndroidRuntime(23866): Uncaught handler: thread Thread-8 exiting due to uncaught exception
10-26 15:22:49.090: E/AndroidRuntime(23866): java.lang.NullPointerException
10-26 15:22:49.090: E/AndroidRuntime(23866):    at java.io.Reader.<init>(Reader.java:65)
 10-26 15:22:49.090: E/AndroidRuntime(23866):   at java.io.InputStreamReader.<init>(InputStreamReader.java:65)
10-26 15:22:49.090: E/AndroidRuntime(23866):    at com.example.httpconnectsample.Httpconnectionsample$5.run(Httpconnectionsample.java:99)
10-26 15:22:49.100: I/dalvikvm(23866): threadid=7: reacting to signal 3
10-26 15:22:49.115: I/dalvikvm(23866): Wrote stack trace to '/data/anr/traces.txt'

我尝试寻找修复程序,但不明白为什么会发生这种情况。我只需要下载文本,所以目前我忽略了此代码的下载图像部分。另外,我补充说 使用权限 android:name="android.permission.INTERNET" 就在清单上方,但仍然显示权限被拒绝。 如有任何帮助,我将不胜感激。

【问题讨论】:

发布你的 androidmanifest.xml 文件 【参考方案1】:

将INTERNET 权限添加到您的清单文件。

你必须添加这一行:

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

在你的 AndroidManifest.xml 中的应用标签之外,如下所示

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.demo"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk android:minSdkVersion="15" /> 

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

<application>
    //your stuffs
</application>

</manifest>

【讨论】:

他已经提到manifest中添加了权限 可能他没有在适当的位置添加权限。 感谢大家的回复,但似乎我在一件小事上浪费了几个小时。我在“uses-sdk”标签中写了这个“使用权限标签”。我现在已经从那里删除了互联网许可标签,现在代码正在运行。非常感谢您的回复。 :)

以上是关于尝试建立 Http 连接时应用程序强制关闭的主要内容,如果未能解决你的问题,请参考以下文章

WSA UDP 套接字无法重用,因为它强制关闭连接

页面加载时获取“现有连接被远程主机强制关闭”,但重新加载时没有

Android:尝试从 URI 播放视频时应用程序强制关闭

如何模拟强制关闭的 TCP 连接?

启动 ListView 类时应用程序强制关闭

应用程序强制关闭 - OutOfMemoryError