安桌HttpURLConnection错误解决

解决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 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值