Android连接服务器的API也没几步,测试总是连接不上,还报一些乱七八糟的错误,我的配置文件中也加入网络权限,但是依然还是有问题,我都郁闷
<uses-permission android:name="android.permission.INTERNET" />
最后经过不断的测试,发现只要将本地连接服务器的代码放入一个新的线程中就OK,代码如下
上面是使用URL的方式去连接服务器,下面介绍HttpURLConnection方式连接服务器
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tt = (TextView) this.findViewById(R.id.tv);
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
BufferedReader bufferedReader = null;
try {
URL url = new URL("http://120.25.221.169:3008/");// 根据自己的服务器地址填写
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(10000);
conn.setDoOutput(true);// 允许输出
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Charset", "GBK");
OutputStream os = conn.getOutputStream();
os.write("name=allen".getBytes());
if (conn.getResponseCode() == 200) {
System.out.println(conn.toString());
InputStream is = conn.getInputStream();
InputStreamReader isr = new InputStreamReader(is, "GBK");
bufferedReader = new BufferedReader(isr);
}
String result = "";
String line = "";
if (bufferedReader != null) {
try {
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println(result);
} catch (MalformedURLException e) {
// URL格式错误
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// 不支持你设置的编码
e.printStackTrace();
} catch (ProtocolException e) {
// 请求方式不支持
e.printStackTrace();
} catch (IOException e) {
// 输入输出通讯出错
e.printStackTrace();
}
}
});
thread.start();
}
FR:海涛高软(QQ技术交流群:386476712)