An exception, access denied, is thrown when httpurlconnection is used to connect to the server in the android activity. The first thought was about permissions. Then, add the Internet permission to manifest:
<uses-permission android:name="android.permission.INTERNET" />
Or throw an exception! Check the exception information, which is related to strictmode. Think about the Android version, and add the following code in the activity to solve the problem:
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());
Complete code:
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 blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.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; } }
Original article, reprinted please specify the Source: withiter