您的位置:首页 > 理论基础 > 计算机网络

HttpURLConnection连接服务器失败解决办法

2016-09-08 19:20 543 查看
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)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android
相关文章推荐