【Android开发那点破事】解决Andriod使用HttpURLConnection 失败问题

在Android的Activity中使用HttpURLConnection连接到服务端时抛出异常,Access denied。第一个想到是权限问题。然后就尝试将INTERNET权限加上:在Manifest中加上:

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

还是抛异常!看异常信息,和StrictMode有关,想到和Android版本有关,然后在Activity中加上如下代码,问题解决:

StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());

完整代码:

package com.example.quhao_test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.annotation.TargetApi;
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {

    @TargetApi(Build.VERSION_CODES.GINGERBREAD)
	@Override
    protected void onCreate(Bundle savedInstanceState) {
    	
    	System.out.println("xxxxxxxxxxxxxxx");
    	
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        String strUrl = "http://146.11.24.100:9081/testcontroller/test1?arg=2222";
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());
        URL url = null;
        try {
			url = new URL(strUrl);
			System.out.println(url.getPort());
			HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
			InputStreamReader in = new InputStreamReader(urlConn.getInputStream());
			BufferedReader br = new BufferedReader(in);
			String result = "";
			String readerLine = null;
			while((readerLine=br.readLine())!=null){
				result += readerLine;
			}
			in.close();
			urlConn.disconnect();
			
			System.out.println("r:"+result);
			TextView textView = (TextView)this.findViewById(R.id.result);
			textView.setText(result);
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    
}

原创文章,转载请指明出处:withiter


更多Android开发的破事,请看专栏:《Android开发那点破事》

你可能感兴趣的:(【Android开发那点破事】解决Andriod使用HttpURLConnection 失败问题)