HttpURLConnection连接服务器失败解决办法
来源:互联网 发布:steam联机游戏mac 编辑:程序博客网 时间:2024/04/29 09:00
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)
0 0
- HttpURLConnection连接服务器失败解决办法
- 织梦上传服务器后-数据连接失败的解决办法
- HttpURLConnection时遇到网络连接失败
- Xftp连接失败,解决办法
- SVN连接服务器失败
- 连接ftp服务器失败
- secureCRT连接服务器失败
- sqlserver2005获取连接失败解决办法
- sqlserver2005获取连接失败解决办法!
- SVN连接失败的解决办法
- R中加载包失败,提示无法连接到服务器时的解决办法
- 服务器ssh升级导致的java程序ssh连接失败解决办法
- Android开发与服务交互过程中,HTTPURLconnection 连接失败
- 通过HttpURLConnection连接服务器,发送报文,获取服务器报文返回
- HttpURLConnection连接
- android使用HttpURLConnection连接java ee服务器传输对象
- java httpURL连接远程服务器并返回数据(httpurlconnection)
- java httpURL连接远程服务器并返回数据(httpurlconnection)
- 利用ToolBar和Drawerlayout实现简单的侧滑菜单
- 抽象
- Glide深入浅出(二)——源码解析
- xcode打包不生成ipa文件而生成文件夹 及 app文件转成ipa
- 鸡仔单片机成长记----------------浅谈51堆栈操作
- HttpURLConnection连接服务器失败解决办法
- pull解析
- JZOJ4753【GDOI2017模拟9.4】种树 LCT维护子树信息+换根时维护Dfs序(CC MONOPLOY加强版)
- 【快速排序】QuickSort
- javascript面向对象-继承
- iOS开发中的对象系统基础
- dpdk多进程示例解读(examples/multi_process/simple_mp)
- Deep Residual Network学习(二)
- 移植u-boot学习笔记6-----修改代码支持nor flash