开发者社区> 问答> 正文

一段程序在java中可以运行但是放到android中却无法运行 有关HttpU?报错

程序代码如下在java中可以运行但是将这段代码放入到android按钮的监听器中却不能得到结果二姐并没有报错

public class MainActivity extends Activity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.www);
  System.out.println("1111111112222222222222");
  Button b = (Button)findViewById(R.id.button1);
  b.setOnClickListener(new OnClickListener(){

   @Override
   public void onClick(View arg0) {
    // TODO Auto-generated method stub
    try{
    String surl = "http://210.47.163.27:9001/loginAction.do"; 
     
    /**
     * 首先要和URL下的URLConnection对话。 URLConnection可以很容易的从URL得到。比如: // Using
     * java.net.URL and //java.net.URLConnection
     */ 
    URL url = new URL(surl); 
    HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
     
    /**
    12. * 然后把连接设为输出模式。URLConnection通常作为输入来使用,比如下载一个Web页。
    13. * 通过把URLConnection设为输出,你可以把数据向你个Web页传送。下面是如何做:
    14. */ 
    connection.setDoOutput(true); 
    /**
     * 最后,为了得到OutputStream,简单起见,把它约束在Writer并且放入POST信息中,例如: ...
     */ 
    OutputStreamWriter out = new OutputStreamWriter(connection 
            .getOutputStream(), "GBK");  
               
    out.write("zjh=155140031&mm=1"); // post的关键所在! 
    // remember to clean up 
    out.flush(); 
    out.close(); 
      System.out.println("wwqqww");
    // 取得cookie,相当于记录了身份,供下次访问时使用 
    String cookieVal = connection.getHeaderField("Set-Cookie"); 
    
                 String s = "http://210.47.163.27:9001/bxqcjcxAction.do?totalrows=&pageSize=40"; 
    //重新打开一个连接 
                  url = new URL(s); 
    HttpURLConnection resumeConnection = (HttpURLConnection) url
            .openConnection(); 
    if (cookieVal != null) { 
                          //发送cookie信息上去,以表明自己的身份,否则会被认为没有权限 
        resumeConnection.setRequestProperty("Cookie", cookieVal); 
    } 
    resumeConnection.connect();
   
    InputStream urlStream = resumeConnection.getInputStream(); 
    BufferedReader bufferedReader = new BufferedReader( 
            new InputStreamReader(urlStream)); 
    String ss = null; 
    String total = ""; 
    while ((ss = bufferedReader.readLine()) != null) { 
        total += ss; 
    } 
    System.out.println(total);
   }
  catch(Exception e){
   e.printStackTrace();
  }
  }});
 }

请指教啊 万分感激

展开
收起
爱吃鱼的程序员 2020-06-22 17:16:13 535 0
1 条回答
写回答
取消 提交回答
  • https://developer.aliyun.com/profile/5yerqm5bn5yqg?spm=a2c6h.12873639.0.0.6eae304abcjaIB

    老生常谈的问题,为什么你不自己看看错误日志呢?

    网络访问权限/在UI线程访问网络

    回复 @yimi199010:不好意思最近开学回学校又有全运会,今天才看到您的评论,我来试试,非常感谢您的回答,可以和您交个朋友吗回复 @_huang:3.0以上不能在主线程访问网络。最简单的方法就是thread+handler可是我已经添加访问网络的权限了啊<uses-permissionandroid:name="android.permission.INTERNET"/>
    2020-06-22 17:16:32
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
58同城Android客户端Walle框架演进与实践之路 立即下载
Android组件化实现 立即下载
蚂蚁聚宝Android秒级编译——Freeline 立即下载